ActivityManagerService.java revision 95465200b0f652c48d40ca1028238763dd647900
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.ApplicationThreadNative;
37import android.app.IActivityContainer;
38import android.app.IActivityContainerCallback;
39import android.app.IAppTask;
40import android.app.ProfilerInfo;
41import android.app.admin.DevicePolicyManager;
42import android.app.usage.UsageEvents;
43import android.app.usage.UsageStatsManagerInternal;
44import android.appwidget.AppWidgetManager;
45import android.content.res.Resources;
46import android.graphics.Bitmap;
47import android.graphics.Point;
48import android.graphics.Rect;
49import android.os.BatteryStats;
50import android.os.PersistableBundle;
51import android.service.voice.IVoiceInteractionSession;
52import android.util.ArrayMap;
53import android.util.ArraySet;
54import android.util.SparseIntArray;
55
56import com.android.internal.R;
57import com.android.internal.annotations.GuardedBy;
58import com.android.internal.app.IAppOpsService;
59import com.android.internal.app.IVoiceInteractor;
60import com.android.internal.app.ProcessMap;
61import com.android.internal.app.ProcessStats;
62import com.android.internal.content.PackageMonitor;
63import com.android.internal.os.BackgroundThread;
64import com.android.internal.os.BatteryStatsImpl;
65import com.android.internal.os.ProcessCpuTracker;
66import com.android.internal.os.TransferPipe;
67import com.android.internal.os.Zygote;
68import com.android.internal.util.FastPrintWriter;
69import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.MemInfoReader;
71import com.android.internal.util.Preconditions;
72import com.android.server.AppOpsService;
73import com.android.server.AttributeCache;
74import com.android.server.IntentResolver;
75import com.android.server.LocalServices;
76import com.android.server.ServiceThread;
77import com.android.server.SystemService;
78import com.android.server.SystemServiceManager;
79import com.android.server.Watchdog;
80import com.android.server.am.ActivityStack.ActivityState;
81import com.android.server.firewall.IntentFirewall;
82import com.android.server.pm.UserManagerService;
83import com.android.server.wm.AppTransition;
84import com.android.server.wm.WindowManagerService;
85import com.google.android.collect.Lists;
86import com.google.android.collect.Maps;
87
88import libcore.io.IoUtils;
89
90import org.xmlpull.v1.XmlPullParser;
91import org.xmlpull.v1.XmlPullParserException;
92import org.xmlpull.v1.XmlSerializer;
93
94import android.app.Activity;
95import android.app.ActivityManager;
96import android.app.ActivityManager.RunningTaskInfo;
97import android.app.ActivityManager.StackInfo;
98import android.app.ActivityManagerInternal;
99import android.app.ActivityManagerNative;
100import android.app.ActivityOptions;
101import android.app.ActivityThread;
102import android.app.AlertDialog;
103import android.app.AppGlobals;
104import android.app.ApplicationErrorReport;
105import android.app.Dialog;
106import android.app.IActivityController;
107import android.app.IApplicationThread;
108import android.app.IInstrumentationWatcher;
109import android.app.INotificationManager;
110import android.app.IProcessObserver;
111import android.app.IServiceConnection;
112import android.app.IStopUserCallback;
113import android.app.IUiAutomationConnection;
114import android.app.IUserSwitchObserver;
115import android.app.Instrumentation;
116import android.app.Notification;
117import android.app.NotificationManager;
118import android.app.PendingIntent;
119import android.app.backup.IBackupManager;
120import android.content.ActivityNotFoundException;
121import android.content.BroadcastReceiver;
122import android.content.ClipData;
123import android.content.ComponentCallbacks2;
124import android.content.ComponentName;
125import android.content.ContentProvider;
126import android.content.ContentResolver;
127import android.content.Context;
128import android.content.DialogInterface;
129import android.content.IContentProvider;
130import android.content.IIntentReceiver;
131import android.content.IIntentSender;
132import android.content.Intent;
133import android.content.IntentFilter;
134import android.content.IntentSender;
135import android.content.pm.ActivityInfo;
136import android.content.pm.ApplicationInfo;
137import android.content.pm.ConfigurationInfo;
138import android.content.pm.IPackageDataObserver;
139import android.content.pm.IPackageManager;
140import android.content.pm.InstrumentationInfo;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageManager;
143import android.content.pm.ParceledListSlice;
144import android.content.pm.UserInfo;
145import android.content.pm.PackageManager.NameNotFoundException;
146import android.content.pm.PathPermission;
147import android.content.pm.ProviderInfo;
148import android.content.pm.ResolveInfo;
149import android.content.pm.ServiceInfo;
150import android.content.res.CompatibilityInfo;
151import android.content.res.Configuration;
152import android.net.Proxy;
153import android.net.ProxyInfo;
154import android.net.Uri;
155import android.os.Binder;
156import android.os.Build;
157import android.os.Bundle;
158import android.os.Debug;
159import android.os.DropBoxManager;
160import android.os.Environment;
161import android.os.FactoryTest;
162import android.os.FileObserver;
163import android.os.FileUtils;
164import android.os.Handler;
165import android.os.IBinder;
166import android.os.IPermissionController;
167import android.os.IRemoteCallback;
168import android.os.IUserManager;
169import android.os.Looper;
170import android.os.Message;
171import android.os.Parcel;
172import android.os.ParcelFileDescriptor;
173import android.os.Process;
174import android.os.RemoteCallbackList;
175import android.os.RemoteException;
176import android.os.SELinux;
177import android.os.ServiceManager;
178import android.os.StrictMode;
179import android.os.SystemClock;
180import android.os.SystemProperties;
181import android.os.UpdateLock;
182import android.os.UserHandle;
183import android.os.UserManager;
184import android.provider.Settings;
185import android.text.format.DateUtils;
186import android.text.format.Time;
187import android.util.AtomicFile;
188import android.util.EventLog;
189import android.util.Log;
190import android.util.Pair;
191import android.util.PrintWriterPrinter;
192import android.util.Slog;
193import android.util.SparseArray;
194import android.util.TimeUtils;
195import android.util.Xml;
196import android.view.Gravity;
197import android.view.LayoutInflater;
198import android.view.View;
199import android.view.WindowManager;
200import dalvik.system.VMRuntime;
201
202import java.io.BufferedInputStream;
203import java.io.BufferedOutputStream;
204import java.io.DataInputStream;
205import java.io.DataOutputStream;
206import java.io.File;
207import java.io.FileDescriptor;
208import java.io.FileInputStream;
209import java.io.FileNotFoundException;
210import java.io.FileOutputStream;
211import java.io.IOException;
212import java.io.InputStreamReader;
213import java.io.PrintWriter;
214import java.io.StringWriter;
215import java.lang.ref.WeakReference;
216import java.util.ArrayList;
217import java.util.Arrays;
218import java.util.Collections;
219import java.util.Comparator;
220import java.util.HashMap;
221import java.util.HashSet;
222import java.util.Iterator;
223import java.util.List;
224import java.util.Locale;
225import java.util.Map;
226import java.util.Set;
227import java.util.concurrent.atomic.AtomicBoolean;
228import java.util.concurrent.atomic.AtomicLong;
229
230public final class ActivityManagerService extends ActivityManagerNative
231        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
232
233    private static final String USER_DATA_DIR = "/data/user/";
234    // File that stores last updated system version and called preboot receivers
235    static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat";
236
237    static final String TAG = "ActivityManager";
238    static final String TAG_MU = "ActivityManagerServiceMU";
239    static final boolean DEBUG = false;
240    static final boolean localLOGV = DEBUG;
241    static final boolean DEBUG_BACKUP = localLOGV || false;
242    static final boolean DEBUG_BROADCAST = localLOGV || false;
243    static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
244    static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
245    static final boolean DEBUG_CLEANUP = localLOGV || false;
246    static final boolean DEBUG_CONFIGURATION = localLOGV || false;
247    static final boolean DEBUG_FOCUS = false;
248    static final boolean DEBUG_IMMERSIVE = localLOGV || false;
249    static final boolean DEBUG_MU = localLOGV || false;
250    static final boolean DEBUG_OOM_ADJ = localLOGV || false;
251    static final boolean DEBUG_LRU = localLOGV || false;
252    static final boolean DEBUG_PAUSE = localLOGV || false;
253    static final boolean DEBUG_POWER = localLOGV || false;
254    static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
255    static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
256    static final boolean DEBUG_PROCESSES = localLOGV || false;
257    static final boolean DEBUG_PROVIDER = localLOGV || false;
258    static final boolean DEBUG_RESULTS = localLOGV || false;
259    static final boolean DEBUG_SERVICE = localLOGV || false;
260    static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
261    static final boolean DEBUG_STACK = localLOGV || false;
262    static final boolean DEBUG_SWITCH = localLOGV || false;
263    static final boolean DEBUG_TASKS = localLOGV || false;
264    static final boolean DEBUG_THUMBNAILS = localLOGV || false;
265    static final boolean DEBUG_TRANSITION = localLOGV || false;
266    static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
267    static final boolean DEBUG_USER_LEAVING = localLOGV || false;
268    static final boolean DEBUG_VISBILITY = localLOGV || false;
269    static final boolean DEBUG_PSS = localLOGV || false;
270    static final boolean DEBUG_LOCKSCREEN = localLOGV || false;
271    static final boolean DEBUG_RECENTS = localLOGV || false;
272    static final boolean VALIDATE_TOKENS = false;
273    static final boolean SHOW_ACTIVITY_START_TIME = true;
274
275    // Control over CPU and battery monitoring.
276    static final long BATTERY_STATS_TIME = 30*60*1000;      // write battery stats every 30 minutes.
277    static final boolean MONITOR_CPU_USAGE = true;
278    static final long MONITOR_CPU_MIN_TIME = 5*1000;        // don't sample cpu less than every 5 seconds.
279    static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;    // wait possibly forever for next cpu sample.
280    static final boolean MONITOR_THREAD_CPU_USAGE = false;
281
282    // The flags that are set for all calls we make to the package manager.
283    static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
284
285    private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
286
287    static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
288
289    // Maximum number recent bitmaps to keep in memory.
290    static final int MAX_RECENT_BITMAPS = 5;
291
292    // Amount of time after a call to stopAppSwitches() during which we will
293    // prevent further untrusted switches from happening.
294    static final long APP_SWITCH_DELAY_TIME = 5*1000;
295
296    // How long we wait for a launched process to attach to the activity manager
297    // before we decide it's never going to come up for real.
298    static final int PROC_START_TIMEOUT = 10*1000;
299
300    // How long we wait for a launched process to attach to the activity manager
301    // before we decide it's never going to come up for real, when the process was
302    // started with a wrapper for instrumentation (such as Valgrind) because it
303    // could take much longer than usual.
304    static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
305
306    // How long to wait after going idle before forcing apps to GC.
307    static final int GC_TIMEOUT = 5*1000;
308
309    // The minimum amount of time between successive GC requests for a process.
310    static final int GC_MIN_INTERVAL = 60*1000;
311
312    // The minimum amount of time between successive PSS requests for a process.
313    static final int FULL_PSS_MIN_INTERVAL = 10*60*1000;
314
315    // The minimum amount of time between successive PSS requests for a process
316    // when the request is due to the memory state being lowered.
317    static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000;
318
319    // The rate at which we check for apps using excessive power -- 15 mins.
320    static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
321
322    // The minimum sample duration we will allow before deciding we have
323    // enough data on wake locks to start killing things.
324    static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
325
326    // The minimum sample duration we will allow before deciding we have
327    // enough data on CPU usage to start killing things.
328    static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
329
330    // How long we allow a receiver to run before giving up on it.
331    static final int BROADCAST_FG_TIMEOUT = 10*1000;
332    static final int BROADCAST_BG_TIMEOUT = 60*1000;
333
334    // How long we wait until we timeout on key dispatching.
335    static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
336
337    // How long we wait until we timeout on key dispatching during instrumentation.
338    static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
339
340    // Amount of time we wait for observers to handle a user switch before
341    // giving up on them and unfreezing the screen.
342    static final int USER_SWITCH_TIMEOUT = 2*1000;
343
344    // Maximum number of users we allow to be running at a time.
345    static final int MAX_RUNNING_USERS = 3;
346
347    // How long to wait in getAssistContextExtras for the activity and foreground services
348    // to respond with the result.
349    static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
350
351    // Maximum number of persisted Uri grants a package is allowed
352    static final int MAX_PERSISTED_URI_GRANTS = 128;
353
354    static final int MY_PID = Process.myPid();
355
356    static final String[] EMPTY_STRING_ARRAY = new String[0];
357
358    // How many bytes to write into the dropbox log before truncating
359    static final int DROPBOX_MAX_SIZE = 256 * 1024;
360
361    // Access modes for handleIncomingUser.
362    static final int ALLOW_NON_FULL = 0;
363    static final int ALLOW_NON_FULL_IN_PROFILE = 1;
364    static final int ALLOW_FULL_ONLY = 2;
365
366    static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000;
367
368    /** All system services */
369    SystemServiceManager mSystemServiceManager;
370
371    /** Run all ActivityStacks through this */
372    ActivityStackSupervisor mStackSupervisor;
373
374    public IntentFirewall mIntentFirewall;
375
376    // Whether we should show our dialogs (ANR, crash, etc) or just perform their
377    // default actuion automatically.  Important for devices without direct input
378    // devices.
379    private boolean mShowDialogs = true;
380
381    BroadcastQueue mFgBroadcastQueue;
382    BroadcastQueue mBgBroadcastQueue;
383    // Convenient for easy iteration over the queues. Foreground is first
384    // so that dispatch of foreground broadcasts gets precedence.
385    final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
386
387    BroadcastQueue broadcastQueueForIntent(Intent intent) {
388        final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
389        if (DEBUG_BACKGROUND_BROADCAST) {
390            Slog.i(TAG, "Broadcast intent " + intent + " on "
391                    + (isFg ? "foreground" : "background")
392                    + " queue");
393        }
394        return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
395    }
396
397    BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
398        for (BroadcastQueue queue : mBroadcastQueues) {
399            BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
400            if (r != null) {
401                return r;
402            }
403        }
404        return null;
405    }
406
407    /**
408     * Activity we have told the window manager to have key focus.
409     */
410    ActivityRecord mFocusedActivity = null;
411
412    /**
413     * List of intents that were used to start the most recent tasks.
414     */
415    ArrayList<TaskRecord> mRecentTasks;
416    ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>();
417
418    /**
419     * For addAppTask: cached of the last activity component that was added.
420     */
421    ComponentName mLastAddedTaskComponent;
422
423    /**
424     * For addAppTask: cached of the last activity uid that was added.
425     */
426    int mLastAddedTaskUid;
427
428    /**
429     * For addAppTask: cached of the last ActivityInfo that was added.
430     */
431    ActivityInfo mLastAddedTaskActivity;
432
433    public class PendingAssistExtras extends Binder implements Runnable {
434        public final ActivityRecord activity;
435        public boolean haveResult = false;
436        public Bundle result = null;
437        public PendingAssistExtras(ActivityRecord _activity) {
438            activity = _activity;
439        }
440        @Override
441        public void run() {
442            Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
443            synchronized (this) {
444                haveResult = true;
445                notifyAll();
446            }
447        }
448    }
449
450    final ArrayList<PendingAssistExtras> mPendingAssistExtras
451            = new ArrayList<PendingAssistExtras>();
452
453    /**
454     * Process management.
455     */
456    final ProcessList mProcessList = new ProcessList();
457
458    /**
459     * All of the applications we currently have running organized by name.
460     * The keys are strings of the application package name (as
461     * returned by the package manager), and the keys are ApplicationRecord
462     * objects.
463     */
464    final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
465
466    /**
467     * Tracking long-term execution of processes to look for abuse and other
468     * bad app behavior.
469     */
470    final ProcessStatsService mProcessStats;
471
472    /**
473     * The currently running isolated processes.
474     */
475    final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
476
477    /**
478     * Counter for assigning isolated process uids, to avoid frequently reusing the
479     * same ones.
480     */
481    int mNextIsolatedProcessUid = 0;
482
483    /**
484     * The currently running heavy-weight process, if any.
485     */
486    ProcessRecord mHeavyWeightProcess = null;
487
488    /**
489     * The last time that various processes have crashed.
490     */
491    final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
492
493    /**
494     * Information about a process that is currently marked as bad.
495     */
496    static final class BadProcessInfo {
497        BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
498            this.time = time;
499            this.shortMsg = shortMsg;
500            this.longMsg = longMsg;
501            this.stack = stack;
502        }
503
504        final long time;
505        final String shortMsg;
506        final String longMsg;
507        final String stack;
508    }
509
510    /**
511     * Set of applications that we consider to be bad, and will reject
512     * incoming broadcasts from (which the user has no control over).
513     * Processes are added to this set when they have crashed twice within
514     * a minimum amount of time; they are removed from it when they are
515     * later restarted (hopefully due to some user action).  The value is the
516     * time it was added to the list.
517     */
518    final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>();
519
520    /**
521     * All of the processes we currently have running organized by pid.
522     * The keys are the pid running the application.
523     *
524     * <p>NOTE: This object is protected by its own lock, NOT the global
525     * activity manager lock!
526     */
527    final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
528
529    /**
530     * All of the processes that have been forced to be foreground.  The key
531     * is the pid of the caller who requested it (we hold a death
532     * link on it).
533     */
534    abstract class ForegroundToken implements IBinder.DeathRecipient {
535        int pid;
536        IBinder token;
537    }
538    final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>();
539
540    /**
541     * List of records for processes that someone had tried to start before the
542     * system was ready.  We don't start them at that point, but ensure they
543     * are started by the time booting is complete.
544     */
545    final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
546
547    /**
548     * List of persistent applications that are in the process
549     * of being started.
550     */
551    final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
552
553    /**
554     * Processes that are being forcibly torn down.
555     */
556    final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>();
557
558    /**
559     * List of running applications, sorted by recent usage.
560     * The first entry in the list is the least recently used.
561     */
562    final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();
563
564    /**
565     * Where in mLruProcesses that the processes hosting activities start.
566     */
567    int mLruProcessActivityStart = 0;
568
569    /**
570     * Where in mLruProcesses that the processes hosting services start.
571     * This is after (lower index) than mLruProcessesActivityStart.
572     */
573    int mLruProcessServiceStart = 0;
574
575    /**
576     * List of processes that should gc as soon as things are idle.
577     */
578    final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
579
580    /**
581     * Processes we want to collect PSS data from.
582     */
583    final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
584
585    /**
586     * Last time we requested PSS data of all processes.
587     */
588    long mLastFullPssTime = SystemClock.uptimeMillis();
589
590    /**
591     * If set, the next time we collect PSS data we should do a full collection
592     * with data from native processes and the kernel.
593     */
594    boolean mFullPssPending = false;
595
596    /**
597     * This is the process holding what we currently consider to be
598     * the "home" activity.
599     */
600    ProcessRecord mHomeProcess;
601
602    /**
603     * This is the process holding the activity the user last visited that
604     * is in a different process from the one they are currently in.
605     */
606    ProcessRecord mPreviousProcess;
607
608    /**
609     * The time at which the previous process was last visible.
610     */
611    long mPreviousProcessVisibleTime;
612
613    /**
614     * Which uses have been started, so are allowed to run code.
615     */
616    final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
617
618    /**
619     * LRU list of history of current users.  Most recently current is at the end.
620     */
621    final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
622
623    /**
624     * Constant array of the users that are currently started.
625     */
626    int[] mStartedUserArray = new int[] { 0 };
627
628    /**
629     * Registered observers of the user switching mechanics.
630     */
631    final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
632            = new RemoteCallbackList<IUserSwitchObserver>();
633
634    /**
635     * Currently active user switch.
636     */
637    Object mCurUserSwitchCallback;
638
639    /**
640     * Packages that the user has asked to have run in screen size
641     * compatibility mode instead of filling the screen.
642     */
643    final CompatModePackages mCompatModePackages;
644
645    /**
646     * Set of IntentSenderRecord objects that are currently active.
647     */
648    final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
649            = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
650
651    /**
652     * Fingerprints (hashCode()) of stack traces that we've
653     * already logged DropBox entries for.  Guarded by itself.  If
654     * something (rogue user app) forces this over
655     * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
656     */
657    private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
658    private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
659
660    /**
661     * Strict Mode background batched logging state.
662     *
663     * The string buffer is guarded by itself, and its lock is also
664     * used to determine if another batched write is already
665     * in-flight.
666     */
667    private final StringBuilder mStrictModeBuffer = new StringBuilder();
668
669    /**
670     * Keeps track of all IIntentReceivers that have been registered for
671     * broadcasts.  Hash keys are the receiver IBinder, hash value is
672     * a ReceiverList.
673     */
674    final HashMap<IBinder, ReceiverList> mRegisteredReceivers =
675            new HashMap<IBinder, ReceiverList>();
676
677    /**
678     * Resolver for broadcast intents to registered receivers.
679     * Holds BroadcastFilter (subclass of IntentFilter).
680     */
681    final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
682            = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
683        @Override
684        protected boolean allowFilterResult(
685                BroadcastFilter filter, List<BroadcastFilter> dest) {
686            IBinder target = filter.receiverList.receiver.asBinder();
687            for (int i=dest.size()-1; i>=0; i--) {
688                if (dest.get(i).receiverList.receiver.asBinder() == target) {
689                    return false;
690                }
691            }
692            return true;
693        }
694
695        @Override
696        protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
697            if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
698                    || userId == filter.owningUserId) {
699                return super.newResult(filter, match, userId);
700            }
701            return null;
702        }
703
704        @Override
705        protected BroadcastFilter[] newArray(int size) {
706            return new BroadcastFilter[size];
707        }
708
709        @Override
710        protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
711            return packageName.equals(filter.packageName);
712        }
713    };
714
715    /**
716     * State of all active sticky broadcasts per user.  Keys are the action of the
717     * sticky Intent, values are an ArrayList of all broadcasted intents with
718     * that action (which should usually be one).  The SparseArray is keyed
719     * by the user ID the sticky is for, and can include UserHandle.USER_ALL
720     * for stickies that are sent to all users.
721     */
722    final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
723            new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
724
725    final ActiveServices mServices;
726
727    /**
728     * Backup/restore process management
729     */
730    String mBackupAppName = null;
731    BackupRecord mBackupTarget = null;
732
733    final ProviderMap mProviderMap;
734
735    /**
736     * List of content providers who have clients waiting for them.  The
737     * application is currently being launched and the provider will be
738     * removed from this list once it is published.
739     */
740    final ArrayList<ContentProviderRecord> mLaunchingProviders
741            = new ArrayList<ContentProviderRecord>();
742
743    /**
744     * File storing persisted {@link #mGrantedUriPermissions}.
745     */
746    private final AtomicFile mGrantFile;
747
748    /** XML constants used in {@link #mGrantFile} */
749    private static final String TAG_URI_GRANTS = "uri-grants";
750    private static final String TAG_URI_GRANT = "uri-grant";
751    private static final String ATTR_USER_HANDLE = "userHandle";
752    private static final String ATTR_SOURCE_USER_ID = "sourceUserId";
753    private static final String ATTR_TARGET_USER_ID = "targetUserId";
754    private static final String ATTR_SOURCE_PKG = "sourcePkg";
755    private static final String ATTR_TARGET_PKG = "targetPkg";
756    private static final String ATTR_URI = "uri";
757    private static final String ATTR_MODE_FLAGS = "modeFlags";
758    private static final String ATTR_CREATED_TIME = "createdTime";
759    private static final String ATTR_PREFIX = "prefix";
760
761    /**
762     * Global set of specific {@link Uri} permissions that have been granted.
763     * This optimized lookup structure maps from {@link UriPermission#targetUid}
764     * to {@link UriPermission#uri} to {@link UriPermission}.
765     */
766    @GuardedBy("this")
767    private final SparseArray<ArrayMap<GrantUri, UriPermission>>
768            mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>();
769
770    public static class GrantUri {
771        public final int sourceUserId;
772        public final Uri uri;
773        public boolean prefix;
774
775        public GrantUri(int sourceUserId, Uri uri, boolean prefix) {
776            this.sourceUserId = sourceUserId;
777            this.uri = uri;
778            this.prefix = prefix;
779        }
780
781        @Override
782        public int hashCode() {
783            return toString().hashCode();
784        }
785
786        @Override
787        public boolean equals(Object o) {
788            if (o instanceof GrantUri) {
789                GrantUri other = (GrantUri) o;
790                return uri.equals(other.uri) && (sourceUserId == other.sourceUserId)
791                        && prefix == other.prefix;
792            }
793            return false;
794        }
795
796        @Override
797        public String toString() {
798            String result = Integer.toString(sourceUserId) + " @ " + uri.toString();
799            if (prefix) result += " [prefix]";
800            return result;
801        }
802
803        public String toSafeString() {
804            String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString();
805            if (prefix) result += " [prefix]";
806            return result;
807        }
808
809        public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) {
810            return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle),
811                    ContentProvider.getUriWithoutUserId(uri), false);
812        }
813    }
814
815    CoreSettingsObserver mCoreSettingsObserver;
816
817    /**
818     * Thread-local storage used to carry caller permissions over through
819     * indirect content-provider access.
820     */
821    private class Identity {
822        public int pid;
823        public int uid;
824
825        Identity(int _pid, int _uid) {
826            pid = _pid;
827            uid = _uid;
828        }
829    }
830
831    private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
832
833    /**
834     * All information we have collected about the runtime performance of
835     * any user id that can impact battery performance.
836     */
837    final BatteryStatsService mBatteryStatsService;
838
839    /**
840     * Information about component usage
841     */
842    UsageStatsManagerInternal mUsageStatsService;
843
844    /**
845     * Information about and control over application operations
846     */
847    final AppOpsService mAppOpsService;
848
849    /**
850     * Save recent tasks information across reboots.
851     */
852    final TaskPersister mTaskPersister;
853
854    /**
855     * Current configuration information.  HistoryRecord objects are given
856     * a reference to this object to indicate which configuration they are
857     * currently running in, so this object must be kept immutable.
858     */
859    Configuration mConfiguration = new Configuration();
860
861    /**
862     * Current sequencing integer of the configuration, for skipping old
863     * configurations.
864     */
865    int mConfigurationSeq = 0;
866
867    /**
868     * Hardware-reported OpenGLES version.
869     */
870    final int GL_ES_VERSION;
871
872    /**
873     * List of initialization arguments to pass to all processes when binding applications to them.
874     * For example, references to the commonly used services.
875     */
876    HashMap<String, IBinder> mAppBindArgs;
877
878    /**
879     * Temporary to avoid allocations.  Protected by main lock.
880     */
881    final StringBuilder mStringBuilder = new StringBuilder(256);
882
883    /**
884     * Used to control how we initialize the service.
885     */
886    ComponentName mTopComponent;
887    String mTopAction = Intent.ACTION_MAIN;
888    String mTopData;
889    boolean mProcessesReady = false;
890    boolean mSystemReady = false;
891    boolean mBooting = false;
892    boolean mCallFinishBooting = false;
893    boolean mBootAnimationComplete = false;
894    boolean mWaitingUpdate = false;
895    boolean mDidUpdate = false;
896    boolean mOnBattery = false;
897    boolean mLaunchWarningShown = false;
898
899    Context mContext;
900
901    int mFactoryTest;
902
903    boolean mCheckedForSetup;
904
905    /**
906     * The time at which we will allow normal application switches again,
907     * after a call to {@link #stopAppSwitches()}.
908     */
909    long mAppSwitchesAllowedTime;
910
911    /**
912     * This is set to true after the first switch after mAppSwitchesAllowedTime
913     * is set; any switches after that will clear the time.
914     */
915    boolean mDidAppSwitch;
916
917    /**
918     * Last time (in realtime) at which we checked for power usage.
919     */
920    long mLastPowerCheckRealtime;
921
922    /**
923     * Last time (in uptime) at which we checked for power usage.
924     */
925    long mLastPowerCheckUptime;
926
927    /**
928     * Set while we are wanting to sleep, to prevent any
929     * activities from being started/resumed.
930     */
931    private boolean mSleeping = false;
932
933    /**
934     * Set while we are running a voice interaction.  This overrides
935     * sleeping while it is active.
936     */
937    private boolean mRunningVoice = false;
938
939    /**
940     * Set while the keyguard is waiting for an activity to draw.
941     * In this state, if we are sleeping, we allow Activities to launch
942     * so that they can draw before Keyguard dismisses itself.
943     */
944    private boolean mKeyguardWaitingForDraw = false;
945
946    /**
947     * State of external calls telling us if the device is asleep.
948     */
949    private boolean mWentToSleep = false;
950
951    /**
952     * State of external call telling us if the lock screen is shown.
953     */
954    private boolean mLockScreenShown = false;
955
956    /**
957     * Set if we are shutting down the system, similar to sleeping.
958     */
959    boolean mShuttingDown = false;
960
961    /**
962     * Current sequence id for oom_adj computation traversal.
963     */
964    int mAdjSeq = 0;
965
966    /**
967     * Current sequence id for process LRU updating.
968     */
969    int mLruSeq = 0;
970
971    /**
972     * Keep track of the non-cached/empty process we last found, to help
973     * determine how to distribute cached/empty processes next time.
974     */
975    int mNumNonCachedProcs = 0;
976
977    /**
978     * Keep track of the number of cached hidden procs, to balance oom adj
979     * distribution between those and empty procs.
980     */
981    int mNumCachedHiddenProcs = 0;
982
983    /**
984     * Keep track of the number of service processes we last found, to
985     * determine on the next iteration which should be B services.
986     */
987    int mNumServiceProcs = 0;
988    int mNewNumAServiceProcs = 0;
989    int mNewNumServiceProcs = 0;
990
991    /**
992     * Allow the current computed overall memory level of the system to go down?
993     * This is set to false when we are killing processes for reasons other than
994     * memory management, so that the now smaller process list will not be taken as
995     * an indication that memory is tighter.
996     */
997    boolean mAllowLowerMemLevel = false;
998
999    /**
1000     * The last computed memory level, for holding when we are in a state that
1001     * processes are going away for other reasons.
1002     */
1003    int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1004
1005    /**
1006     * The last total number of process we have, to determine if changes actually look
1007     * like a shrinking number of process due to lower RAM.
1008     */
1009    int mLastNumProcesses;
1010
1011    /**
1012     * The uptime of the last time we performed idle maintenance.
1013     */
1014    long mLastIdleTime = SystemClock.uptimeMillis();
1015
1016    /**
1017     * Total time spent with RAM that has been added in the past since the last idle time.
1018     */
1019    long mLowRamTimeSinceLastIdle = 0;
1020
1021    /**
1022     * If RAM is currently low, when that horrible situation started.
1023     */
1024    long mLowRamStartTime = 0;
1025
1026    /**
1027     * For reporting to battery stats the current top application.
1028     */
1029    private String mCurResumedPackage = null;
1030    private int mCurResumedUid = -1;
1031
1032    /**
1033     * For reporting to battery stats the apps currently running foreground
1034     * service.  The ProcessMap is package/uid tuples; each of these contain
1035     * an array of the currently foreground processes.
1036     */
1037    final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1038            = new ProcessMap<ArrayList<ProcessRecord>>();
1039
1040    /**
1041     * This is set if we had to do a delayed dexopt of an app before launching
1042     * it, to increase the ANR timeouts in that case.
1043     */
1044    boolean mDidDexOpt;
1045
1046    /**
1047     * Set if the systemServer made a call to enterSafeMode.
1048     */
1049    boolean mSafeMode;
1050
1051    String mDebugApp = null;
1052    boolean mWaitForDebugger = false;
1053    boolean mDebugTransient = false;
1054    String mOrigDebugApp = null;
1055    boolean mOrigWaitForDebugger = false;
1056    boolean mAlwaysFinishActivities = false;
1057    IActivityController mController = null;
1058    String mProfileApp = null;
1059    ProcessRecord mProfileProc = null;
1060    String mProfileFile;
1061    ParcelFileDescriptor mProfileFd;
1062    int mSamplingInterval = 0;
1063    boolean mAutoStopProfiler = false;
1064    int mProfileType = 0;
1065    String mOpenGlTraceApp = null;
1066
1067    static class ProcessChangeItem {
1068        static final int CHANGE_ACTIVITIES = 1<<0;
1069        static final int CHANGE_PROCESS_STATE = 1<<1;
1070        int changes;
1071        int uid;
1072        int pid;
1073        int processState;
1074        boolean foregroundActivities;
1075    }
1076
1077    final RemoteCallbackList<IProcessObserver> mProcessObservers
1078            = new RemoteCallbackList<IProcessObserver>();
1079    ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
1080
1081    final ArrayList<ProcessChangeItem> mPendingProcessChanges
1082            = new ArrayList<ProcessChangeItem>();
1083    final ArrayList<ProcessChangeItem> mAvailProcessChanges
1084            = new ArrayList<ProcessChangeItem>();
1085
1086    /**
1087     * Runtime CPU use collection thread.  This object's lock is used to
1088     * perform synchronization with the thread (notifying it to run).
1089     */
1090    final Thread mProcessCpuThread;
1091
1092    /**
1093     * Used to collect per-process CPU use for ANRs, battery stats, etc.
1094     * Must acquire this object's lock when accessing it.
1095     * NOTE: this lock will be held while doing long operations (trawling
1096     * through all processes in /proc), so it should never be acquired by
1097     * any critical paths such as when holding the main activity manager lock.
1098     */
1099    final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
1100            MONITOR_THREAD_CPU_USAGE);
1101    final AtomicLong mLastCpuTime = new AtomicLong(0);
1102    final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
1103
1104    long mLastWriteTime = 0;
1105
1106    /**
1107     * Used to retain an update lock when the foreground activity is in
1108     * immersive mode.
1109     */
1110    final UpdateLock mUpdateLock = new UpdateLock("immersive");
1111
1112    /**
1113     * Set to true after the system has finished booting.
1114     */
1115    boolean mBooted = false;
1116
1117    int mProcessLimit = ProcessList.MAX_CACHED_APPS;
1118    int mProcessLimitOverride = -1;
1119
1120    WindowManagerService mWindowManager;
1121
1122    final ActivityThread mSystemThread;
1123
1124    // Holds the current foreground user's id
1125    int mCurrentUserId = 0;
1126    // Holds the target user's id during a user switch
1127    int mTargetUserId = UserHandle.USER_NULL;
1128    // If there are multiple profiles for the current user, their ids are here
1129    // Currently only the primary user can have managed profiles
1130    int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack
1131
1132    /**
1133     * Mapping from each known user ID to the profile group ID it is associated with.
1134     */
1135    SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
1136
1137    private UserManagerService mUserManager;
1138
1139    private final class AppDeathRecipient implements IBinder.DeathRecipient {
1140        final ProcessRecord mApp;
1141        final int mPid;
1142        final IApplicationThread mAppThread;
1143
1144        AppDeathRecipient(ProcessRecord app, int pid,
1145                IApplicationThread thread) {
1146            if (localLOGV) Slog.v(
1147                TAG, "New death recipient " + this
1148                + " for thread " + thread.asBinder());
1149            mApp = app;
1150            mPid = pid;
1151            mAppThread = thread;
1152        }
1153
1154        @Override
1155        public void binderDied() {
1156            if (localLOGV) Slog.v(
1157                TAG, "Death received in " + this
1158                + " for thread " + mAppThread.asBinder());
1159            synchronized(ActivityManagerService.this) {
1160                appDiedLocked(mApp, mPid, mAppThread);
1161            }
1162        }
1163    }
1164
1165    static final int SHOW_ERROR_MSG = 1;
1166    static final int SHOW_NOT_RESPONDING_MSG = 2;
1167    static final int SHOW_FACTORY_ERROR_MSG = 3;
1168    static final int UPDATE_CONFIGURATION_MSG = 4;
1169    static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1170    static final int WAIT_FOR_DEBUGGER_MSG = 6;
1171    static final int SERVICE_TIMEOUT_MSG = 12;
1172    static final int UPDATE_TIME_ZONE = 13;
1173    static final int SHOW_UID_ERROR_MSG = 14;
1174    static final int IM_FEELING_LUCKY_MSG = 15;
1175    static final int PROC_START_TIMEOUT_MSG = 20;
1176    static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
1177    static final int KILL_APPLICATION_MSG = 22;
1178    static final int FINALIZE_PENDING_INTENT_MSG = 23;
1179    static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1180    static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
1181    static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
1182    static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
1183    static final int CLEAR_DNS_CACHE_MSG = 28;
1184    static final int UPDATE_HTTP_PROXY_MSG = 29;
1185    static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
1186    static final int DISPATCH_PROCESSES_CHANGED = 31;
1187    static final int DISPATCH_PROCESS_DIED = 32;
1188    static final int REPORT_MEM_USAGE_MSG = 33;
1189    static final int REPORT_USER_SWITCH_MSG = 34;
1190    static final int CONTINUE_USER_SWITCH_MSG = 35;
1191    static final int USER_SWITCH_TIMEOUT_MSG = 36;
1192    static final int IMMERSIVE_MODE_LOCK_MSG = 37;
1193    static final int PERSIST_URI_GRANTS_MSG = 38;
1194    static final int REQUEST_ALL_PSS_MSG = 39;
1195    static final int START_PROFILES_MSG = 40;
1196    static final int UPDATE_TIME = 41;
1197    static final int SYSTEM_USER_START_MSG = 42;
1198    static final int SYSTEM_USER_CURRENT_MSG = 43;
1199    static final int ENTER_ANIMATION_COMPLETE_MSG = 44;
1200    static final int ENABLE_SCREEN_AFTER_BOOT_MSG = 45;
1201    static final int START_USER_SWITCH_MSG = 46;
1202
1203    static final int FIRST_ACTIVITY_STACK_MSG = 100;
1204    static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1205    static final int FIRST_COMPAT_MODE_MSG = 300;
1206    static final int FIRST_SUPERVISOR_STACK_MSG = 100;
1207
1208    AlertDialog mUidAlert;
1209    CompatModeDialog mCompatModeDialog;
1210    long mLastMemUsageReportTime = 0;
1211
1212    private LockToAppRequestDialog mLockToAppRequest;
1213
1214    /**
1215     * Flag whether the current user is a "monkey", i.e. whether
1216     * the UI is driven by a UI automation tool.
1217     */
1218    private boolean mUserIsMonkey;
1219
1220    /** Flag whether the device has a Recents UI */
1221    boolean mHasRecents;
1222
1223    /** The dimensions of the thumbnails in the Recents UI. */
1224    int mThumbnailWidth;
1225    int mThumbnailHeight;
1226
1227    final ServiceThread mHandlerThread;
1228    final MainHandler mHandler;
1229
1230    final class MainHandler extends Handler {
1231        public MainHandler(Looper looper) {
1232            super(looper, null, true);
1233        }
1234
1235        @Override
1236        public void handleMessage(Message msg) {
1237            switch (msg.what) {
1238            case SHOW_ERROR_MSG: {
1239                HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1240                boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
1241                        Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
1242                synchronized (ActivityManagerService.this) {
1243                    ProcessRecord proc = (ProcessRecord)data.get("app");
1244                    AppErrorResult res = (AppErrorResult) data.get("result");
1245                    if (proc != null && proc.crashDialog != null) {
1246                        Slog.e(TAG, "App already has crash dialog: " + proc);
1247                        if (res != null) {
1248                            res.set(0);
1249                        }
1250                        return;
1251                    }
1252                    boolean isBackground = (UserHandle.getAppId(proc.uid)
1253                            >= Process.FIRST_APPLICATION_UID
1254                            && proc.pid != MY_PID);
1255                    for (int userId : mCurrentProfileIds) {
1256                        isBackground &= (proc.userId != userId);
1257                    }
1258                    if (isBackground && !showBackground) {
1259                        Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
1260                        if (res != null) {
1261                            res.set(0);
1262                        }
1263                        return;
1264                    }
1265                    if (mShowDialogs && !mSleeping && !mShuttingDown) {
1266                        Dialog d = new AppErrorDialog(mContext,
1267                                ActivityManagerService.this, res, proc);
1268                        d.show();
1269                        proc.crashDialog = d;
1270                    } else {
1271                        // The device is asleep, so just pretend that the user
1272                        // saw a crash dialog and hit "force quit".
1273                        if (res != null) {
1274                            res.set(0);
1275                        }
1276                    }
1277                }
1278
1279                ensureBootCompleted();
1280            } break;
1281            case SHOW_NOT_RESPONDING_MSG: {
1282                synchronized (ActivityManagerService.this) {
1283                    HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1284                    ProcessRecord proc = (ProcessRecord)data.get("app");
1285                    if (proc != null && proc.anrDialog != null) {
1286                        Slog.e(TAG, "App already has anr dialog: " + proc);
1287                        return;
1288                    }
1289
1290                    Intent intent = new Intent("android.intent.action.ANR");
1291                    if (!mProcessesReady) {
1292                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1293                                | Intent.FLAG_RECEIVER_FOREGROUND);
1294                    }
1295                    broadcastIntentLocked(null, null, intent,
1296                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1297                            false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
1298
1299                    if (mShowDialogs) {
1300                        Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
1301                                mContext, proc, (ActivityRecord)data.get("activity"),
1302                                msg.arg1 != 0);
1303                        d.show();
1304                        proc.anrDialog = d;
1305                    } else {
1306                        // Just kill the app if there is no dialog to be shown.
1307                        killAppAtUsersRequest(proc, null);
1308                    }
1309                }
1310
1311                ensureBootCompleted();
1312            } break;
1313            case SHOW_STRICT_MODE_VIOLATION_MSG: {
1314                HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1315                synchronized (ActivityManagerService.this) {
1316                    ProcessRecord proc = (ProcessRecord) data.get("app");
1317                    if (proc == null) {
1318                        Slog.e(TAG, "App not found when showing strict mode dialog.");
1319                        break;
1320                    }
1321                    if (proc.crashDialog != null) {
1322                        Slog.e(TAG, "App already has strict mode dialog: " + proc);
1323                        return;
1324                    }
1325                    AppErrorResult res = (AppErrorResult) data.get("result");
1326                    if (mShowDialogs && !mSleeping && !mShuttingDown) {
1327                        Dialog d = new StrictModeViolationDialog(mContext,
1328                                ActivityManagerService.this, res, proc);
1329                        d.show();
1330                        proc.crashDialog = d;
1331                    } else {
1332                        // The device is asleep, so just pretend that the user
1333                        // saw a crash dialog and hit "force quit".
1334                        res.set(0);
1335                    }
1336                }
1337                ensureBootCompleted();
1338            } break;
1339            case SHOW_FACTORY_ERROR_MSG: {
1340                Dialog d = new FactoryErrorDialog(
1341                    mContext, msg.getData().getCharSequence("msg"));
1342                d.show();
1343                ensureBootCompleted();
1344            } break;
1345            case UPDATE_CONFIGURATION_MSG: {
1346                final ContentResolver resolver = mContext.getContentResolver();
1347                Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1348            } break;
1349            case GC_BACKGROUND_PROCESSES_MSG: {
1350                synchronized (ActivityManagerService.this) {
1351                    performAppGcsIfAppropriateLocked();
1352                }
1353            } break;
1354            case WAIT_FOR_DEBUGGER_MSG: {
1355                synchronized (ActivityManagerService.this) {
1356                    ProcessRecord app = (ProcessRecord)msg.obj;
1357                    if (msg.arg1 != 0) {
1358                        if (!app.waitedForDebugger) {
1359                            Dialog d = new AppWaitingForDebuggerDialog(
1360                                    ActivityManagerService.this,
1361                                    mContext, app);
1362                            app.waitDialog = d;
1363                            app.waitedForDebugger = true;
1364                            d.show();
1365                        }
1366                    } else {
1367                        if (app.waitDialog != null) {
1368                            app.waitDialog.dismiss();
1369                            app.waitDialog = null;
1370                        }
1371                    }
1372                }
1373            } break;
1374            case SERVICE_TIMEOUT_MSG: {
1375                if (mDidDexOpt) {
1376                    mDidDexOpt = false;
1377                    Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1378                    nmsg.obj = msg.obj;
1379                    mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
1380                    return;
1381                }
1382                mServices.serviceTimeout((ProcessRecord)msg.obj);
1383            } break;
1384            case UPDATE_TIME_ZONE: {
1385                synchronized (ActivityManagerService.this) {
1386                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1387                        ProcessRecord r = mLruProcesses.get(i);
1388                        if (r.thread != null) {
1389                            try {
1390                                r.thread.updateTimeZone();
1391                            } catch (RemoteException ex) {
1392                                Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
1393                            }
1394                        }
1395                    }
1396                }
1397            } break;
1398            case CLEAR_DNS_CACHE_MSG: {
1399                synchronized (ActivityManagerService.this) {
1400                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1401                        ProcessRecord r = mLruProcesses.get(i);
1402                        if (r.thread != null) {
1403                            try {
1404                                r.thread.clearDnsCache();
1405                            } catch (RemoteException ex) {
1406                                Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1407                            }
1408                        }
1409                    }
1410                }
1411            } break;
1412            case UPDATE_HTTP_PROXY_MSG: {
1413                ProxyInfo proxy = (ProxyInfo)msg.obj;
1414                String host = "";
1415                String port = "";
1416                String exclList = "";
1417                Uri pacFileUrl = Uri.EMPTY;
1418                if (proxy != null) {
1419                    host = proxy.getHost();
1420                    port = Integer.toString(proxy.getPort());
1421                    exclList = proxy.getExclusionListAsString();
1422                    pacFileUrl = proxy.getPacFileUrl();
1423                }
1424                synchronized (ActivityManagerService.this) {
1425                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1426                        ProcessRecord r = mLruProcesses.get(i);
1427                        if (r.thread != null) {
1428                            try {
1429                                r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
1430                            } catch (RemoteException ex) {
1431                                Slog.w(TAG, "Failed to update http proxy for: " +
1432                                        r.info.processName);
1433                            }
1434                        }
1435                    }
1436                }
1437            } break;
1438            case SHOW_UID_ERROR_MSG: {
1439                String title = "System UIDs Inconsistent";
1440                String text = "UIDs on the system are inconsistent, you need to wipe your"
1441                        + " data partition or your device will be unstable.";
1442                Log.e(TAG, title + ": " + text);
1443                if (mShowDialogs) {
1444                    // XXX This is a temporary dialog, no need to localize.
1445                    AlertDialog d = new BaseErrorDialog(mContext);
1446                    d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1447                    d.setCancelable(false);
1448                    d.setTitle(title);
1449                    d.setMessage(text);
1450                    d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1451                            mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1452                    mUidAlert = d;
1453                    d.show();
1454                }
1455            } break;
1456            case IM_FEELING_LUCKY_MSG: {
1457                if (mUidAlert != null) {
1458                    mUidAlert.dismiss();
1459                    mUidAlert = null;
1460                }
1461            } break;
1462            case PROC_START_TIMEOUT_MSG: {
1463                if (mDidDexOpt) {
1464                    mDidDexOpt = false;
1465                    Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1466                    nmsg.obj = msg.obj;
1467                    mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1468                    return;
1469                }
1470                ProcessRecord app = (ProcessRecord)msg.obj;
1471                synchronized (ActivityManagerService.this) {
1472                    processStartTimedOutLocked(app);
1473                }
1474            } break;
1475            case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1476                synchronized (ActivityManagerService.this) {
1477                    mStackSupervisor.doPendingActivityLaunchesLocked(true);
1478                }
1479            } break;
1480            case KILL_APPLICATION_MSG: {
1481                synchronized (ActivityManagerService.this) {
1482                    int appid = msg.arg1;
1483                    boolean restart = (msg.arg2 == 1);
1484                    Bundle bundle = (Bundle)msg.obj;
1485                    String pkg = bundle.getString("pkg");
1486                    String reason = bundle.getString("reason");
1487                    forceStopPackageLocked(pkg, appid, restart, false, true, false,
1488                            false, UserHandle.USER_ALL, reason);
1489                }
1490            } break;
1491            case FINALIZE_PENDING_INTENT_MSG: {
1492                ((PendingIntentRecord)msg.obj).completeFinalize();
1493            } break;
1494            case POST_HEAVY_NOTIFICATION_MSG: {
1495                INotificationManager inm = NotificationManager.getService();
1496                if (inm == null) {
1497                    return;
1498                }
1499
1500                ActivityRecord root = (ActivityRecord)msg.obj;
1501                ProcessRecord process = root.app;
1502                if (process == null) {
1503                    return;
1504                }
1505
1506                try {
1507                    Context context = mContext.createPackageContext(process.info.packageName, 0);
1508                    String text = mContext.getString(R.string.heavy_weight_notification,
1509                            context.getApplicationInfo().loadLabel(context.getPackageManager()));
1510                    Notification notification = new Notification();
1511                    notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1512                    notification.when = 0;
1513                    notification.flags = Notification.FLAG_ONGOING_EVENT;
1514                    notification.tickerText = text;
1515                    notification.defaults = 0; // please be quiet
1516                    notification.sound = null;
1517                    notification.vibrate = null;
1518                    notification.color = mContext.getResources().getColor(
1519                            com.android.internal.R.color.system_notification_accent_color);
1520                    notification.setLatestEventInfo(context, text,
1521                            mContext.getText(R.string.heavy_weight_notification_detail),
1522                            PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1523                                    PendingIntent.FLAG_CANCEL_CURRENT, null,
1524                                    new UserHandle(root.userId)));
1525
1526                    try {
1527                        int[] outId = new int[1];
1528                        inm.enqueueNotificationWithTag("android", "android", null,
1529                                R.string.heavy_weight_notification,
1530                                notification, outId, root.userId);
1531                    } catch (RuntimeException e) {
1532                        Slog.w(ActivityManagerService.TAG,
1533                                "Error showing notification for heavy-weight app", e);
1534                    } catch (RemoteException e) {
1535                    }
1536                } catch (NameNotFoundException e) {
1537                    Slog.w(TAG, "Unable to create context for heavy notification", e);
1538                }
1539            } break;
1540            case CANCEL_HEAVY_NOTIFICATION_MSG: {
1541                INotificationManager inm = NotificationManager.getService();
1542                if (inm == null) {
1543                    return;
1544                }
1545                try {
1546                    inm.cancelNotificationWithTag("android", null,
1547                            R.string.heavy_weight_notification,  msg.arg1);
1548                } catch (RuntimeException e) {
1549                    Slog.w(ActivityManagerService.TAG,
1550                            "Error canceling notification for service", e);
1551                } catch (RemoteException e) {
1552                }
1553            } break;
1554            case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1555                synchronized (ActivityManagerService.this) {
1556                    checkExcessivePowerUsageLocked(true);
1557                    removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1558                    Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1559                    sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
1560                }
1561            } break;
1562            case SHOW_COMPAT_MODE_DIALOG_MSG: {
1563                synchronized (ActivityManagerService.this) {
1564                    ActivityRecord ar = (ActivityRecord)msg.obj;
1565                    if (mCompatModeDialog != null) {
1566                        if (mCompatModeDialog.mAppInfo.packageName.equals(
1567                                ar.info.applicationInfo.packageName)) {
1568                            return;
1569                        }
1570                        mCompatModeDialog.dismiss();
1571                        mCompatModeDialog = null;
1572                    }
1573                    if (ar != null && false) {
1574                        if (mCompatModePackages.getPackageAskCompatModeLocked(
1575                                ar.packageName)) {
1576                            int mode = mCompatModePackages.computeCompatModeLocked(
1577                                    ar.info.applicationInfo);
1578                            if (mode == ActivityManager.COMPAT_MODE_DISABLED
1579                                    || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1580                                mCompatModeDialog = new CompatModeDialog(
1581                                        ActivityManagerService.this, mContext,
1582                                        ar.info.applicationInfo);
1583                                mCompatModeDialog.show();
1584                            }
1585                        }
1586                    }
1587                }
1588                break;
1589            }
1590            case DISPATCH_PROCESSES_CHANGED: {
1591                dispatchProcessesChanged();
1592                break;
1593            }
1594            case DISPATCH_PROCESS_DIED: {
1595                final int pid = msg.arg1;
1596                final int uid = msg.arg2;
1597                dispatchProcessDied(pid, uid);
1598                break;
1599            }
1600            case REPORT_MEM_USAGE_MSG: {
1601                final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
1602                Thread thread = new Thread() {
1603                    @Override public void run() {
1604                        final SparseArray<ProcessMemInfo> infoMap
1605                                = new SparseArray<ProcessMemInfo>(memInfos.size());
1606                        for (int i=0, N=memInfos.size(); i<N; i++) {
1607                            ProcessMemInfo mi = memInfos.get(i);
1608                            infoMap.put(mi.pid, mi);
1609                        }
1610                        updateCpuStatsNow();
1611                        synchronized (mProcessCpuTracker) {
1612                            final int N = mProcessCpuTracker.countStats();
1613                            for (int i=0; i<N; i++) {
1614                                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
1615                                if (st.vsize > 0) {
1616                                    long pss = Debug.getPss(st.pid, null);
1617                                    if (pss > 0) {
1618                                        if (infoMap.indexOfKey(st.pid) < 0) {
1619                                            ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid,
1620                                                    ProcessList.NATIVE_ADJ, -1, "native", null);
1621                                            mi.pss = pss;
1622                                            memInfos.add(mi);
1623                                        }
1624                                    }
1625                                }
1626                            }
1627                        }
1628
1629                        long totalPss = 0;
1630                        for (int i=0, N=memInfos.size(); i<N; i++) {
1631                            ProcessMemInfo mi = memInfos.get(i);
1632                            if (mi.pss == 0) {
1633                                mi.pss = Debug.getPss(mi.pid, null);
1634                            }
1635                            totalPss += mi.pss;
1636                        }
1637                        Collections.sort(memInfos, new Comparator<ProcessMemInfo>() {
1638                            @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) {
1639                                if (lhs.oomAdj != rhs.oomAdj) {
1640                                    return lhs.oomAdj < rhs.oomAdj ? -1 : 1;
1641                                }
1642                                if (lhs.pss != rhs.pss) {
1643                                    return lhs.pss < rhs.pss ? 1 : -1;
1644                                }
1645                                return 0;
1646                            }
1647                        });
1648
1649                        StringBuilder tag = new StringBuilder(128);
1650                        StringBuilder stack = new StringBuilder(128);
1651                        tag.append("Low on memory -- ");
1652                        appendMemBucket(tag, totalPss, "total", false);
1653                        appendMemBucket(stack, totalPss, "total", true);
1654
1655                        StringBuilder logBuilder = new StringBuilder(1024);
1656                        logBuilder.append("Low on memory:\n");
1657
1658                        boolean firstLine = true;
1659                        int lastOomAdj = Integer.MIN_VALUE;
1660                        for (int i=0, N=memInfos.size(); i<N; i++) {
1661                            ProcessMemInfo mi = memInfos.get(i);
1662
1663                            if (mi.oomAdj != ProcessList.NATIVE_ADJ
1664                                    && (mi.oomAdj < ProcessList.SERVICE_ADJ
1665                                            || mi.oomAdj == ProcessList.HOME_APP_ADJ
1666                                            || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) {
1667                                if (lastOomAdj != mi.oomAdj) {
1668                                    lastOomAdj = mi.oomAdj;
1669                                    if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
1670                                        tag.append(" / ");
1671                                    }
1672                                    if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) {
1673                                        if (firstLine) {
1674                                            stack.append(":");
1675                                            firstLine = false;
1676                                        }
1677                                        stack.append("\n\t at ");
1678                                    } else {
1679                                        stack.append("$");
1680                                    }
1681                                } else {
1682                                    tag.append(" ");
1683                                    stack.append("$");
1684                                }
1685                                if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
1686                                    appendMemBucket(tag, mi.pss, mi.name, false);
1687                                }
1688                                appendMemBucket(stack, mi.pss, mi.name, true);
1689                                if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ
1690                                        && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) {
1691                                    stack.append("(");
1692                                    for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
1693                                        if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) {
1694                                            stack.append(DUMP_MEM_OOM_LABEL[k]);
1695                                            stack.append(":");
1696                                            stack.append(DUMP_MEM_OOM_ADJ[k]);
1697                                        }
1698                                    }
1699                                    stack.append(")");
1700                                }
1701                            }
1702
1703                            logBuilder.append("  ");
1704                            logBuilder.append(ProcessList.makeOomAdjString(mi.oomAdj));
1705                            logBuilder.append(' ');
1706                            logBuilder.append(ProcessList.makeProcStateString(mi.procState));
1707                            logBuilder.append(' ');
1708                            ProcessList.appendRamKb(logBuilder, mi.pss);
1709                            logBuilder.append(" kB: ");
1710                            logBuilder.append(mi.name);
1711                            logBuilder.append(" (");
1712                            logBuilder.append(mi.pid);
1713                            logBuilder.append(") ");
1714                            logBuilder.append(mi.adjType);
1715                            logBuilder.append('\n');
1716                            if (mi.adjReason != null) {
1717                                logBuilder.append("                      ");
1718                                logBuilder.append(mi.adjReason);
1719                                logBuilder.append('\n');
1720                            }
1721                        }
1722
1723                        logBuilder.append("           ");
1724                        ProcessList.appendRamKb(logBuilder, totalPss);
1725                        logBuilder.append(" kB: TOTAL\n");
1726
1727                        long[] infos = new long[Debug.MEMINFO_COUNT];
1728                        Debug.getMemInfo(infos);
1729                        logBuilder.append("  MemInfo: ");
1730                        logBuilder.append(infos[Debug.MEMINFO_SLAB]).append(" kB slab, ");
1731                        logBuilder.append(infos[Debug.MEMINFO_SHMEM]).append(" kB shmem, ");
1732                        logBuilder.append(infos[Debug.MEMINFO_BUFFERS]).append(" kB buffers, ");
1733                        logBuilder.append(infos[Debug.MEMINFO_CACHED]).append(" kB cached, ");
1734                        logBuilder.append(infos[Debug.MEMINFO_FREE]).append(" kB free\n");
1735                        if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) {
1736                            logBuilder.append("  ZRAM: ");
1737                            logBuilder.append(infos[Debug.MEMINFO_ZRAM_TOTAL]);
1738                            logBuilder.append(" kB RAM, ");
1739                            logBuilder.append(infos[Debug.MEMINFO_SWAP_TOTAL]);
1740                            logBuilder.append(" kB swap total, ");
1741                            logBuilder.append(infos[Debug.MEMINFO_SWAP_FREE]);
1742                            logBuilder.append(" kB swap free\n");
1743                        }
1744                        Slog.i(TAG, logBuilder.toString());
1745
1746                        StringBuilder dropBuilder = new StringBuilder(1024);
1747                        /*
1748                        StringWriter oomSw = new StringWriter();
1749                        PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256);
1750                        StringWriter catSw = new StringWriter();
1751                        PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
1752                        String[] emptyArgs = new String[] { };
1753                        dumpApplicationMemoryUsage(null, oomPw, "  ", emptyArgs, true, catPw);
1754                        oomPw.flush();
1755                        String oomString = oomSw.toString();
1756                        */
1757                        dropBuilder.append(stack);
1758                        dropBuilder.append('\n');
1759                        dropBuilder.append('\n');
1760                        dropBuilder.append(logBuilder);
1761                        dropBuilder.append('\n');
1762                        /*
1763                        dropBuilder.append(oomString);
1764                        dropBuilder.append('\n');
1765                        */
1766                        StringWriter catSw = new StringWriter();
1767                        synchronized (ActivityManagerService.this) {
1768                            PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
1769                            String[] emptyArgs = new String[] { };
1770                            catPw.println();
1771                            dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
1772                            catPw.println();
1773                            mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1774                                    false, false, null);
1775                            catPw.println();
1776                            dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
1777                            catPw.flush();
1778                        }
1779                        dropBuilder.append(catSw.toString());
1780                        addErrorToDropBox("lowmem", null, "system_server", null,
1781                                null, tag.toString(), dropBuilder.toString(), null, null);
1782                        //Slog.i(TAG, "Sent to dropbox:");
1783                        //Slog.i(TAG, dropBuilder.toString());
1784                        synchronized (ActivityManagerService.this) {
1785                            long now = SystemClock.uptimeMillis();
1786                            if (mLastMemUsageReportTime < now) {
1787                                mLastMemUsageReportTime = now;
1788                            }
1789                        }
1790                    }
1791                };
1792                thread.start();
1793                break;
1794            }
1795            case START_USER_SWITCH_MSG: {
1796                showUserSwitchDialog(msg.arg1, (String) msg.obj);
1797                break;
1798            }
1799            case REPORT_USER_SWITCH_MSG: {
1800                dispatchUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
1801                break;
1802            }
1803            case CONTINUE_USER_SWITCH_MSG: {
1804                continueUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
1805                break;
1806            }
1807            case USER_SWITCH_TIMEOUT_MSG: {
1808                timeoutUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
1809                break;
1810            }
1811            case IMMERSIVE_MODE_LOCK_MSG: {
1812                final boolean nextState = (msg.arg1 != 0);
1813                if (mUpdateLock.isHeld() != nextState) {
1814                    if (DEBUG_IMMERSIVE) {
1815                        final ActivityRecord r = (ActivityRecord) msg.obj;
1816                        Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1817                    }
1818                    if (nextState) {
1819                        mUpdateLock.acquire();
1820                    } else {
1821                        mUpdateLock.release();
1822                    }
1823                }
1824                break;
1825            }
1826            case PERSIST_URI_GRANTS_MSG: {
1827                writeGrantedUriPermissions();
1828                break;
1829            }
1830            case REQUEST_ALL_PSS_MSG: {
1831                requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
1832                break;
1833            }
1834            case START_PROFILES_MSG: {
1835                synchronized (ActivityManagerService.this) {
1836                    startProfilesLocked();
1837                }
1838                break;
1839            }
1840            case UPDATE_TIME: {
1841                synchronized (ActivityManagerService.this) {
1842                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1843                        ProcessRecord r = mLruProcesses.get(i);
1844                        if (r.thread != null) {
1845                            try {
1846                                r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true);
1847                            } catch (RemoteException ex) {
1848                                Slog.w(TAG, "Failed to update preferences for: " + r.info.processName);
1849                            }
1850                        }
1851                    }
1852                }
1853                break;
1854            }
1855            case SYSTEM_USER_START_MSG: {
1856                mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
1857                        Integer.toString(msg.arg1), msg.arg1);
1858                mSystemServiceManager.startUser(msg.arg1);
1859                break;
1860            }
1861            case SYSTEM_USER_CURRENT_MSG: {
1862                mBatteryStatsService.noteEvent(
1863                        BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
1864                        Integer.toString(msg.arg2), msg.arg2);
1865                mBatteryStatsService.noteEvent(
1866                        BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
1867                        Integer.toString(msg.arg1), msg.arg1);
1868                mSystemServiceManager.switchUser(msg.arg1);
1869                mLockToAppRequest.clearPrompt();
1870                break;
1871            }
1872            case ENTER_ANIMATION_COMPLETE_MSG: {
1873                synchronized (ActivityManagerService.this) {
1874                    ActivityRecord r = ActivityRecord.forToken((IBinder) msg.obj);
1875                    if (r != null && r.app != null && r.app.thread != null) {
1876                        try {
1877                            r.app.thread.scheduleEnterAnimationComplete(r.appToken);
1878                        } catch (RemoteException e) {
1879                        }
1880                    }
1881                }
1882                break;
1883            }
1884            case ENABLE_SCREEN_AFTER_BOOT_MSG: {
1885                enableScreenAfterBoot();
1886                break;
1887            }
1888            }
1889        }
1890    };
1891
1892    static final int COLLECT_PSS_BG_MSG = 1;
1893
1894    final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
1895        @Override
1896        public void handleMessage(Message msg) {
1897            switch (msg.what) {
1898            case COLLECT_PSS_BG_MSG: {
1899                long start = SystemClock.uptimeMillis();
1900                MemInfoReader memInfo = null;
1901                synchronized (ActivityManagerService.this) {
1902                    if (mFullPssPending) {
1903                        mFullPssPending = false;
1904                        memInfo = new MemInfoReader();
1905                    }
1906                }
1907                if (memInfo != null) {
1908                    updateCpuStatsNow();
1909                    long nativeTotalPss = 0;
1910                    synchronized (mProcessCpuTracker) {
1911                        final int N = mProcessCpuTracker.countStats();
1912                        for (int j=0; j<N; j++) {
1913                            ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j);
1914                            if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) {
1915                                // This is definitely an application process; skip it.
1916                                continue;
1917                            }
1918                            synchronized (mPidsSelfLocked) {
1919                                if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) {
1920                                    // This is one of our own processes; skip it.
1921                                    continue;
1922                                }
1923                            }
1924                            nativeTotalPss += Debug.getPss(st.pid, null);
1925                        }
1926                    }
1927                    memInfo.readMemInfo();
1928                    synchronized (ActivityManagerService.this) {
1929                        if (DEBUG_PSS) Slog.d(TAG, "Collected native and kernel memory in "
1930                                + (SystemClock.uptimeMillis()-start) + "ms");
1931                        mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(),
1932                                memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(),
1933                                memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb()
1934                                        +memInfo.getSlabSizeKb(),
1935                                nativeTotalPss);
1936                    }
1937                }
1938
1939                int i=0, num=0;
1940                long[] tmp = new long[1];
1941                do {
1942                    ProcessRecord proc;
1943                    int procState;
1944                    int pid;
1945                    synchronized (ActivityManagerService.this) {
1946                        if (i >= mPendingPssProcesses.size()) {
1947                            if (DEBUG_PSS) Slog.d(TAG, "Collected PSS of " + num + " of " + i
1948                                    + " processes in " + (SystemClock.uptimeMillis()-start) + "ms");
1949                            mPendingPssProcesses.clear();
1950                            return;
1951                        }
1952                        proc = mPendingPssProcesses.get(i);
1953                        procState = proc.pssProcState;
1954                        if (proc.thread != null && procState == proc.setProcState) {
1955                            pid = proc.pid;
1956                        } else {
1957                            proc = null;
1958                            pid = 0;
1959                        }
1960                        i++;
1961                    }
1962                    if (proc != null) {
1963                        long pss = Debug.getPss(pid, tmp);
1964                        synchronized (ActivityManagerService.this) {
1965                            if (proc.thread != null && proc.setProcState == procState
1966                                    && proc.pid == pid) {
1967                                num++;
1968                                proc.lastPssTime = SystemClock.uptimeMillis();
1969                                proc.baseProcessTracker.addPss(pss, tmp[0], true, proc.pkgList);
1970                                if (DEBUG_PSS) Slog.d(TAG, "PSS of " + proc.toShortString()
1971                                        + ": " + pss + " lastPss=" + proc.lastPss
1972                                        + " state=" + ProcessList.makeProcStateString(procState));
1973                                if (proc.initialIdlePss == 0) {
1974                                    proc.initialIdlePss = pss;
1975                                }
1976                                proc.lastPss = pss;
1977                                if (procState >= ActivityManager.PROCESS_STATE_HOME) {
1978                                    proc.lastCachedPss = pss;
1979                                }
1980                            }
1981                        }
1982                    }
1983                } while (true);
1984            }
1985            }
1986        }
1987    };
1988
1989    /**
1990     * Monitor for package changes and update our internal state.
1991     */
1992    private final PackageMonitor mPackageMonitor = new PackageMonitor() {
1993        @Override
1994        public void onPackageRemoved(String packageName, int uid) {
1995            // Remove all tasks with activities in the specified package from the list of recent tasks
1996            synchronized (ActivityManagerService.this) {
1997                for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
1998                    TaskRecord tr = mRecentTasks.get(i);
1999                    ComponentName cn = tr.intent.getComponent();
2000                    if (cn != null && cn.getPackageName().equals(packageName)) {
2001                        // If the package name matches, remove the task and kill the process
2002                        removeTaskByIdLocked(tr.taskId, ActivityManager.REMOVE_TASK_KILL_PROCESS);
2003                    }
2004                }
2005            }
2006        }
2007
2008        @Override
2009        public boolean onPackageChanged(String packageName, int uid, String[] components) {
2010            onPackageModified(packageName);
2011            return true;
2012        }
2013
2014        @Override
2015        public void onPackageModified(String packageName) {
2016            final PackageManager pm = mContext.getPackageManager();
2017            final ArrayList<Pair<Intent, Integer>> recentTaskIntents =
2018                    new ArrayList<Pair<Intent, Integer>>();
2019            final ArrayList<Integer> tasksToRemove = new ArrayList<Integer>();
2020            // Copy the list of recent tasks so that we don't hold onto the lock on
2021            // ActivityManagerService for long periods while checking if components exist.
2022            synchronized (ActivityManagerService.this) {
2023                for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
2024                    TaskRecord tr = mRecentTasks.get(i);
2025                    recentTaskIntents.add(new Pair<Intent, Integer>(tr.intent, tr.taskId));
2026                }
2027            }
2028            // Check the recent tasks and filter out all tasks with components that no longer exist.
2029            Intent tmpI = new Intent();
2030            for (int i = recentTaskIntents.size() - 1; i >= 0; i--) {
2031                Pair<Intent, Integer> p = recentTaskIntents.get(i);
2032                ComponentName cn = p.first.getComponent();
2033                if (cn != null && cn.getPackageName().equals(packageName)) {
2034                    try {
2035                        // Add the task to the list to remove if the component no longer exists
2036                        tmpI.setComponent(cn);
2037                        if (pm.queryIntentActivities(tmpI, PackageManager.MATCH_DEFAULT_ONLY).isEmpty()) {
2038                            tasksToRemove.add(p.second);
2039                        }
2040                    } catch (Exception e) {}
2041                }
2042            }
2043            // Prune all the tasks with removed components from the list of recent tasks
2044            synchronized (ActivityManagerService.this) {
2045                for (int i = tasksToRemove.size() - 1; i >= 0; i--) {
2046                    // Remove the task but don't kill the process (since other components in that
2047                    // package may still be running and in the background)
2048                    removeTaskByIdLocked(tasksToRemove.get(i), 0);
2049                }
2050            }
2051        }
2052
2053        @Override
2054        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
2055            // Force stop the specified packages
2056            if (packages != null) {
2057                for (String pkg : packages) {
2058                    synchronized (ActivityManagerService.this) {
2059                        if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 0,
2060                                "finished booting")) {
2061                            return true;
2062                        }
2063                    }
2064                }
2065            }
2066            return false;
2067        }
2068    };
2069
2070    public void setSystemProcess() {
2071        try {
2072            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
2073            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2074            ServiceManager.addService("meminfo", new MemBinder(this));
2075            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2076            ServiceManager.addService("dbinfo", new DbBinder(this));
2077            if (MONITOR_CPU_USAGE) {
2078                ServiceManager.addService("cpuinfo", new CpuBinder(this));
2079            }
2080            ServiceManager.addService("permission", new PermissionController(this));
2081
2082            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2083                    "android", STOCK_PM_FLAGS);
2084            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2085
2086            synchronized (this) {
2087                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2088                app.persistent = true;
2089                app.pid = MY_PID;
2090                app.maxAdj = ProcessList.SYSTEM_ADJ;
2091                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2092                mProcessNames.put(app.processName, app.uid, app);
2093                synchronized (mPidsSelfLocked) {
2094                    mPidsSelfLocked.put(app.pid, app);
2095                }
2096                updateLruProcessLocked(app, false, null);
2097                updateOomAdjLocked();
2098            }
2099        } catch (PackageManager.NameNotFoundException e) {
2100            throw new RuntimeException(
2101                    "Unable to find android system package", e);
2102        }
2103    }
2104
2105    public void setWindowManager(WindowManagerService wm) {
2106        mWindowManager = wm;
2107        mStackSupervisor.setWindowManager(wm);
2108    }
2109
2110    public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
2111        mUsageStatsService = usageStatsManager;
2112    }
2113
2114    public void startObservingNativeCrashes() {
2115        final NativeCrashListener ncl = new NativeCrashListener(this);
2116        ncl.start();
2117    }
2118
2119    public IAppOpsService getAppOpsService() {
2120        return mAppOpsService;
2121    }
2122
2123    static class MemBinder extends Binder {
2124        ActivityManagerService mActivityManagerService;
2125        MemBinder(ActivityManagerService activityManagerService) {
2126            mActivityManagerService = activityManagerService;
2127        }
2128
2129        @Override
2130        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2131            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2132                    != PackageManager.PERMISSION_GRANTED) {
2133                pw.println("Permission Denial: can't dump meminfo from from pid="
2134                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2135                        + " without permission " + android.Manifest.permission.DUMP);
2136                return;
2137            }
2138
2139            mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, "  ", args, false, null);
2140        }
2141    }
2142
2143    static class GraphicsBinder extends Binder {
2144        ActivityManagerService mActivityManagerService;
2145        GraphicsBinder(ActivityManagerService activityManagerService) {
2146            mActivityManagerService = activityManagerService;
2147        }
2148
2149        @Override
2150        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2151            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2152                    != PackageManager.PERMISSION_GRANTED) {
2153                pw.println("Permission Denial: can't dump gfxinfo from from pid="
2154                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2155                        + " without permission " + android.Manifest.permission.DUMP);
2156                return;
2157            }
2158
2159            mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2160        }
2161    }
2162
2163    static class DbBinder extends Binder {
2164        ActivityManagerService mActivityManagerService;
2165        DbBinder(ActivityManagerService activityManagerService) {
2166            mActivityManagerService = activityManagerService;
2167        }
2168
2169        @Override
2170        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2171            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2172                    != PackageManager.PERMISSION_GRANTED) {
2173                pw.println("Permission Denial: can't dump dbinfo from from pid="
2174                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2175                        + " without permission " + android.Manifest.permission.DUMP);
2176                return;
2177            }
2178
2179            mActivityManagerService.dumpDbInfo(fd, pw, args);
2180        }
2181    }
2182
2183    static class CpuBinder extends Binder {
2184        ActivityManagerService mActivityManagerService;
2185        CpuBinder(ActivityManagerService activityManagerService) {
2186            mActivityManagerService = activityManagerService;
2187        }
2188
2189        @Override
2190        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2191            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2192                    != PackageManager.PERMISSION_GRANTED) {
2193                pw.println("Permission Denial: can't dump cpuinfo from from pid="
2194                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2195                        + " without permission " + android.Manifest.permission.DUMP);
2196                return;
2197            }
2198
2199            synchronized (mActivityManagerService.mProcessCpuTracker) {
2200                pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
2201                pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
2202                        SystemClock.uptimeMillis()));
2203            }
2204        }
2205    }
2206
2207    public static final class Lifecycle extends SystemService {
2208        private final ActivityManagerService mService;
2209
2210        public Lifecycle(Context context) {
2211            super(context);
2212            mService = new ActivityManagerService(context);
2213        }
2214
2215        @Override
2216        public void onStart() {
2217            mService.start();
2218        }
2219
2220        public ActivityManagerService getService() {
2221            return mService;
2222        }
2223    }
2224
2225    // Note: This method is invoked on the main thread but may need to attach various
2226    // handlers to other threads.  So take care to be explicit about the looper.
2227    public ActivityManagerService(Context systemContext) {
2228        mContext = systemContext;
2229        mFactoryTest = FactoryTest.getMode();
2230        mSystemThread = ActivityThread.currentActivityThread();
2231
2232        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2233
2234        mHandlerThread = new ServiceThread(TAG,
2235                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2236        mHandlerThread.start();
2237        mHandler = new MainHandler(mHandlerThread.getLooper());
2238
2239        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2240                "foreground", BROADCAST_FG_TIMEOUT, false);
2241        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2242                "background", BROADCAST_BG_TIMEOUT, true);
2243        mBroadcastQueues[0] = mFgBroadcastQueue;
2244        mBroadcastQueues[1] = mBgBroadcastQueue;
2245
2246        mServices = new ActiveServices(this);
2247        mProviderMap = new ProviderMap(this);
2248
2249        // TODO: Move creation of battery stats service outside of activity manager service.
2250        File dataDir = Environment.getDataDirectory();
2251        File systemDir = new File(dataDir, "system");
2252        systemDir.mkdirs();
2253        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
2254        mBatteryStatsService.getActiveStatistics().readLocked();
2255        mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
2256        mOnBattery = DEBUG_POWER ? true
2257                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2258        mBatteryStatsService.getActiveStatistics().setCallback(this);
2259
2260        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2261
2262        mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
2263
2264        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
2265
2266        // User 0 is the first and only user that runs at boot.
2267        mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
2268        mUserLru.add(Integer.valueOf(0));
2269        updateStartedUserArrayLocked();
2270
2271        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2272            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2273
2274        mConfiguration.setToDefaults();
2275        mConfiguration.setLocale(Locale.getDefault());
2276
2277        mConfigurationSeq = mConfiguration.seq = 1;
2278        mProcessCpuTracker.init();
2279
2280        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
2281        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2282        mStackSupervisor = new ActivityStackSupervisor(this);
2283        mTaskPersister = new TaskPersister(systemDir, mStackSupervisor);
2284
2285        mProcessCpuThread = new Thread("CpuTracker") {
2286            @Override
2287            public void run() {
2288                while (true) {
2289                    try {
2290                        try {
2291                            synchronized(this) {
2292                                final long now = SystemClock.uptimeMillis();
2293                                long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2294                                long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2295                                //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2296                                //        + ", write delay=" + nextWriteDelay);
2297                                if (nextWriteDelay < nextCpuDelay) {
2298                                    nextCpuDelay = nextWriteDelay;
2299                                }
2300                                if (nextCpuDelay > 0) {
2301                                    mProcessCpuMutexFree.set(true);
2302                                    this.wait(nextCpuDelay);
2303                                }
2304                            }
2305                        } catch (InterruptedException e) {
2306                        }
2307                        updateCpuStatsNow();
2308                    } catch (Exception e) {
2309                        Slog.e(TAG, "Unexpected exception collecting process stats", e);
2310                    }
2311                }
2312            }
2313        };
2314
2315        mLockToAppRequest = new LockToAppRequestDialog(mContext, this);
2316
2317        Watchdog.getInstance().addMonitor(this);
2318        Watchdog.getInstance().addThread(mHandler);
2319    }
2320
2321    public void setSystemServiceManager(SystemServiceManager mgr) {
2322        mSystemServiceManager = mgr;
2323    }
2324
2325    private void start() {
2326        Process.removeAllProcessGroups();
2327        mProcessCpuThread.start();
2328
2329        mBatteryStatsService.publish(mContext);
2330        mAppOpsService.publish(mContext);
2331        Slog.d("AppOps", "AppOpsService published");
2332        LocalServices.addService(ActivityManagerInternal.class, new LocalService());
2333    }
2334
2335    public void initPowerManagement() {
2336        mStackSupervisor.initPowerManagement();
2337        mBatteryStatsService.initPowerManagement();
2338    }
2339
2340    @Override
2341    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2342            throws RemoteException {
2343        if (code == SYSPROPS_TRANSACTION) {
2344            // We need to tell all apps about the system property change.
2345            ArrayList<IBinder> procs = new ArrayList<IBinder>();
2346            synchronized(this) {
2347                final int NP = mProcessNames.getMap().size();
2348                for (int ip=0; ip<NP; ip++) {
2349                    SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
2350                    final int NA = apps.size();
2351                    for (int ia=0; ia<NA; ia++) {
2352                        ProcessRecord app = apps.valueAt(ia);
2353                        if (app.thread != null) {
2354                            procs.add(app.thread.asBinder());
2355                        }
2356                    }
2357                }
2358            }
2359
2360            int N = procs.size();
2361            for (int i=0; i<N; i++) {
2362                Parcel data2 = Parcel.obtain();
2363                try {
2364                    procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
2365                } catch (RemoteException e) {
2366                }
2367                data2.recycle();
2368            }
2369        }
2370        try {
2371            return super.onTransact(code, data, reply, flags);
2372        } catch (RuntimeException e) {
2373            // The activity manager only throws security exceptions, so let's
2374            // log all others.
2375            if (!(e instanceof SecurityException)) {
2376                Slog.wtf(TAG, "Activity Manager Crash", e);
2377            }
2378            throw e;
2379        }
2380    }
2381
2382    void updateCpuStats() {
2383        final long now = SystemClock.uptimeMillis();
2384        if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2385            return;
2386        }
2387        if (mProcessCpuMutexFree.compareAndSet(true, false)) {
2388            synchronized (mProcessCpuThread) {
2389                mProcessCpuThread.notify();
2390            }
2391        }
2392    }
2393
2394    void updateCpuStatsNow() {
2395        synchronized (mProcessCpuTracker) {
2396            mProcessCpuMutexFree.set(false);
2397            final long now = SystemClock.uptimeMillis();
2398            boolean haveNewCpuStats = false;
2399
2400            if (MONITOR_CPU_USAGE &&
2401                    mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2402                mLastCpuTime.set(now);
2403                haveNewCpuStats = true;
2404                mProcessCpuTracker.update();
2405                //Slog.i(TAG, mProcessCpu.printCurrentState());
2406                //Slog.i(TAG, "Total CPU usage: "
2407                //        + mProcessCpu.getTotalCpuPercent() + "%");
2408
2409                // Slog the cpu usage if the property is set.
2410                if ("true".equals(SystemProperties.get("events.cpu"))) {
2411                    int user = mProcessCpuTracker.getLastUserTime();
2412                    int system = mProcessCpuTracker.getLastSystemTime();
2413                    int iowait = mProcessCpuTracker.getLastIoWaitTime();
2414                    int irq = mProcessCpuTracker.getLastIrqTime();
2415                    int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
2416                    int idle = mProcessCpuTracker.getLastIdleTime();
2417
2418                    int total = user + system + iowait + irq + softIrq + idle;
2419                    if (total == 0) total = 1;
2420
2421                    EventLog.writeEvent(EventLogTags.CPU,
2422                            ((user+system+iowait+irq+softIrq) * 100) / total,
2423                            (user * 100) / total,
2424                            (system * 100) / total,
2425                            (iowait * 100) / total,
2426                            (irq * 100) / total,
2427                            (softIrq * 100) / total);
2428                }
2429            }
2430
2431            long[] cpuSpeedTimes = mProcessCpuTracker.getLastCpuSpeedTimes();
2432            final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
2433            synchronized(bstats) {
2434                synchronized(mPidsSelfLocked) {
2435                    if (haveNewCpuStats) {
2436                        if (mOnBattery) {
2437                            int perc = bstats.startAddingCpuLocked();
2438                            int totalUTime = 0;
2439                            int totalSTime = 0;
2440                            final int N = mProcessCpuTracker.countStats();
2441                            for (int i=0; i<N; i++) {
2442                                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
2443                                if (!st.working) {
2444                                    continue;
2445                                }
2446                                ProcessRecord pr = mPidsSelfLocked.get(st.pid);
2447                                int otherUTime = (st.rel_utime*perc)/100;
2448                                int otherSTime = (st.rel_stime*perc)/100;
2449                                totalUTime += otherUTime;
2450                                totalSTime += otherSTime;
2451                                if (pr != null) {
2452                                    BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
2453                                    if (ps == null || !ps.isActive()) {
2454                                        pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
2455                                                pr.info.uid, pr.processName);
2456                                    }
2457                                    ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2458                                            st.rel_stime-otherSTime);
2459                                    ps.addSpeedStepTimes(cpuSpeedTimes);
2460                                    pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
2461                                } else {
2462                                    BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
2463                                    if (ps == null || !ps.isActive()) {
2464                                        st.batteryStats = ps = bstats.getProcessStatsLocked(
2465                                                bstats.mapUid(st.uid), st.name);
2466                                    }
2467                                    ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2468                                            st.rel_stime-otherSTime);
2469                                    ps.addSpeedStepTimes(cpuSpeedTimes);
2470                                }
2471                            }
2472                            bstats.finishAddingCpuLocked(perc, totalUTime,
2473                                    totalSTime, cpuSpeedTimes);
2474                        }
2475                    }
2476                }
2477
2478                if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2479                    mLastWriteTime = now;
2480                    mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
2481                }
2482            }
2483        }
2484    }
2485
2486    @Override
2487    public void batteryNeedsCpuUpdate() {
2488        updateCpuStatsNow();
2489    }
2490
2491    @Override
2492    public void batteryPowerChanged(boolean onBattery) {
2493        // When plugging in, update the CPU stats first before changing
2494        // the plug state.
2495        updateCpuStatsNow();
2496        synchronized (this) {
2497            synchronized(mPidsSelfLocked) {
2498                mOnBattery = DEBUG_POWER ? true : onBattery;
2499            }
2500        }
2501    }
2502
2503    /**
2504     * Initialize the application bind args. These are passed to each
2505     * process when the bindApplication() IPC is sent to the process. They're
2506     * lazily setup to make sure the services are running when they're asked for.
2507     */
2508    private HashMap<String, IBinder> getCommonServicesLocked() {
2509        if (mAppBindArgs == null) {
2510            mAppBindArgs = new HashMap<String, IBinder>();
2511
2512            // Setup the application init args
2513            mAppBindArgs.put("package", ServiceManager.getService("package"));
2514            mAppBindArgs.put("window", ServiceManager.getService("window"));
2515            mAppBindArgs.put(Context.ALARM_SERVICE,
2516                    ServiceManager.getService(Context.ALARM_SERVICE));
2517        }
2518        return mAppBindArgs;
2519    }
2520
2521    final void setFocusedActivityLocked(ActivityRecord r) {
2522        if (mFocusedActivity != r) {
2523            if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedActivityLocked: r=" + r);
2524            mFocusedActivity = r;
2525            if (r.task != null && r.task.voiceInteractor != null) {
2526                startRunningVoiceLocked();
2527            } else {
2528                finishRunningVoiceLocked();
2529            }
2530            mStackSupervisor.setFocusedStack(r);
2531            if (r != null) {
2532                mWindowManager.setFocusedApp(r.appToken, true);
2533            }
2534            applyUpdateLockStateLocked(r);
2535        }
2536    }
2537
2538    final void clearFocusedActivity(ActivityRecord r) {
2539        if (mFocusedActivity == r) {
2540            mFocusedActivity = null;
2541        }
2542    }
2543
2544    @Override
2545    public void setFocusedStack(int stackId) {
2546        if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedStack: stackId=" + stackId);
2547        synchronized (ActivityManagerService.this) {
2548            ActivityStack stack = mStackSupervisor.getStack(stackId);
2549            if (stack != null) {
2550                ActivityRecord r = stack.topRunningActivityLocked(null);
2551                if (r != null) {
2552                    setFocusedActivityLocked(r);
2553                }
2554            }
2555        }
2556    }
2557
2558    @Override
2559    public void notifyActivityDrawn(IBinder token) {
2560        if (DEBUG_VISBILITY) Slog.d(TAG, "notifyActivityDrawn: token=" + token);
2561        synchronized (this) {
2562            ActivityRecord r= mStackSupervisor.isInAnyStackLocked(token);
2563            if (r != null) {
2564                r.task.stack.notifyActivityDrawnLocked(r);
2565            }
2566        }
2567    }
2568
2569    final void applyUpdateLockStateLocked(ActivityRecord r) {
2570        // Modifications to the UpdateLock state are done on our handler, outside
2571        // the activity manager's locks.  The new state is determined based on the
2572        // state *now* of the relevant activity record.  The object is passed to
2573        // the handler solely for logging detail, not to be consulted/modified.
2574        final boolean nextState = r != null && r.immersive;
2575        mHandler.sendMessage(
2576                mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
2577    }
2578
2579    final void showAskCompatModeDialogLocked(ActivityRecord r) {
2580        Message msg = Message.obtain();
2581        msg.what = SHOW_COMPAT_MODE_DIALOG_MSG;
2582        msg.obj = r.task.askedCompatMode ? null : r;
2583        mHandler.sendMessage(msg);
2584    }
2585
2586    private final int updateLruProcessInternalLocked(ProcessRecord app, long now, int index,
2587            String what, Object obj, ProcessRecord srcApp) {
2588        app.lastActivityTime = now;
2589
2590        if (app.activities.size() > 0) {
2591            // Don't want to touch dependent processes that are hosting activities.
2592            return index;
2593        }
2594
2595        int lrui = mLruProcesses.lastIndexOf(app);
2596        if (lrui < 0) {
2597            Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: "
2598                    + what + " " + obj + " from " + srcApp);
2599            return index;
2600        }
2601
2602        if (lrui >= index) {
2603            // Don't want to cause this to move dependent processes *back* in the
2604            // list as if they were less frequently used.
2605            return index;
2606        }
2607
2608        if (lrui >= mLruProcessActivityStart) {
2609            // Don't want to touch dependent processes that are hosting activities.
2610            return index;
2611        }
2612
2613        mLruProcesses.remove(lrui);
2614        if (index > 0) {
2615            index--;
2616        }
2617        if (DEBUG_LRU) Slog.d(TAG, "Moving dep from " + lrui + " to " + index
2618                + " in LRU list: " + app);
2619        mLruProcesses.add(index, app);
2620        return index;
2621    }
2622
2623    final void removeLruProcessLocked(ProcessRecord app) {
2624        int lrui = mLruProcesses.lastIndexOf(app);
2625        if (lrui >= 0) {
2626            if (lrui <= mLruProcessActivityStart) {
2627                mLruProcessActivityStart--;
2628            }
2629            if (lrui <= mLruProcessServiceStart) {
2630                mLruProcessServiceStart--;
2631            }
2632            mLruProcesses.remove(lrui);
2633        }
2634    }
2635
2636    final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2637            ProcessRecord client) {
2638        final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities
2639                || app.treatLikeActivity;
2640        final boolean hasService = false; // not impl yet. app.services.size() > 0;
2641        if (!activityChange && hasActivity) {
2642            // The process has activities, so we are only allowing activity-based adjustments
2643            // to move it.  It should be kept in the front of the list with other
2644            // processes that have activities, and we don't want those to change their
2645            // order except due to activity operations.
2646            return;
2647        }
2648
2649        mLruSeq++;
2650        final long now = SystemClock.uptimeMillis();
2651        app.lastActivityTime = now;
2652
2653        // First a quick reject: if the app is already at the position we will
2654        // put it, then there is nothing to do.
2655        if (hasActivity) {
2656            final int N = mLruProcesses.size();
2657            if (N > 0 && mLruProcesses.get(N-1) == app) {
2658                if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top activity: " + app);
2659                return;
2660            }
2661        } else {
2662            if (mLruProcessServiceStart > 0
2663                    && mLruProcesses.get(mLruProcessServiceStart-1) == app) {
2664                if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top other: " + app);
2665                return;
2666            }
2667        }
2668
2669        int lrui = mLruProcesses.lastIndexOf(app);
2670
2671        if (app.persistent && lrui >= 0) {
2672            // We don't care about the position of persistent processes, as long as
2673            // they are in the list.
2674            if (DEBUG_LRU) Slog.d(TAG, "Not moving, persistent: " + app);
2675            return;
2676        }
2677
2678        /* In progress: compute new position first, so we can avoid doing work
2679           if the process is not actually going to move.  Not yet working.
2680        int addIndex;
2681        int nextIndex;
2682        boolean inActivity = false, inService = false;
2683        if (hasActivity) {
2684            // Process has activities, put it at the very tipsy-top.
2685            addIndex = mLruProcesses.size();
2686            nextIndex = mLruProcessServiceStart;
2687            inActivity = true;
2688        } else if (hasService) {
2689            // Process has services, put it at the top of the service list.
2690            addIndex = mLruProcessActivityStart;
2691            nextIndex = mLruProcessServiceStart;
2692            inActivity = true;
2693            inService = true;
2694        } else  {
2695            // Process not otherwise of interest, it goes to the top of the non-service area.
2696            addIndex = mLruProcessServiceStart;
2697            if (client != null) {
2698                int clientIndex = mLruProcesses.lastIndexOf(client);
2699                if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating "
2700                        + app);
2701                if (clientIndex >= 0 && addIndex > clientIndex) {
2702                    addIndex = clientIndex;
2703                }
2704            }
2705            nextIndex = addIndex > 0 ? addIndex-1 : addIndex;
2706        }
2707
2708        Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act="
2709                + mLruProcessActivityStart + "): " + app);
2710        */
2711
2712        if (lrui >= 0) {
2713            if (lrui < mLruProcessActivityStart) {
2714                mLruProcessActivityStart--;
2715            }
2716            if (lrui < mLruProcessServiceStart) {
2717                mLruProcessServiceStart--;
2718            }
2719            /*
2720            if (addIndex > lrui) {
2721                addIndex--;
2722            }
2723            if (nextIndex > lrui) {
2724                nextIndex--;
2725            }
2726            */
2727            mLruProcesses.remove(lrui);
2728        }
2729
2730        /*
2731        mLruProcesses.add(addIndex, app);
2732        if (inActivity) {
2733            mLruProcessActivityStart++;
2734        }
2735        if (inService) {
2736            mLruProcessActivityStart++;
2737        }
2738        */
2739
2740        int nextIndex;
2741        if (hasActivity) {
2742            final int N = mLruProcesses.size();
2743            if (app.activities.size() == 0 && mLruProcessActivityStart < (N-1)) {
2744                // Process doesn't have activities, but has clients with
2745                // activities...  move it up, but one below the top (the top
2746                // should always have a real activity).
2747                if (DEBUG_LRU) Slog.d(TAG, "Adding to second-top of LRU activity list: " + app);
2748                mLruProcesses.add(N-1, app);
2749                // To keep it from spamming the LRU list (by making a bunch of clients),
2750                // we will push down any other entries owned by the app.
2751                final int uid = app.info.uid;
2752                for (int i=N-2; i>mLruProcessActivityStart; i--) {
2753                    ProcessRecord subProc = mLruProcesses.get(i);
2754                    if (subProc.info.uid == uid) {
2755                        // We want to push this one down the list.  If the process after
2756                        // it is for the same uid, however, don't do so, because we don't
2757                        // want them internally to be re-ordered.
2758                        if (mLruProcesses.get(i-1).info.uid != uid) {
2759                            if (DEBUG_LRU) Slog.d(TAG, "Pushing uid " + uid + " swapping at " + i
2760                                    + ": " + mLruProcesses.get(i) + " : " + mLruProcesses.get(i-1));
2761                            ProcessRecord tmp = mLruProcesses.get(i);
2762                            mLruProcesses.set(i, mLruProcesses.get(i-1));
2763                            mLruProcesses.set(i-1, tmp);
2764                            i--;
2765                        }
2766                    } else {
2767                        // A gap, we can stop here.
2768                        break;
2769                    }
2770                }
2771            } else {
2772                // Process has activities, put it at the very tipsy-top.
2773                if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU activity list: " + app);
2774                mLruProcesses.add(app);
2775            }
2776            nextIndex = mLruProcessServiceStart;
2777        } else if (hasService) {
2778            // Process has services, put it at the top of the service list.
2779            if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU service list: " + app);
2780            mLruProcesses.add(mLruProcessActivityStart, app);
2781            nextIndex = mLruProcessServiceStart;
2782            mLruProcessActivityStart++;
2783        } else  {
2784            // Process not otherwise of interest, it goes to the top of the non-service area.
2785            int index = mLruProcessServiceStart;
2786            if (client != null) {
2787                // If there is a client, don't allow the process to be moved up higher
2788                // in the list than that client.
2789                int clientIndex = mLruProcesses.lastIndexOf(client);
2790                if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG, "Unknown client " + client
2791                        + " when updating " + app);
2792                if (clientIndex <= lrui) {
2793                    // Don't allow the client index restriction to push it down farther in the
2794                    // list than it already is.
2795                    clientIndex = lrui;
2796                }
2797                if (clientIndex >= 0 && index > clientIndex) {
2798                    index = clientIndex;
2799                }
2800            }
2801            if (DEBUG_LRU) Slog.d(TAG, "Adding at " + index + " of LRU list: " + app);
2802            mLruProcesses.add(index, app);
2803            nextIndex = index-1;
2804            mLruProcessActivityStart++;
2805            mLruProcessServiceStart++;
2806        }
2807
2808        // If the app is currently using a content provider or service,
2809        // bump those processes as well.
2810        for (int j=app.connections.size()-1; j>=0; j--) {
2811            ConnectionRecord cr = app.connections.valueAt(j);
2812            if (cr.binding != null && !cr.serviceDead && cr.binding.service != null
2813                    && cr.binding.service.app != null
2814                    && cr.binding.service.app.lruSeq != mLruSeq
2815                    && !cr.binding.service.app.persistent) {
2816                nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex,
2817                        "service connection", cr, app);
2818            }
2819        }
2820        for (int j=app.conProviders.size()-1; j>=0; j--) {
2821            ContentProviderRecord cpr = app.conProviders.get(j).provider;
2822            if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) {
2823                nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex,
2824                        "provider reference", cpr, app);
2825            }
2826        }
2827    }
2828
2829    final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
2830        if (uid == Process.SYSTEM_UID) {
2831            // The system gets to run in any process.  If there are multiple
2832            // processes with the same uid, just pick the first (this
2833            // should never happen).
2834            SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName);
2835            if (procs == null) return null;
2836            final int N = procs.size();
2837            for (int i = 0; i < N; i++) {
2838                if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
2839            }
2840        }
2841        ProcessRecord proc = mProcessNames.get(processName, uid);
2842        if (false && proc != null && !keepIfLarge
2843                && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY
2844                && proc.lastCachedPss >= 4000) {
2845            // Turn this condition on to cause killing to happen regularly, for testing.
2846            if (proc.baseProcessTracker != null) {
2847                proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
2848            }
2849            proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
2850        } else if (proc != null && !keepIfLarge
2851                && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
2852                && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2853            if (DEBUG_PSS) Slog.d(TAG, "May not keep " + proc + ": pss=" + proc.lastCachedPss);
2854            if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) {
2855                if (proc.baseProcessTracker != null) {
2856                    proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
2857                }
2858                proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
2859            }
2860        }
2861        return proc;
2862    }
2863
2864    void ensurePackageDexOpt(String packageName) {
2865        IPackageManager pm = AppGlobals.getPackageManager();
2866        try {
2867            if (pm.performDexOptIfNeeded(packageName, null /* instruction set */)) {
2868                mDidDexOpt = true;
2869            }
2870        } catch (RemoteException e) {
2871        }
2872    }
2873
2874    boolean isNextTransitionForward() {
2875        int transit = mWindowManager.getPendingAppTransition();
2876        return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
2877                || transit == AppTransition.TRANSIT_TASK_OPEN
2878                || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
2879    }
2880
2881    int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
2882            String processName, String abiOverride, int uid, Runnable crashHandler) {
2883        synchronized(this) {
2884            ApplicationInfo info = new ApplicationInfo();
2885            // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
2886            // For isolated processes, the former contains the parent's uid and the latter the
2887            // actual uid of the isolated process.
2888            // In the special case introduced by this method (which is, starting an isolated
2889            // process directly from the SystemServer without an actual parent app process) the
2890            // closest thing to a parent's uid is SYSTEM_UID.
2891            // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
2892            // the |isolated| logic in the ProcessRecord constructor.
2893            info.uid = Process.SYSTEM_UID;
2894            info.processName = processName;
2895            info.className = entryPoint;
2896            info.packageName = "android";
2897            ProcessRecord proc = startProcessLocked(processName, info /* info */,
2898                    false /* knownToBeDead */, 0 /* intentFlags */, ""  /* hostingType */,
2899                    null /* hostingName */, true /* allowWhileBooting */, true /* isolated */,
2900                    uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
2901                    crashHandler);
2902            return proc != null ? proc.pid : 0;
2903        }
2904    }
2905
2906    final ProcessRecord startProcessLocked(String processName,
2907            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
2908            String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2909            boolean isolated, boolean keepIfLarge) {
2910        return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
2911                hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
2912                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
2913                null /* crashHandler */);
2914    }
2915
2916    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
2917            boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
2918            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
2919            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
2920        long startTime = SystemClock.elapsedRealtime();
2921        ProcessRecord app;
2922        if (!isolated) {
2923            app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
2924            checkTime(startTime, "startProcess: after getProcessRecord");
2925        } else {
2926            // If this is an isolated process, it can't re-use an existing process.
2927            app = null;
2928        }
2929        // We don't have to do anything more if:
2930        // (1) There is an existing application record; and
2931        // (2) The caller doesn't think it is dead, OR there is no thread
2932        //     object attached to it so we know it couldn't have crashed; and
2933        // (3) There is a pid assigned to it, so it is either starting or
2934        //     already running.
2935        if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
2936                + " app=" + app + " knownToBeDead=" + knownToBeDead
2937                + " thread=" + (app != null ? app.thread : null)
2938                + " pid=" + (app != null ? app.pid : -1));
2939        if (app != null && app.pid > 0) {
2940            if (!knownToBeDead || app.thread == null) {
2941                // We already have the app running, or are waiting for it to
2942                // come up (we have a pid but not yet its thread), so keep it.
2943                if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
2944                // If this is a new package in the process, add the package to the list
2945                app.addPackage(info.packageName, info.versionCode, mProcessStats);
2946                checkTime(startTime, "startProcess: done, added package to proc");
2947                return app;
2948            }
2949
2950            // An application record is attached to a previous process,
2951            // clean it up now.
2952            if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
2953            checkTime(startTime, "startProcess: bad proc running, killing");
2954            Process.killProcessGroup(app.info.uid, app.pid);
2955            handleAppDiedLocked(app, true, true);
2956            checkTime(startTime, "startProcess: done killing old proc");
2957        }
2958
2959        String hostingNameStr = hostingName != null
2960                ? hostingName.flattenToShortString() : null;
2961
2962        if (!isolated) {
2963            if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2964                // If we are in the background, then check to see if this process
2965                // is bad.  If so, we will just silently fail.
2966                if (mBadProcesses.get(info.processName, info.uid) != null) {
2967                    if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2968                            + "/" + info.processName);
2969                    return null;
2970                }
2971            } else {
2972                // When the user is explicitly starting a process, then clear its
2973                // crash count so that we won't make it bad until they see at
2974                // least one crash dialog again, and make the process good again
2975                // if it had been bad.
2976                if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
2977                        + "/" + info.processName);
2978                mProcessCrashTimes.remove(info.processName, info.uid);
2979                if (mBadProcesses.get(info.processName, info.uid) != null) {
2980                    EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2981                            UserHandle.getUserId(info.uid), info.uid,
2982                            info.processName);
2983                    mBadProcesses.remove(info.processName, info.uid);
2984                    if (app != null) {
2985                        app.bad = false;
2986                    }
2987                }
2988            }
2989        }
2990
2991        if (app == null) {
2992            checkTime(startTime, "startProcess: creating new process record");
2993            app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
2994            app.crashHandler = crashHandler;
2995            if (app == null) {
2996                Slog.w(TAG, "Failed making new process record for "
2997                        + processName + "/" + info.uid + " isolated=" + isolated);
2998                return null;
2999            }
3000            mProcessNames.put(processName, app.uid, app);
3001            if (isolated) {
3002                mIsolatedProcesses.put(app.uid, app);
3003            }
3004            checkTime(startTime, "startProcess: done creating new process record");
3005        } else {
3006            // If this is a new package in the process, add the package to the list
3007            app.addPackage(info.packageName, info.versionCode, mProcessStats);
3008            checkTime(startTime, "startProcess: added package to existing proc");
3009        }
3010
3011        // If the system is not ready yet, then hold off on starting this
3012        // process until it is.
3013        if (!mProcessesReady
3014                && !isAllowedWhileBooting(info)
3015                && !allowWhileBooting) {
3016            if (!mProcessesOnHold.contains(app)) {
3017                mProcessesOnHold.add(app);
3018            }
3019            if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
3020            checkTime(startTime, "startProcess: returning with proc on hold");
3021            return app;
3022        }
3023
3024        checkTime(startTime, "startProcess: stepping in to startProcess");
3025        startProcessLocked(
3026                app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
3027        checkTime(startTime, "startProcess: done starting proc!");
3028        return (app.pid != 0) ? app : null;
3029    }
3030
3031    boolean isAllowedWhileBooting(ApplicationInfo ai) {
3032        return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
3033    }
3034
3035    private final void startProcessLocked(ProcessRecord app,
3036            String hostingType, String hostingNameStr) {
3037        startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */,
3038                null /* entryPoint */, null /* entryPointArgs */);
3039    }
3040
3041    private final void startProcessLocked(ProcessRecord app, String hostingType,
3042            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
3043        long startTime = SystemClock.elapsedRealtime();
3044        if (app.pid > 0 && app.pid != MY_PID) {
3045            checkTime(startTime, "startProcess: removing from pids map");
3046            synchronized (mPidsSelfLocked) {
3047                mPidsSelfLocked.remove(app.pid);
3048                mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3049            }
3050            checkTime(startTime, "startProcess: done removing from pids map");
3051            app.setPid(0);
3052        }
3053
3054        if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3055                "startProcessLocked removing on hold: " + app);
3056        mProcessesOnHold.remove(app);
3057
3058        checkTime(startTime, "startProcess: starting to update cpu stats");
3059        updateCpuStats();
3060        checkTime(startTime, "startProcess: done updating cpu stats");
3061
3062        try {
3063            int uid = app.uid;
3064
3065            int[] gids = null;
3066            int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
3067            if (!app.isolated) {
3068                int[] permGids = null;
3069                try {
3070                    checkTime(startTime, "startProcess: getting gids from package manager");
3071                    final PackageManager pm = mContext.getPackageManager();
3072                    permGids = pm.getPackageGids(app.info.packageName);
3073
3074                    if (Environment.isExternalStorageEmulated()) {
3075                        checkTime(startTime, "startProcess: checking external storage perm");
3076                        if (pm.checkPermission(
3077                                android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
3078                                app.info.packageName) == PERMISSION_GRANTED) {
3079                            mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
3080                        } else {
3081                            mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
3082                        }
3083                    }
3084                } catch (PackageManager.NameNotFoundException e) {
3085                    Slog.w(TAG, "Unable to retrieve gids", e);
3086                }
3087
3088                /*
3089                 * Add shared application and profile GIDs so applications can share some
3090                 * resources like shared libraries and access user-wide resources
3091                 */
3092                if (permGids == null) {
3093                    gids = new int[2];
3094                } else {
3095                    gids = new int[permGids.length + 2];
3096                    System.arraycopy(permGids, 0, gids, 2, permGids.length);
3097                }
3098                gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
3099                gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));
3100            }
3101            checkTime(startTime, "startProcess: building args");
3102            if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) {
3103                if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3104                        && mTopComponent != null
3105                        && app.processName.equals(mTopComponent.getPackageName())) {
3106                    uid = 0;
3107                }
3108                if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL
3109                        && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
3110                    uid = 0;
3111                }
3112            }
3113            int debugFlags = 0;
3114            if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3115                debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
3116                // Also turn on CheckJNI for debuggable apps. It's quite
3117                // awkward to turn on otherwise.
3118                debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3119            }
3120            // Run the app in safe mode if its manifest requests so or the
3121            // system is booted in safe mode.
3122            if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
3123                mSafeMode == true) {
3124                debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
3125            }
3126            if ("1".equals(SystemProperties.get("debug.checkjni"))) {
3127                debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3128            }
3129            if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
3130                debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
3131            }
3132            if ("1".equals(SystemProperties.get("debug.assert"))) {
3133                debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
3134            }
3135
3136            String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
3137            if (requiredAbi == null) {
3138                requiredAbi = Build.SUPPORTED_ABIS[0];
3139            }
3140
3141            String instructionSet = null;
3142            if (app.info.primaryCpuAbi != null) {
3143                instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
3144            }
3145
3146            // Start the process.  It will either succeed and return a result containing
3147            // the PID of the new process, or else throw a RuntimeException.
3148            boolean isActivityProcess = (entryPoint == null);
3149            if (entryPoint == null) entryPoint = "android.app.ActivityThread";
3150            checkTime(startTime, "startProcess: asking zygote to start proc");
3151            Process.ProcessStartResult startResult = Process.start(entryPoint,
3152                    app.processName, uid, uid, gids, debugFlags, mountExternal,
3153                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
3154                    entryPointArgs);
3155            checkTime(startTime, "startProcess: returned from zygote!");
3156
3157            if (app.isolated) {
3158                mBatteryStatsService.addIsolatedUid(app.uid, app.info.uid);
3159            }
3160            mBatteryStatsService.noteProcessStart(app.processName, app.info.uid);
3161            checkTime(startTime, "startProcess: done updating battery stats");
3162
3163            EventLog.writeEvent(EventLogTags.AM_PROC_START,
3164                    UserHandle.getUserId(uid), startResult.pid, uid,
3165                    app.processName, hostingType,
3166                    hostingNameStr != null ? hostingNameStr : "");
3167
3168            if (app.persistent) {
3169                Watchdog.getInstance().processStarted(app.processName, startResult.pid);
3170            }
3171
3172            checkTime(startTime, "startProcess: building log message");
3173            StringBuilder buf = mStringBuilder;
3174            buf.setLength(0);
3175            buf.append("Start proc ");
3176            buf.append(app.processName);
3177            if (!isActivityProcess) {
3178                buf.append(" [");
3179                buf.append(entryPoint);
3180                buf.append("]");
3181            }
3182            buf.append(" for ");
3183            buf.append(hostingType);
3184            if (hostingNameStr != null) {
3185                buf.append(" ");
3186                buf.append(hostingNameStr);
3187            }
3188            buf.append(": pid=");
3189            buf.append(startResult.pid);
3190            buf.append(" uid=");
3191            buf.append(uid);
3192            buf.append(" gids={");
3193            if (gids != null) {
3194                for (int gi=0; gi<gids.length; gi++) {
3195                    if (gi != 0) buf.append(", ");
3196                    buf.append(gids[gi]);
3197
3198                }
3199            }
3200            buf.append("}");
3201            if (requiredAbi != null) {
3202                buf.append(" abi=");
3203                buf.append(requiredAbi);
3204            }
3205            Slog.i(TAG, buf.toString());
3206            app.setPid(startResult.pid);
3207            app.usingWrapper = startResult.usingWrapper;
3208            app.removed = false;
3209            app.killedByAm = false;
3210            checkTime(startTime, "startProcess: starting to update pids map");
3211            synchronized (mPidsSelfLocked) {
3212                this.mPidsSelfLocked.put(startResult.pid, app);
3213                if (isActivityProcess) {
3214                    Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
3215                    msg.obj = app;
3216                    mHandler.sendMessageDelayed(msg, startResult.usingWrapper
3217                            ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
3218                }
3219            }
3220            checkTime(startTime, "startProcess: done updating pids map");
3221        } catch (RuntimeException e) {
3222            // XXX do better error recovery.
3223            app.setPid(0);
3224            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
3225            if (app.isolated) {
3226                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
3227            }
3228            Slog.e(TAG, "Failure starting process " + app.processName, e);
3229        }
3230    }
3231
3232    void updateUsageStats(ActivityRecord component, boolean resumed) {
3233        if (DEBUG_SWITCH) Slog.d(TAG, "updateUsageStats: comp=" + component + "res=" + resumed);
3234        final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3235        if (resumed) {
3236            if (mUsageStatsService != null) {
3237                mUsageStatsService.reportEvent(component.realActivity, component.userId,
3238                        UsageEvents.Event.MOVE_TO_FOREGROUND);
3239            }
3240            synchronized (stats) {
3241                stats.noteActivityResumedLocked(component.app.uid);
3242            }
3243        } else {
3244            if (mUsageStatsService != null) {
3245                mUsageStatsService.reportEvent(component.realActivity, component.userId,
3246                        UsageEvents.Event.MOVE_TO_BACKGROUND);
3247            }
3248            synchronized (stats) {
3249                stats.noteActivityPausedLocked(component.app.uid);
3250            }
3251        }
3252    }
3253
3254    Intent getHomeIntent() {
3255        Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
3256        intent.setComponent(mTopComponent);
3257        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
3258            intent.addCategory(Intent.CATEGORY_HOME);
3259        }
3260        return intent;
3261    }
3262
3263    boolean startHomeActivityLocked(int userId) {
3264        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3265                && mTopAction == null) {
3266            // We are running in factory test mode, but unable to find
3267            // the factory test app, so just sit around displaying the
3268            // error message and don't try to start anything.
3269            return false;
3270        }
3271        Intent intent = getHomeIntent();
3272        ActivityInfo aInfo =
3273            resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
3274        if (aInfo != null) {
3275            intent.setComponent(new ComponentName(
3276                    aInfo.applicationInfo.packageName, aInfo.name));
3277            // Don't do this if the home app is currently being
3278            // instrumented.
3279            aInfo = new ActivityInfo(aInfo);
3280            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
3281            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
3282                    aInfo.applicationInfo.uid, true);
3283            if (app == null || app.instrumentationClass == null) {
3284                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
3285                mStackSupervisor.startHomeActivity(intent, aInfo);
3286            }
3287        }
3288
3289        return true;
3290    }
3291
3292    private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
3293        ActivityInfo ai = null;
3294        ComponentName comp = intent.getComponent();
3295        try {
3296            if (comp != null) {
3297                ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
3298            } else {
3299                ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
3300                        intent,
3301                        intent.resolveTypeIfNeeded(mContext.getContentResolver()),
3302                            flags, userId);
3303
3304                if (info != null) {
3305                    ai = info.activityInfo;
3306                }
3307            }
3308        } catch (RemoteException e) {
3309            // ignore
3310        }
3311
3312        return ai;
3313    }
3314
3315    /**
3316     * Starts the "new version setup screen" if appropriate.
3317     */
3318    void startSetupActivityLocked() {
3319        // Only do this once per boot.
3320        if (mCheckedForSetup) {
3321            return;
3322        }
3323
3324        // We will show this screen if the current one is a different
3325        // version than the last one shown, and we are not running in
3326        // low-level factory test mode.
3327        final ContentResolver resolver = mContext.getContentResolver();
3328        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL &&
3329                Settings.Global.getInt(resolver,
3330                        Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
3331            mCheckedForSetup = true;
3332
3333            // See if we should be showing the platform update setup UI.
3334            Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
3335            List<ResolveInfo> ris = mContext.getPackageManager()
3336                    .queryIntentActivities(intent, PackageManager.GET_META_DATA);
3337
3338            // We don't allow third party apps to replace this.
3339            ResolveInfo ri = null;
3340            for (int i=0; ris != null && i<ris.size(); i++) {
3341                if ((ris.get(i).activityInfo.applicationInfo.flags
3342                        & ApplicationInfo.FLAG_SYSTEM) != 0) {
3343                    ri = ris.get(i);
3344                    break;
3345                }
3346            }
3347
3348            if (ri != null) {
3349                String vers = ri.activityInfo.metaData != null
3350                        ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
3351                        : null;
3352                if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
3353                    vers = ri.activityInfo.applicationInfo.metaData.getString(
3354                            Intent.METADATA_SETUP_VERSION);
3355                }
3356                String lastVers = Settings.Secure.getString(
3357                        resolver, Settings.Secure.LAST_SETUP_SHOWN);
3358                if (vers != null && !vers.equals(lastVers)) {
3359                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3360                    intent.setComponent(new ComponentName(
3361                            ri.activityInfo.packageName, ri.activityInfo.name));
3362                    mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo,
3363                            null, null, null, null, 0, 0, 0, null, 0, 0, 0, null, false, null, null,
3364                            null);
3365                }
3366            }
3367        }
3368    }
3369
3370    CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
3371        return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
3372    }
3373
3374    void enforceNotIsolatedCaller(String caller) {
3375        if (UserHandle.isIsolated(Binder.getCallingUid())) {
3376            throw new SecurityException("Isolated process not allowed to call " + caller);
3377        }
3378    }
3379
3380    void enforceShellRestriction(String restriction, int userHandle) {
3381        if (Binder.getCallingUid() == Process.SHELL_UID) {
3382            if (userHandle < 0
3383                    || mUserManager.hasUserRestriction(restriction, userHandle)) {
3384                throw new SecurityException("Shell does not have permission to access user "
3385                        + userHandle);
3386            }
3387        }
3388    }
3389
3390    @Override
3391    public int getFrontActivityScreenCompatMode() {
3392        enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
3393        synchronized (this) {
3394            return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
3395        }
3396    }
3397
3398    @Override
3399    public void setFrontActivityScreenCompatMode(int mode) {
3400        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3401                "setFrontActivityScreenCompatMode");
3402        synchronized (this) {
3403            mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
3404        }
3405    }
3406
3407    @Override
3408    public int getPackageScreenCompatMode(String packageName) {
3409        enforceNotIsolatedCaller("getPackageScreenCompatMode");
3410        synchronized (this) {
3411            return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
3412        }
3413    }
3414
3415    @Override
3416    public void setPackageScreenCompatMode(String packageName, int mode) {
3417        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3418                "setPackageScreenCompatMode");
3419        synchronized (this) {
3420            mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
3421        }
3422    }
3423
3424    @Override
3425    public boolean getPackageAskScreenCompat(String packageName) {
3426        enforceNotIsolatedCaller("getPackageAskScreenCompat");
3427        synchronized (this) {
3428            return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
3429        }
3430    }
3431
3432    @Override
3433    public void setPackageAskScreenCompat(String packageName, boolean ask) {
3434        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3435                "setPackageAskScreenCompat");
3436        synchronized (this) {
3437            mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
3438        }
3439    }
3440
3441    private void dispatchProcessesChanged() {
3442        int N;
3443        synchronized (this) {
3444            N = mPendingProcessChanges.size();
3445            if (mActiveProcessChanges.length < N) {
3446                mActiveProcessChanges = new ProcessChangeItem[N];
3447            }
3448            mPendingProcessChanges.toArray(mActiveProcessChanges);
3449            mAvailProcessChanges.addAll(mPendingProcessChanges);
3450            mPendingProcessChanges.clear();
3451            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
3452        }
3453
3454        int i = mProcessObservers.beginBroadcast();
3455        while (i > 0) {
3456            i--;
3457            final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3458            if (observer != null) {
3459                try {
3460                    for (int j=0; j<N; j++) {
3461                        ProcessChangeItem item = mActiveProcessChanges[j];
3462                        if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
3463                            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
3464                                    + item.pid + " uid=" + item.uid + ": "
3465                                    + item.foregroundActivities);
3466                            observer.onForegroundActivitiesChanged(item.pid, item.uid,
3467                                    item.foregroundActivities);
3468                        }
3469                        if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) {
3470                            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "PROCSTATE CHANGED pid="
3471                                    + item.pid + " uid=" + item.uid + ": " + item.processState);
3472                            observer.onProcessStateChanged(item.pid, item.uid, item.processState);
3473                        }
3474                    }
3475                } catch (RemoteException e) {
3476                }
3477            }
3478        }
3479        mProcessObservers.finishBroadcast();
3480    }
3481
3482    private void dispatchProcessDied(int pid, int uid) {
3483        int i = mProcessObservers.beginBroadcast();
3484        while (i > 0) {
3485            i--;
3486            final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3487            if (observer != null) {
3488                try {
3489                    observer.onProcessDied(pid, uid);
3490                } catch (RemoteException e) {
3491                }
3492            }
3493        }
3494        mProcessObservers.finishBroadcast();
3495    }
3496
3497    @Override
3498    public final int startActivity(IApplicationThread caller, String callingPackage,
3499            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3500            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
3501        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
3502            resultWho, requestCode, startFlags, profilerInfo, options,
3503            UserHandle.getCallingUserId());
3504    }
3505
3506    @Override
3507    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3508            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3509            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
3510        enforceNotIsolatedCaller("startActivity");
3511        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3512                false, ALLOW_FULL_ONLY, "startActivity", null);
3513        // TODO: Switch to user app stacks here.
3514        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
3515                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
3516                profilerInfo, null, null, options, userId, null, null);
3517    }
3518
3519    @Override
3520    public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
3521            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3522            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
3523
3524        // This is very dangerous -- it allows you to perform a start activity (including
3525        // permission grants) as any app that may launch one of your own activities.  So
3526        // we will only allow this to be done from activities that are part of the core framework,
3527        // and then only when they are running as the system.
3528        final ActivityRecord sourceRecord;
3529        final int targetUid;
3530        final String targetPackage;
3531        synchronized (this) {
3532            if (resultTo == null) {
3533                throw new SecurityException("Must be called from an activity");
3534            }
3535            sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
3536            if (sourceRecord == null) {
3537                throw new SecurityException("Called with bad activity token: " + resultTo);
3538            }
3539            if (!sourceRecord.info.packageName.equals("android")) {
3540                throw new SecurityException(
3541                        "Must be called from an activity that is declared in the android package");
3542            }
3543            if (sourceRecord.app == null) {
3544                throw new SecurityException("Called without a process attached to activity");
3545            }
3546            if (UserHandle.getAppId(sourceRecord.app.uid) != Process.SYSTEM_UID) {
3547                // This is still okay, as long as this activity is running under the
3548                // uid of the original calling activity.
3549                if (sourceRecord.app.uid != sourceRecord.launchedFromUid) {
3550                    throw new SecurityException(
3551                            "Calling activity in uid " + sourceRecord.app.uid
3552                                    + " must be system uid or original calling uid "
3553                                    + sourceRecord.launchedFromUid);
3554                }
3555            }
3556            targetUid = sourceRecord.launchedFromUid;
3557            targetPackage = sourceRecord.launchedFromPackage;
3558        }
3559
3560        // TODO: Switch to user app stacks here.
3561        try {
3562            int ret = mStackSupervisor.startActivityMayWait(null, targetUid, targetPackage, intent,
3563                    resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null,
3564                    null, null, options, UserHandle.getUserId(sourceRecord.app.uid), null, null);
3565            return ret;
3566        } catch (SecurityException e) {
3567            // XXX need to figure out how to propagate to original app.
3568            // A SecurityException here is generally actually a fault of the original
3569            // calling activity (such as a fairly granting permissions), so propagate it
3570            // back to them.
3571            /*
3572            StringBuilder msg = new StringBuilder();
3573            msg.append("While launching");
3574            msg.append(intent.toString());
3575            msg.append(": ");
3576            msg.append(e.getMessage());
3577            */
3578            throw e;
3579        }
3580    }
3581
3582    @Override
3583    public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3584            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3585            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
3586        enforceNotIsolatedCaller("startActivityAndWait");
3587        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3588                false, ALLOW_FULL_ONLY, "startActivityAndWait", null);
3589        WaitResult res = new WaitResult();
3590        // TODO: Switch to user app stacks here.
3591        mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
3592                null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null,
3593                options, userId, null, null);
3594        return res;
3595    }
3596
3597    @Override
3598    public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
3599            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3600            int startFlags, Configuration config, Bundle options, int userId) {
3601        enforceNotIsolatedCaller("startActivityWithConfig");
3602        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3603                false, ALLOW_FULL_ONLY, "startActivityWithConfig", null);
3604        // TODO: Switch to user app stacks here.
3605        int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
3606                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
3607                null, null, config, options, userId, null, null);
3608        return ret;
3609    }
3610
3611    @Override
3612    public int startActivityIntentSender(IApplicationThread caller,
3613            IntentSender intent, Intent fillInIntent, String resolvedType,
3614            IBinder resultTo, String resultWho, int requestCode,
3615            int flagsMask, int flagsValues, Bundle options) {
3616        enforceNotIsolatedCaller("startActivityIntentSender");
3617        // Refuse possible leaked file descriptors
3618        if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3619            throw new IllegalArgumentException("File descriptors passed in Intent");
3620        }
3621
3622        IIntentSender sender = intent.getTarget();
3623        if (!(sender instanceof PendingIntentRecord)) {
3624            throw new IllegalArgumentException("Bad PendingIntent object");
3625        }
3626
3627        PendingIntentRecord pir = (PendingIntentRecord)sender;
3628
3629        synchronized (this) {
3630            // If this is coming from the currently resumed activity, it is
3631            // effectively saying that app switches are allowed at this point.
3632            final ActivityStack stack = getFocusedStack();
3633            if (stack.mResumedActivity != null &&
3634                    stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
3635                mAppSwitchesAllowedTime = 0;
3636            }
3637        }
3638        int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
3639                resultTo, resultWho, requestCode, flagsMask, flagsValues, options, null);
3640        return ret;
3641    }
3642
3643    @Override
3644    public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
3645            Intent intent, String resolvedType, IVoiceInteractionSession session,
3646            IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
3647            Bundle options, int userId) {
3648        if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION)
3649                != PackageManager.PERMISSION_GRANTED) {
3650            String msg = "Permission Denial: startVoiceActivity() from pid="
3651                    + Binder.getCallingPid()
3652                    + ", uid=" + Binder.getCallingUid()
3653                    + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION;
3654            Slog.w(TAG, msg);
3655            throw new SecurityException(msg);
3656        }
3657        if (session == null || interactor == null) {
3658            throw new NullPointerException("null session or interactor");
3659        }
3660        userId = handleIncomingUser(callingPid, callingUid, userId,
3661                false, ALLOW_FULL_ONLY, "startVoiceActivity", null);
3662        // TODO: Switch to user app stacks here.
3663        return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent,
3664                resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null,
3665                null, options, userId, null, null);
3666    }
3667
3668    @Override
3669    public boolean startNextMatchingActivity(IBinder callingActivity,
3670            Intent intent, Bundle options) {
3671        // Refuse possible leaked file descriptors
3672        if (intent != null && intent.hasFileDescriptors() == true) {
3673            throw new IllegalArgumentException("File descriptors passed in Intent");
3674        }
3675
3676        synchronized (this) {
3677            final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
3678            if (r == null) {
3679                ActivityOptions.abort(options);
3680                return false;
3681            }
3682            if (r.app == null || r.app.thread == null) {
3683                // The caller is not running...  d'oh!
3684                ActivityOptions.abort(options);
3685                return false;
3686            }
3687            intent = new Intent(intent);
3688            // The caller is not allowed to change the data.
3689            intent.setDataAndType(r.intent.getData(), r.intent.getType());
3690            // And we are resetting to find the next component...
3691            intent.setComponent(null);
3692
3693            final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3694
3695            ActivityInfo aInfo = null;
3696            try {
3697                List<ResolveInfo> resolves =
3698                    AppGlobals.getPackageManager().queryIntentActivities(
3699                            intent, r.resolvedType,
3700                            PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
3701                            UserHandle.getCallingUserId());
3702
3703                // Look for the original activity in the list...
3704                final int N = resolves != null ? resolves.size() : 0;
3705                for (int i=0; i<N; i++) {
3706                    ResolveInfo rInfo = resolves.get(i);
3707                    if (rInfo.activityInfo.packageName.equals(r.packageName)
3708                            && rInfo.activityInfo.name.equals(r.info.name)) {
3709                        // We found the current one...  the next matching is
3710                        // after it.
3711                        i++;
3712                        if (i<N) {
3713                            aInfo = resolves.get(i).activityInfo;
3714                        }
3715                        if (debug) {
3716                            Slog.v(TAG, "Next matching activity: found current " + r.packageName
3717                                    + "/" + r.info.name);
3718                            Slog.v(TAG, "Next matching activity: next is " + aInfo.packageName
3719                                    + "/" + aInfo.name);
3720                        }
3721                        break;
3722                    }
3723                }
3724            } catch (RemoteException e) {
3725            }
3726
3727            if (aInfo == null) {
3728                // Nobody who is next!
3729                ActivityOptions.abort(options);
3730                if (debug) Slog.d(TAG, "Next matching activity: nothing found");
3731                return false;
3732            }
3733
3734            intent.setComponent(new ComponentName(
3735                    aInfo.applicationInfo.packageName, aInfo.name));
3736            intent.setFlags(intent.getFlags()&~(
3737                    Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3738                    Intent.FLAG_ACTIVITY_CLEAR_TOP|
3739                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3740                    Intent.FLAG_ACTIVITY_NEW_TASK));
3741
3742            // Okay now we need to start the new activity, replacing the
3743            // currently running activity.  This is a little tricky because
3744            // we want to start the new one as if the current one is finished,
3745            // but not finish the current one first so that there is no flicker.
3746            // And thus...
3747            final boolean wasFinishing = r.finishing;
3748            r.finishing = true;
3749
3750            // Propagate reply information over to the new activity.
3751            final ActivityRecord resultTo = r.resultTo;
3752            final String resultWho = r.resultWho;
3753            final int requestCode = r.requestCode;
3754            r.resultTo = null;
3755            if (resultTo != null) {
3756                resultTo.removeResultsLocked(r, resultWho, requestCode);
3757            }
3758
3759            final long origId = Binder.clearCallingIdentity();
3760            int res = mStackSupervisor.startActivityLocked(r.app.thread, intent,
3761                    r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null,
3762                    resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage,
3763                    -1, r.launchedFromUid, 0, options, false, null, null, null);
3764            Binder.restoreCallingIdentity(origId);
3765
3766            r.finishing = wasFinishing;
3767            if (res != ActivityManager.START_SUCCESS) {
3768                return false;
3769            }
3770            return true;
3771        }
3772    }
3773
3774    @Override
3775    public final int startActivityFromRecents(int taskId, Bundle options) {
3776        if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) {
3777            String msg = "Permission Denial: startActivityFromRecents called without " +
3778                    START_TASKS_FROM_RECENTS;
3779            Slog.w(TAG, msg);
3780            throw new SecurityException(msg);
3781        }
3782        return startActivityFromRecentsInner(taskId, options);
3783    }
3784
3785    final int startActivityFromRecentsInner(int taskId, Bundle options) {
3786        final TaskRecord task;
3787        final int callingUid;
3788        final String callingPackage;
3789        final Intent intent;
3790        final int userId;
3791        synchronized (this) {
3792            task = recentTaskForIdLocked(taskId);
3793            if (task == null) {
3794                throw new IllegalArgumentException("Task " + taskId + " not found.");
3795            }
3796            callingUid = task.mCallingUid;
3797            callingPackage = task.mCallingPackage;
3798            intent = task.intent;
3799            intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
3800            userId = task.userId;
3801        }
3802        return startActivityInPackage(callingUid, callingPackage, intent, null, null, null, 0, 0,
3803                options, userId, null, task);
3804    }
3805
3806    final int startActivityInPackage(int uid, String callingPackage,
3807            Intent intent, String resolvedType, IBinder resultTo,
3808            String resultWho, int requestCode, int startFlags, Bundle options, int userId,
3809            IActivityContainer container, TaskRecord inTask) {
3810
3811        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3812                false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
3813
3814        // TODO: Switch to user app stacks here.
3815        int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent,
3816                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
3817                null, null, null, options, userId, container, inTask);
3818        return ret;
3819    }
3820
3821    @Override
3822    public final int startActivities(IApplicationThread caller, String callingPackage,
3823            Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
3824            int userId) {
3825        enforceNotIsolatedCaller("startActivities");
3826        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3827                false, ALLOW_FULL_ONLY, "startActivity", null);
3828        // TODO: Switch to user app stacks here.
3829        int ret = mStackSupervisor.startActivities(caller, -1, callingPackage, intents,
3830                resolvedTypes, resultTo, options, userId);
3831        return ret;
3832    }
3833
3834    final int startActivitiesInPackage(int uid, String callingPackage,
3835            Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3836            Bundle options, int userId) {
3837
3838        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3839                false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
3840        // TODO: Switch to user app stacks here.
3841        int ret = mStackSupervisor.startActivities(null, uid, callingPackage, intents, resolvedTypes,
3842                resultTo, options, userId);
3843        return ret;
3844    }
3845
3846    //explicitly remove thd old information in mRecentTasks when removing existing user.
3847    private void removeRecentTasksForUserLocked(int userId) {
3848        if(userId <= 0) {
3849            Slog.i(TAG, "Can't remove recent task on user " + userId);
3850            return;
3851        }
3852
3853        for (int i = mRecentTasks.size() - 1; i >= 0; --i) {
3854            TaskRecord tr = mRecentTasks.get(i);
3855            if (tr.userId == userId) {
3856                if(DEBUG_TASKS) Slog.i(TAG, "remove RecentTask " + tr
3857                        + " when finishing user" + userId);
3858                mRecentTasks.remove(i);
3859                tr.removedFromRecents(mTaskPersister);
3860            }
3861        }
3862
3863        // Remove tasks from persistent storage.
3864        mTaskPersister.wakeup(null, true);
3865    }
3866
3867    // Sort by taskId
3868    private Comparator<TaskRecord> mTaskRecordComparator = new Comparator<TaskRecord>() {
3869        @Override
3870        public int compare(TaskRecord lhs, TaskRecord rhs) {
3871            return rhs.taskId - lhs.taskId;
3872        }
3873    };
3874
3875    // Extract the affiliates of the chain containing mRecentTasks[start].
3876    private int processNextAffiliateChain(int start) {
3877        final TaskRecord startTask = mRecentTasks.get(start);
3878        final int affiliateId = startTask.mAffiliatedTaskId;
3879
3880        // Quick identification of isolated tasks. I.e. those not launched behind.
3881        if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
3882                startTask.mNextAffiliate == null) {
3883            // There is still a slim chance that there are other tasks that point to this task
3884            // and that the chain is so messed up that this task no longer points to them but
3885            // the gain of this optimization outweighs the risk.
3886            startTask.inRecents = true;
3887            return start + 1;
3888        }
3889
3890        // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
3891        mTmpRecents.clear();
3892        for (int i = mRecentTasks.size() - 1; i >= start; --i) {
3893            final TaskRecord task = mRecentTasks.get(i);
3894            if (task.mAffiliatedTaskId == affiliateId) {
3895                mRecentTasks.remove(i);
3896                mTmpRecents.add(task);
3897            }
3898        }
3899
3900        // Sort them all by taskId. That is the order they were create in and that order will
3901        // always be correct.
3902        Collections.sort(mTmpRecents, mTaskRecordComparator);
3903
3904        // Go through and fix up the linked list.
3905        // The first one is the end of the chain and has no next.
3906        final TaskRecord first = mTmpRecents.get(0);
3907        first.inRecents = true;
3908        if (first.mNextAffiliate != null) {
3909            Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
3910            first.setNextAffiliate(null);
3911            mTaskPersister.wakeup(first, false);
3912        }
3913        // Everything in the middle is doubly linked from next to prev.
3914        final int tmpSize = mTmpRecents.size();
3915        for (int i = 0; i < tmpSize - 1; ++i) {
3916            final TaskRecord next = mTmpRecents.get(i);
3917            final TaskRecord prev = mTmpRecents.get(i + 1);
3918            if (next.mPrevAffiliate != prev) {
3919                Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
3920                        " setting prev=" + prev);
3921                next.setPrevAffiliate(prev);
3922                mTaskPersister.wakeup(next, false);
3923            }
3924            if (prev.mNextAffiliate != next) {
3925                Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
3926                        " setting next=" + next);
3927                prev.setNextAffiliate(next);
3928                mTaskPersister.wakeup(prev, false);
3929            }
3930            prev.inRecents = true;
3931        }
3932        // The last one is the beginning of the list and has no prev.
3933        final TaskRecord last = mTmpRecents.get(tmpSize - 1);
3934        if (last.mPrevAffiliate != null) {
3935            Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
3936            last.setPrevAffiliate(null);
3937            mTaskPersister.wakeup(last, false);
3938        }
3939
3940        // Insert the group back into mRecentTasks at start.
3941        mRecentTasks.addAll(start, mTmpRecents);
3942
3943        // Let the caller know where we left off.
3944        return start + tmpSize;
3945    }
3946
3947    /**
3948     * Update the recent tasks lists: make sure tasks should still be here (their
3949     * applications / activities still exist), update their availability, fixup ordering
3950     * of affiliations.
3951     */
3952    void cleanupRecentTasksLocked(int userId) {
3953        if (mRecentTasks == null) {
3954            // Happens when called from the packagemanager broadcast before boot.
3955            return;
3956        }
3957
3958        final HashMap<ComponentName, ActivityInfo> availActCache = new HashMap<>();
3959        final HashMap<String, ApplicationInfo> availAppCache = new HashMap<>();
3960        final IPackageManager pm = AppGlobals.getPackageManager();
3961        final ActivityInfo dummyAct = new ActivityInfo();
3962        final ApplicationInfo dummyApp = new ApplicationInfo();
3963
3964        int N = mRecentTasks.size();
3965
3966        int[] users = userId == UserHandle.USER_ALL
3967                ? getUsersLocked() : new int[] { userId };
3968        for (int user : users) {
3969            for (int i = 0; i < N; i++) {
3970                TaskRecord task = mRecentTasks.get(i);
3971                if (task.userId != user) {
3972                    // Only look at tasks for the user ID of interest.
3973                    continue;
3974                }
3975                if (task.autoRemoveRecents && task.getTopActivity() == null) {
3976                    // This situation is broken, and we should just get rid of it now.
3977                    mRecentTasks.remove(i);
3978                    task.removedFromRecents(mTaskPersister);
3979                    i--;
3980                    N--;
3981                    Slog.w(TAG, "Removing auto-remove without activity: " + task);
3982                    continue;
3983                }
3984                // Check whether this activity is currently available.
3985                if (task.realActivity != null) {
3986                    ActivityInfo ai = availActCache.get(task.realActivity);
3987                    if (ai == null) {
3988                        try {
3989                            ai = pm.getActivityInfo(task.realActivity,
3990                                    PackageManager.GET_UNINSTALLED_PACKAGES
3991                                    | PackageManager.GET_DISABLED_COMPONENTS, user);
3992                        } catch (RemoteException e) {
3993                            // Will never happen.
3994                            continue;
3995                        }
3996                        if (ai == null) {
3997                            ai = dummyAct;
3998                        }
3999                        availActCache.put(task.realActivity, ai);
4000                    }
4001                    if (ai == dummyAct) {
4002                        // This could be either because the activity no longer exists, or the
4003                        // app is temporarily gone.  For the former we want to remove the recents
4004                        // entry; for the latter we want to mark it as unavailable.
4005                        ApplicationInfo app = availAppCache.get(task.realActivity.getPackageName());
4006                        if (app == null) {
4007                            try {
4008                                app = pm.getApplicationInfo(task.realActivity.getPackageName(),
4009                                        PackageManager.GET_UNINSTALLED_PACKAGES
4010                                        | PackageManager.GET_DISABLED_COMPONENTS, user);
4011                            } catch (RemoteException e) {
4012                                // Will never happen.
4013                                continue;
4014                            }
4015                            if (app == null) {
4016                                app = dummyApp;
4017                            }
4018                            availAppCache.put(task.realActivity.getPackageName(), app);
4019                        }
4020                        if (app == dummyApp || (app.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
4021                            // Doesn't exist any more!  Good-bye.
4022                            mRecentTasks.remove(i);
4023                            task.removedFromRecents(mTaskPersister);
4024                            i--;
4025                            N--;
4026                            Slog.w(TAG, "Removing no longer valid recent: " + task);
4027                            continue;
4028                        } else {
4029                            // Otherwise just not available for now.
4030                            if (task.isAvailable) {
4031                                if (DEBUG_RECENTS) Slog.d(TAG, "Making recent unavailable: "
4032                                        + task);
4033                            }
4034                            task.isAvailable = false;
4035                        }
4036                    } else {
4037                        if (!ai.enabled || !ai.applicationInfo.enabled
4038                                || (ai.applicationInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
4039                            if (task.isAvailable) {
4040                                if (DEBUG_RECENTS) Slog.d(TAG, "Making recent unavailable: "
4041                                        + task + " (enabled=" + ai.enabled + "/"
4042                                        + ai.applicationInfo.enabled +  " flags="
4043                                        + Integer.toHexString(ai.applicationInfo.flags) + ")");
4044                            }
4045                            task.isAvailable = false;
4046                        } else {
4047                            if (!task.isAvailable) {
4048                                if (DEBUG_RECENTS) Slog.d(TAG, "Making recent available: "
4049                                        + task);
4050                            }
4051                            task.isAvailable = true;
4052                        }
4053                    }
4054                }
4055            }
4056        }
4057
4058        // Verify the affiliate chain for each task.
4059        for (int i = 0; i < N; i = processNextAffiliateChain(i)) {
4060        }
4061
4062        mTmpRecents.clear();
4063        // mRecentTasks is now in sorted, affiliated order.
4064    }
4065
4066    private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) {
4067        int N = mRecentTasks.size();
4068        TaskRecord top = task;
4069        int topIndex = taskIndex;
4070        while (top.mNextAffiliate != null && topIndex > 0) {
4071            top = top.mNextAffiliate;
4072            topIndex--;
4073        }
4074        if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding affilliates starting at "
4075                + topIndex + " from intial " + taskIndex);
4076        // Find the end of the chain, doing a sanity check along the way.
4077        boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
4078        int endIndex = topIndex;
4079        TaskRecord prev = top;
4080        while (endIndex < N) {
4081            TaskRecord cur = mRecentTasks.get(endIndex);
4082            if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: looking at next chain @"
4083                    + endIndex + " " + cur);
4084            if (cur == top) {
4085                // Verify start of the chain.
4086                if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != -1) {
4087                    Slog.wtf(TAG, "Bad chain @" + endIndex
4088                            + ": first task has next affiliate: " + prev);
4089                    sane = false;
4090                    break;
4091                }
4092            } else {
4093                // Verify middle of the chain's next points back to the one before.
4094                if (cur.mNextAffiliate != prev
4095                        || cur.mNextAffiliateTaskId != prev.taskId) {
4096                    Slog.wtf(TAG, "Bad chain @" + endIndex
4097                            + ": middle task " + cur + " @" + endIndex
4098                            + " has bad next affiliate "
4099                            + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
4100                            + ", expected " + prev);
4101                    sane = false;
4102                    break;
4103                }
4104            }
4105            if (cur.mPrevAffiliateTaskId == -1) {
4106                // Chain ends here.
4107                if (cur.mPrevAffiliate != null) {
4108                    Slog.wtf(TAG, "Bad chain @" + endIndex
4109                            + ": last task " + cur + " has previous affiliate "
4110                            + cur.mPrevAffiliate);
4111                    sane = false;
4112                }
4113                if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: end of chain @" + endIndex);
4114                break;
4115            } else {
4116                // Verify middle of the chain's prev points to a valid item.
4117                if (cur.mPrevAffiliate == null) {
4118                    Slog.wtf(TAG, "Bad chain @" + endIndex
4119                            + ": task " + cur + " has previous affiliate "
4120                            + cur.mPrevAffiliate + " but should be id "
4121                            + cur.mPrevAffiliate);
4122                    sane = false;
4123                    break;
4124                }
4125            }
4126            if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
4127                Slog.wtf(TAG, "Bad chain @" + endIndex
4128                        + ": task " + cur + " has affiliated id "
4129                        + cur.mAffiliatedTaskId + " but should be "
4130                        + task.mAffiliatedTaskId);
4131                sane = false;
4132                break;
4133            }
4134            prev = cur;
4135            endIndex++;
4136            if (endIndex >= N) {
4137                Slog.wtf(TAG, "Bad chain ran off index " + endIndex
4138                        + ": last task " + prev);
4139                sane = false;
4140                break;
4141            }
4142        }
4143        if (sane) {
4144            if (endIndex < taskIndex) {
4145                Slog.wtf(TAG, "Bad chain @" + endIndex
4146                        + ": did not extend to task " + task + " @" + taskIndex);
4147                sane = false;
4148            }
4149        }
4150        if (sane) {
4151            // All looks good, we can just move all of the affiliated tasks
4152            // to the top.
4153            for (int i=topIndex; i<=endIndex; i++) {
4154                if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving affiliated " + task
4155                        + " from " + i + " to " + (i-topIndex));
4156                TaskRecord cur = mRecentTasks.remove(i);
4157                mRecentTasks.add(i-topIndex, cur);
4158            }
4159            if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: done moving tasks  " +  topIndex
4160                    + " to " + endIndex);
4161            return true;
4162        }
4163
4164        // Whoops, couldn't do it.
4165        return false;
4166    }
4167
4168    final void addRecentTaskLocked(TaskRecord task) {
4169        final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
4170                || task.mNextAffiliateTaskId != -1 || task.mPrevAffiliateTaskId != -1;
4171
4172        int N = mRecentTasks.size();
4173        // Quick case: check if the top-most recent task is the same.
4174        if (!isAffiliated && N > 0 && mRecentTasks.get(0) == task) {
4175            if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: already at top: " + task);
4176            return;
4177        }
4178        // Another quick case: check if this is part of a set of affiliated
4179        // tasks that are at the top.
4180        if (isAffiliated && N > 0 && task.inRecents
4181                && task.mAffiliatedTaskId == mRecentTasks.get(0).mAffiliatedTaskId) {
4182            if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: affiliated " + mRecentTasks.get(0)
4183                    + " at top when adding " + task);
4184            return;
4185        }
4186        // Another quick case: never add voice sessions.
4187        if (task.voiceSession != null) {
4188            if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: not adding voice interaction " + task);
4189            return;
4190        }
4191
4192        boolean needAffiliationFix = false;
4193
4194        // Slightly less quick case: the task is already in recents, so all we need
4195        // to do is move it.
4196        if (task.inRecents) {
4197            int taskIndex = mRecentTasks.indexOf(task);
4198            if (taskIndex >= 0) {
4199                if (!isAffiliated) {
4200                    // Simple case: this is not an affiliated task, so we just move it to the front.
4201                    mRecentTasks.remove(taskIndex);
4202                    mRecentTasks.add(0, task);
4203                    notifyTaskPersisterLocked(task, false);
4204                    if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving to top " + task
4205                            + " from " + taskIndex);
4206                    return;
4207                } else {
4208                    // More complicated: need to keep all affiliated tasks together.
4209                    if (moveAffiliatedTasksToFront(task, taskIndex)) {
4210                        // All went well.
4211                        return;
4212                    }
4213
4214                    // Uh oh...  something bad in the affiliation chain, try to rebuild
4215                    // everything and then go through our general path of adding a new task.
4216                    needAffiliationFix = true;
4217                }
4218            } else {
4219                Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
4220                needAffiliationFix = true;
4221            }
4222        }
4223
4224        if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: trimming tasks for " + task);
4225        trimRecentsForTask(task, true);
4226
4227        N = mRecentTasks.size();
4228        while (N >= ActivityManager.getMaxRecentTasksStatic()) {
4229            final TaskRecord tr = mRecentTasks.remove(N - 1);
4230            tr.removedFromRecents(mTaskPersister);
4231            N--;
4232        }
4233        task.inRecents = true;
4234        if (!isAffiliated || needAffiliationFix) {
4235            // If this is a simple non-affiliated task, or we had some failure trying to
4236            // handle it as part of an affilated task, then just place it at the top.
4237            mRecentTasks.add(0, task);
4238        } else if (isAffiliated) {
4239            // If this is a new affiliated task, then move all of the affiliated tasks
4240            // to the front and insert this new one.
4241            TaskRecord other = task.mNextAffiliate;
4242            if (other == null) {
4243                other = task.mPrevAffiliate;
4244            }
4245            if (other != null) {
4246                int otherIndex = mRecentTasks.indexOf(other);
4247                if (otherIndex >= 0) {
4248                    // Insert new task at appropriate location.
4249                    int taskIndex;
4250                    if (other == task.mNextAffiliate) {
4251                        // We found the index of our next affiliation, which is who is
4252                        // before us in the list, so add after that point.
4253                        taskIndex = otherIndex+1;
4254                    } else {
4255                        // We found the index of our previous affiliation, which is who is
4256                        // after us in the list, so add at their position.
4257                        taskIndex = otherIndex;
4258                    }
4259                    if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: new affiliated task added at "
4260                            + taskIndex + ": " + task);
4261                    mRecentTasks.add(taskIndex, task);
4262
4263                    // Now move everything to the front.
4264                    if (moveAffiliatedTasksToFront(task, taskIndex)) {
4265                        // All went well.
4266                        return;
4267                    }
4268
4269                    // Uh oh...  something bad in the affiliation chain, try to rebuild
4270                    // everything and then go through our general path of adding a new task.
4271                    needAffiliationFix = true;
4272                } else {
4273                    if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: couldn't find other affiliation "
4274                            + other);
4275                    needAffiliationFix = true;
4276                }
4277            } else {
4278                if (DEBUG_RECENTS) Slog.d(TAG,
4279                        "addRecent: adding affiliated task without next/prev:" + task);
4280                needAffiliationFix = true;
4281            }
4282        }
4283        if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding " + task);
4284
4285        if (needAffiliationFix) {
4286            if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: regrouping affiliations");
4287            cleanupRecentTasksLocked(task.userId);
4288        }
4289    }
4290
4291    /**
4292     * If needed, remove oldest existing entries in recents that are for the same kind
4293     * of task as the given one.
4294     */
4295    int trimRecentsForTask(TaskRecord task, boolean doTrim) {
4296        int N = mRecentTasks.size();
4297        final Intent intent = task.intent;
4298        final boolean document = intent != null && intent.isDocument();
4299
4300        int maxRecents = task.maxRecents - 1;
4301        for (int i=0; i<N; i++) {
4302            final TaskRecord tr = mRecentTasks.get(i);
4303            if (task != tr) {
4304                if (task.userId != tr.userId) {
4305                    continue;
4306                }
4307                if (i > MAX_RECENT_BITMAPS) {
4308                    tr.freeLastThumbnail();
4309                }
4310                final Intent trIntent = tr.intent;
4311                if ((task.affinity == null || !task.affinity.equals(tr.affinity)) &&
4312                    (intent == null || !intent.filterEquals(trIntent))) {
4313                    continue;
4314                }
4315                final boolean trIsDocument = trIntent != null && trIntent.isDocument();
4316                if (document && trIsDocument) {
4317                    // These are the same document activity (not necessarily the same doc).
4318                    if (maxRecents > 0) {
4319                        --maxRecents;
4320                        continue;
4321                    }
4322                    // Hit the maximum number of documents for this task. Fall through
4323                    // and remove this document from recents.
4324                } else if (document || trIsDocument) {
4325                    // Only one of these is a document. Not the droid we're looking for.
4326                    continue;
4327                }
4328            }
4329
4330            if (!doTrim) {
4331                // If the caller is not actually asking for a trim, just tell them we reached
4332                // a point where the trim would happen.
4333                return i;
4334            }
4335
4336            // Either task and tr are the same or, their affinities match or their intents match
4337            // and neither of them is a document, or they are documents using the same activity
4338            // and their maxRecents has been reached.
4339            tr.disposeThumbnail();
4340            mRecentTasks.remove(i);
4341            if (task != tr) {
4342                tr.removedFromRecents(mTaskPersister);
4343            }
4344            i--;
4345            N--;
4346            if (task.intent == null) {
4347                // If the new recent task we are adding is not fully
4348                // specified, then replace it with the existing recent task.
4349                task = tr;
4350            }
4351            notifyTaskPersisterLocked(tr, false);
4352        }
4353
4354        return -1;
4355    }
4356
4357    @Override
4358    public void reportActivityFullyDrawn(IBinder token) {
4359        synchronized (this) {
4360            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4361            if (r == null) {
4362                return;
4363            }
4364            r.reportFullyDrawnLocked();
4365        }
4366    }
4367
4368    @Override
4369    public void setRequestedOrientation(IBinder token, int requestedOrientation) {
4370        synchronized (this) {
4371            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4372            if (r == null) {
4373                return;
4374            }
4375            final long origId = Binder.clearCallingIdentity();
4376            mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
4377            Configuration config = mWindowManager.updateOrientationFromAppTokens(
4378                    mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
4379            if (config != null) {
4380                r.frozenBeforeDestroy = true;
4381                if (!updateConfigurationLocked(config, r, false, false)) {
4382                    mStackSupervisor.resumeTopActivitiesLocked();
4383                }
4384            }
4385            Binder.restoreCallingIdentity(origId);
4386        }
4387    }
4388
4389    @Override
4390    public int getRequestedOrientation(IBinder token) {
4391        synchronized (this) {
4392            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4393            if (r == null) {
4394                return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
4395            }
4396            return mWindowManager.getAppOrientation(r.appToken);
4397        }
4398    }
4399
4400    /**
4401     * This is the internal entry point for handling Activity.finish().
4402     *
4403     * @param token The Binder token referencing the Activity we want to finish.
4404     * @param resultCode Result code, if any, from this Activity.
4405     * @param resultData Result data (Intent), if any, from this Activity.
4406     * @param finishTask Whether to finish the task associated with this Activity.  Only applies to
4407     *            the root Activity in the task.
4408     *
4409     * @return Returns true if the activity successfully finished, or false if it is still running.
4410     */
4411    @Override
4412    public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
4413            boolean finishTask) {
4414        // Refuse possible leaked file descriptors
4415        if (resultData != null && resultData.hasFileDescriptors() == true) {
4416            throw new IllegalArgumentException("File descriptors passed in Intent");
4417        }
4418
4419        synchronized(this) {
4420            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4421            if (r == null) {
4422                return true;
4423            }
4424            // Keep track of the root activity of the task before we finish it
4425            TaskRecord tr = r.task;
4426            ActivityRecord rootR = tr.getRootActivity();
4427            // Do not allow task to finish in Lock Task mode.
4428            if (tr == mStackSupervisor.mLockTaskModeTask) {
4429                if (rootR == r) {
4430                    mStackSupervisor.showLockTaskToast();
4431                    return false;
4432                }
4433            }
4434            if (mController != null) {
4435                // Find the first activity that is not finishing.
4436                ActivityRecord next = r.task.stack.topRunningActivityLocked(token, 0);
4437                if (next != null) {
4438                    // ask watcher if this is allowed
4439                    boolean resumeOK = true;
4440                    try {
4441                        resumeOK = mController.activityResuming(next.packageName);
4442                    } catch (RemoteException e) {
4443                        mController = null;
4444                        Watchdog.getInstance().setActivityController(null);
4445                    }
4446
4447                    if (!resumeOK) {
4448                        return false;
4449                    }
4450                }
4451            }
4452            final long origId = Binder.clearCallingIdentity();
4453            try {
4454                boolean res;
4455                if (finishTask && r == rootR) {
4456                    // If requested, remove the task that is associated to this activity only if it
4457                    // was the root activity in the task.  The result code and data is ignored because
4458                    // we don't support returning them across task boundaries.
4459                    res = removeTaskByIdLocked(tr.taskId, 0);
4460                } else {
4461                    res = tr.stack.requestFinishActivityLocked(token, resultCode,
4462                            resultData, "app-request", true);
4463                }
4464                return res;
4465            } finally {
4466                Binder.restoreCallingIdentity(origId);
4467            }
4468        }
4469    }
4470
4471    @Override
4472    public final void finishHeavyWeightApp() {
4473        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4474                != PackageManager.PERMISSION_GRANTED) {
4475            String msg = "Permission Denial: finishHeavyWeightApp() from pid="
4476                    + Binder.getCallingPid()
4477                    + ", uid=" + Binder.getCallingUid()
4478                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4479            Slog.w(TAG, msg);
4480            throw new SecurityException(msg);
4481        }
4482
4483        synchronized(this) {
4484            if (mHeavyWeightProcess == null) {
4485                return;
4486            }
4487
4488            ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
4489                    mHeavyWeightProcess.activities);
4490            for (int i=0; i<activities.size(); i++) {
4491                ActivityRecord r = activities.get(i);
4492                if (!r.finishing) {
4493                    r.task.stack.finishActivityLocked(r, Activity.RESULT_CANCELED,
4494                            null, "finish-heavy", true);
4495                }
4496            }
4497
4498            mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4499                    mHeavyWeightProcess.userId, 0));
4500            mHeavyWeightProcess = null;
4501        }
4502    }
4503
4504    @Override
4505    public void crashApplication(int uid, int initialPid, String packageName,
4506            String message) {
4507        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4508                != PackageManager.PERMISSION_GRANTED) {
4509            String msg = "Permission Denial: crashApplication() from pid="
4510                    + Binder.getCallingPid()
4511                    + ", uid=" + Binder.getCallingUid()
4512                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4513            Slog.w(TAG, msg);
4514            throw new SecurityException(msg);
4515        }
4516
4517        synchronized(this) {
4518            ProcessRecord proc = null;
4519
4520            // Figure out which process to kill.  We don't trust that initialPid
4521            // still has any relation to current pids, so must scan through the
4522            // list.
4523            synchronized (mPidsSelfLocked) {
4524                for (int i=0; i<mPidsSelfLocked.size(); i++) {
4525                    ProcessRecord p = mPidsSelfLocked.valueAt(i);
4526                    if (p.uid != uid) {
4527                        continue;
4528                    }
4529                    if (p.pid == initialPid) {
4530                        proc = p;
4531                        break;
4532                    }
4533                    if (p.pkgList.containsKey(packageName)) {
4534                        proc = p;
4535                    }
4536                }
4537            }
4538
4539            if (proc == null) {
4540                Slog.w(TAG, "crashApplication: nothing for uid=" + uid
4541                        + " initialPid=" + initialPid
4542                        + " packageName=" + packageName);
4543                return;
4544            }
4545
4546            if (proc.thread != null) {
4547                if (proc.pid == Process.myPid()) {
4548                    Log.w(TAG, "crashApplication: trying to crash self!");
4549                    return;
4550                }
4551                long ident = Binder.clearCallingIdentity();
4552                try {
4553                    proc.thread.scheduleCrash(message);
4554                } catch (RemoteException e) {
4555                }
4556                Binder.restoreCallingIdentity(ident);
4557            }
4558        }
4559    }
4560
4561    @Override
4562    public final void finishSubActivity(IBinder token, String resultWho,
4563            int requestCode) {
4564        synchronized(this) {
4565            final long origId = Binder.clearCallingIdentity();
4566            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4567            if (r != null) {
4568                r.task.stack.finishSubActivityLocked(r, resultWho, requestCode);
4569            }
4570            Binder.restoreCallingIdentity(origId);
4571        }
4572    }
4573
4574    @Override
4575    public boolean finishActivityAffinity(IBinder token) {
4576        synchronized(this) {
4577            final long origId = Binder.clearCallingIdentity();
4578            try {
4579                ActivityRecord r = ActivityRecord.isInStackLocked(token);
4580
4581                ActivityRecord rootR = r.task.getRootActivity();
4582                // Do not allow task to finish in Lock Task mode.
4583                if (r.task == mStackSupervisor.mLockTaskModeTask) {
4584                    if (rootR == r) {
4585                        mStackSupervisor.showLockTaskToast();
4586                        return false;
4587                    }
4588                }
4589                boolean res = false;
4590                if (r != null) {
4591                    res = r.task.stack.finishActivityAffinityLocked(r);
4592                }
4593                return res;
4594            } finally {
4595                Binder.restoreCallingIdentity(origId);
4596            }
4597        }
4598    }
4599
4600    @Override
4601    public void finishVoiceTask(IVoiceInteractionSession session) {
4602        synchronized(this) {
4603            final long origId = Binder.clearCallingIdentity();
4604            try {
4605                mStackSupervisor.finishVoiceTask(session);
4606            } finally {
4607                Binder.restoreCallingIdentity(origId);
4608            }
4609        }
4610
4611    }
4612
4613    @Override
4614    public boolean releaseActivityInstance(IBinder token) {
4615        synchronized(this) {
4616            final long origId = Binder.clearCallingIdentity();
4617            try {
4618                ActivityRecord r = ActivityRecord.isInStackLocked(token);
4619                if (r.task == null || r.task.stack == null) {
4620                    return false;
4621                }
4622                return r.task.stack.safelyDestroyActivityLocked(r, "app-req");
4623            } finally {
4624                Binder.restoreCallingIdentity(origId);
4625            }
4626        }
4627    }
4628
4629    @Override
4630    public void releaseSomeActivities(IApplicationThread appInt) {
4631        synchronized(this) {
4632            final long origId = Binder.clearCallingIdentity();
4633            try {
4634                ProcessRecord app = getRecordForAppLocked(appInt);
4635                mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
4636            } finally {
4637                Binder.restoreCallingIdentity(origId);
4638            }
4639        }
4640    }
4641
4642    @Override
4643    public boolean willActivityBeVisible(IBinder token) {
4644        synchronized(this) {
4645            ActivityStack stack = ActivityRecord.getStackLocked(token);
4646            if (stack != null) {
4647                return stack.willActivityBeVisibleLocked(token);
4648            }
4649            return false;
4650        }
4651    }
4652
4653    @Override
4654    public void overridePendingTransition(IBinder token, String packageName,
4655            int enterAnim, int exitAnim) {
4656        synchronized(this) {
4657            ActivityRecord self = ActivityRecord.isInStackLocked(token);
4658            if (self == null) {
4659                return;
4660            }
4661
4662            final long origId = Binder.clearCallingIdentity();
4663
4664            if (self.state == ActivityState.RESUMED
4665                    || self.state == ActivityState.PAUSING) {
4666                mWindowManager.overridePendingAppTransition(packageName,
4667                        enterAnim, exitAnim, null);
4668            }
4669
4670            Binder.restoreCallingIdentity(origId);
4671        }
4672    }
4673
4674    /**
4675     * Main function for removing an existing process from the activity manager
4676     * as a result of that process going away.  Clears out all connections
4677     * to the process.
4678     */
4679    private final void handleAppDiedLocked(ProcessRecord app,
4680            boolean restarting, boolean allowRestart) {
4681        int pid = app.pid;
4682        cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
4683        if (!restarting) {
4684            removeLruProcessLocked(app);
4685            if (pid > 0) {
4686                ProcessList.remove(pid);
4687            }
4688        }
4689
4690        if (mProfileProc == app) {
4691            clearProfilerLocked();
4692        }
4693
4694        // Remove this application's activities from active lists.
4695        boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app);
4696
4697        app.activities.clear();
4698
4699        if (app.instrumentationClass != null) {
4700            Slog.w(TAG, "Crash of app " + app.processName
4701                  + " running instrumentation " + app.instrumentationClass);
4702            Bundle info = new Bundle();
4703            info.putString("shortMsg", "Process crashed.");
4704            finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
4705        }
4706
4707        if (!restarting) {
4708            if (!mStackSupervisor.resumeTopActivitiesLocked()) {
4709                // If there was nothing to resume, and we are not already
4710                // restarting this process, but there is a visible activity that
4711                // is hosted by the process...  then make sure all visible
4712                // activities are running, taking care of restarting this
4713                // process.
4714                if (hasVisibleActivities) {
4715                    mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
4716                }
4717            }
4718        }
4719    }
4720
4721    private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
4722        IBinder threadBinder = thread.asBinder();
4723        // Find the application record.
4724        for (int i=mLruProcesses.size()-1; i>=0; i--) {
4725            ProcessRecord rec = mLruProcesses.get(i);
4726            if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
4727                return i;
4728            }
4729        }
4730        return -1;
4731    }
4732
4733    final ProcessRecord getRecordForAppLocked(
4734            IApplicationThread thread) {
4735        if (thread == null) {
4736            return null;
4737        }
4738
4739        int appIndex = getLRURecordIndexForAppLocked(thread);
4740        return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
4741    }
4742
4743    final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
4744        // If there are no longer any background processes running,
4745        // and the app that died was not running instrumentation,
4746        // then tell everyone we are now low on memory.
4747        boolean haveBg = false;
4748        for (int i=mLruProcesses.size()-1; i>=0; i--) {
4749            ProcessRecord rec = mLruProcesses.get(i);
4750            if (rec.thread != null
4751                    && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
4752                haveBg = true;
4753                break;
4754            }
4755        }
4756
4757        if (!haveBg) {
4758            boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
4759            if (doReport) {
4760                long now = SystemClock.uptimeMillis();
4761                if (now < (mLastMemUsageReportTime+5*60*1000)) {
4762                    doReport = false;
4763                } else {
4764                    mLastMemUsageReportTime = now;
4765                }
4766            }
4767            final ArrayList<ProcessMemInfo> memInfos
4768                    = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null;
4769            EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
4770            long now = SystemClock.uptimeMillis();
4771            for (int i=mLruProcesses.size()-1; i>=0; i--) {
4772                ProcessRecord rec = mLruProcesses.get(i);
4773                if (rec == dyingProc || rec.thread == null) {
4774                    continue;
4775                }
4776                if (doReport) {
4777                    memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
4778                            rec.setProcState, rec.adjType, rec.makeAdjReason()));
4779                }
4780                if ((rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
4781                    // The low memory report is overriding any current
4782                    // state for a GC request.  Make sure to do
4783                    // heavy/important/visible/foreground processes first.
4784                    if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
4785                        rec.lastRequestedGc = 0;
4786                    } else {
4787                        rec.lastRequestedGc = rec.lastLowMemory;
4788                    }
4789                    rec.reportLowMemory = true;
4790                    rec.lastLowMemory = now;
4791                    mProcessesToGc.remove(rec);
4792                    addProcessToGcListLocked(rec);
4793                }
4794            }
4795            if (doReport) {
4796                Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
4797                mHandler.sendMessage(msg);
4798            }
4799            scheduleAppGcsLocked();
4800        }
4801    }
4802
4803    final void appDiedLocked(ProcessRecord app) {
4804       appDiedLocked(app, app.pid, app.thread);
4805    }
4806
4807    final void appDiedLocked(ProcessRecord app, int pid,
4808            IApplicationThread thread) {
4809
4810        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
4811        synchronized (stats) {
4812            stats.noteProcessDiedLocked(app.info.uid, pid);
4813        }
4814
4815        Process.killProcessGroup(app.info.uid, pid);
4816
4817        // Clean up already done if the process has been re-started.
4818        if (app.pid == pid && app.thread != null &&
4819                app.thread.asBinder() == thread.asBinder()) {
4820            boolean doLowMem = app.instrumentationClass == null;
4821            boolean doOomAdj = doLowMem;
4822            if (!app.killedByAm) {
4823                Slog.i(TAG, "Process " + app.processName + " (pid " + pid
4824                        + ") has died.");
4825                mAllowLowerMemLevel = true;
4826            } else {
4827                // Note that we always want to do oom adj to update our state with the
4828                // new number of procs.
4829                mAllowLowerMemLevel = false;
4830                doLowMem = false;
4831            }
4832            EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
4833            if (DEBUG_CLEANUP) Slog.v(
4834                TAG, "Dying app: " + app + ", pid: " + pid
4835                + ", thread: " + thread.asBinder());
4836            handleAppDiedLocked(app, false, true);
4837
4838            if (doOomAdj) {
4839                updateOomAdjLocked();
4840            }
4841            if (doLowMem) {
4842                doLowMemReportIfNeededLocked(app);
4843            }
4844        } else if (app.pid != pid) {
4845            // A new process has already been started.
4846            Slog.i(TAG, "Process " + app.processName + " (pid " + pid
4847                    + ") has died and restarted (pid " + app.pid + ").");
4848            EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
4849        } else if (DEBUG_PROCESSES) {
4850            Slog.d(TAG, "Received spurious death notification for thread "
4851                    + thread.asBinder());
4852        }
4853    }
4854
4855    /**
4856     * If a stack trace dump file is configured, dump process stack traces.
4857     * @param clearTraces causes the dump file to be erased prior to the new
4858     *    traces being written, if true; when false, the new traces will be
4859     *    appended to any existing file content.
4860     * @param firstPids of dalvik VM processes to dump stack traces for first
4861     * @param lastPids of dalvik VM processes to dump stack traces for last
4862     * @param nativeProcs optional list of native process names to dump stack crawls
4863     * @return file containing stack traces, or null if no dump file is configured
4864     */
4865    public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
4866            ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
4867        String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4868        if (tracesPath == null || tracesPath.length() == 0) {
4869            return null;
4870        }
4871
4872        File tracesFile = new File(tracesPath);
4873        try {
4874            File tracesDir = tracesFile.getParentFile();
4875            if (!tracesDir.exists()) {
4876                tracesDir.mkdirs();
4877                if (!SELinux.restorecon(tracesDir)) {
4878                    return null;
4879                }
4880            }
4881            FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
4882
4883            if (clearTraces && tracesFile.exists()) tracesFile.delete();
4884            tracesFile.createNewFile();
4885            FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4886        } catch (IOException e) {
4887            Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
4888            return null;
4889        }
4890
4891        dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativeProcs);
4892        return tracesFile;
4893    }
4894
4895    private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
4896            ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
4897        // Use a FileObserver to detect when traces finish writing.
4898        // The order of traces is considered important to maintain for legibility.
4899        FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
4900            @Override
4901            public synchronized void onEvent(int event, String path) { notify(); }
4902        };
4903
4904        try {
4905            observer.startWatching();
4906
4907            // First collect all of the stacks of the most important pids.
4908            if (firstPids != null) {
4909                try {
4910                    int num = firstPids.size();
4911                    for (int i = 0; i < num; i++) {
4912                        synchronized (observer) {
4913                            Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
4914                            observer.wait(200);  // Wait for write-close, give up after 200msec
4915                        }
4916                    }
4917                } catch (InterruptedException e) {
4918                    Log.wtf(TAG, e);
4919                }
4920            }
4921
4922            // Next collect the stacks of the native pids
4923            if (nativeProcs != null) {
4924                int[] pids = Process.getPidsForCommands(nativeProcs);
4925                if (pids != null) {
4926                    for (int pid : pids) {
4927                        Debug.dumpNativeBacktraceToFile(pid, tracesPath);
4928                    }
4929                }
4930            }
4931
4932            // Lastly, measure CPU usage.
4933            if (processCpuTracker != null) {
4934                processCpuTracker.init();
4935                System.gc();
4936                processCpuTracker.update();
4937                try {
4938                    synchronized (processCpuTracker) {
4939                        processCpuTracker.wait(500); // measure over 1/2 second.
4940                    }
4941                } catch (InterruptedException e) {
4942                }
4943                processCpuTracker.update();
4944
4945                // We'll take the stack crawls of just the top apps using CPU.
4946                final int N = processCpuTracker.countWorkingStats();
4947                int numProcs = 0;
4948                for (int i=0; i<N && numProcs<5; i++) {
4949                    ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
4950                    if (lastPids.indexOfKey(stats.pid) >= 0) {
4951                        numProcs++;
4952                        try {
4953                            synchronized (observer) {
4954                                Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
4955                                observer.wait(200);  // Wait for write-close, give up after 200msec
4956                            }
4957                        } catch (InterruptedException e) {
4958                            Log.wtf(TAG, e);
4959                        }
4960
4961                    }
4962                }
4963            }
4964        } finally {
4965            observer.stopWatching();
4966        }
4967    }
4968
4969    final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
4970        if (true || IS_USER_BUILD) {
4971            return;
4972        }
4973        String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4974        if (tracesPath == null || tracesPath.length() == 0) {
4975            return;
4976        }
4977
4978        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4979        StrictMode.allowThreadDiskWrites();
4980        try {
4981            final File tracesFile = new File(tracesPath);
4982            final File tracesDir = tracesFile.getParentFile();
4983            final File tracesTmp = new File(tracesDir, "__tmp__");
4984            try {
4985                if (!tracesDir.exists()) {
4986                    tracesDir.mkdirs();
4987                    if (!SELinux.restorecon(tracesDir.getPath())) {
4988                        return;
4989                    }
4990                }
4991                FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
4992
4993                if (tracesFile.exists()) {
4994                    tracesTmp.delete();
4995                    tracesFile.renameTo(tracesTmp);
4996                }
4997                StringBuilder sb = new StringBuilder();
4998                Time tobj = new Time();
4999                tobj.set(System.currentTimeMillis());
5000                sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5001                sb.append(": ");
5002                TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5003                sb.append(" since ");
5004                sb.append(msg);
5005                FileOutputStream fos = new FileOutputStream(tracesFile);
5006                fos.write(sb.toString().getBytes());
5007                if (app == null) {
5008                    fos.write("\n*** No application process!".getBytes());
5009                }
5010                fos.close();
5011                FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5012            } catch (IOException e) {
5013                Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
5014                return;
5015            }
5016
5017            if (app != null) {
5018                ArrayList<Integer> firstPids = new ArrayList<Integer>();
5019                firstPids.add(app.pid);
5020                dumpStackTraces(tracesPath, firstPids, null, null, null);
5021            }
5022
5023            File lastTracesFile = null;
5024            File curTracesFile = null;
5025            for (int i=9; i>=0; i--) {
5026                String name = String.format(Locale.US, "slow%02d.txt", i);
5027                curTracesFile = new File(tracesDir, name);
5028                if (curTracesFile.exists()) {
5029                    if (lastTracesFile != null) {
5030                        curTracesFile.renameTo(lastTracesFile);
5031                    } else {
5032                        curTracesFile.delete();
5033                    }
5034                }
5035                lastTracesFile = curTracesFile;
5036            }
5037            tracesFile.renameTo(curTracesFile);
5038            if (tracesTmp.exists()) {
5039                tracesTmp.renameTo(tracesFile);
5040            }
5041        } finally {
5042            StrictMode.setThreadPolicy(oldPolicy);
5043        }
5044    }
5045
5046    final void appNotResponding(ProcessRecord app, ActivityRecord activity,
5047            ActivityRecord parent, boolean aboveSystem, final String annotation) {
5048        ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
5049        SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
5050
5051        if (mController != null) {
5052            try {
5053                // 0 == continue, -1 = kill process immediately
5054                int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
5055                if (res < 0 && app.pid != MY_PID) {
5056                    app.kill("anr", true);
5057                }
5058            } catch (RemoteException e) {
5059                mController = null;
5060                Watchdog.getInstance().setActivityController(null);
5061            }
5062        }
5063
5064        long anrTime = SystemClock.uptimeMillis();
5065        if (MONITOR_CPU_USAGE) {
5066            updateCpuStatsNow();
5067        }
5068
5069        synchronized (this) {
5070            // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
5071            if (mShuttingDown) {
5072                Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
5073                return;
5074            } else if (app.notResponding) {
5075                Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
5076                return;
5077            } else if (app.crashing) {
5078                Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
5079                return;
5080            }
5081
5082            // In case we come through here for the same app before completing
5083            // this one, mark as anring now so we will bail out.
5084            app.notResponding = true;
5085
5086            // Log the ANR to the event log.
5087            EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
5088                    app.processName, app.info.flags, annotation);
5089
5090            // Dump thread traces as quickly as we can, starting with "interesting" processes.
5091            firstPids.add(app.pid);
5092
5093            int parentPid = app.pid;
5094            if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
5095            if (parentPid != app.pid) firstPids.add(parentPid);
5096
5097            if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
5098
5099            for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
5100                ProcessRecord r = mLruProcesses.get(i);
5101                if (r != null && r.thread != null) {
5102                    int pid = r.pid;
5103                    if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
5104                        if (r.persistent) {
5105                            firstPids.add(pid);
5106                        } else {
5107                            lastPids.put(pid, Boolean.TRUE);
5108                        }
5109                    }
5110                }
5111            }
5112        }
5113
5114        // Log the ANR to the main log.
5115        StringBuilder info = new StringBuilder();
5116        info.setLength(0);
5117        info.append("ANR in ").append(app.processName);
5118        if (activity != null && activity.shortComponentName != null) {
5119            info.append(" (").append(activity.shortComponentName).append(")");
5120        }
5121        info.append("\n");
5122        info.append("PID: ").append(app.pid).append("\n");
5123        if (annotation != null) {
5124            info.append("Reason: ").append(annotation).append("\n");
5125        }
5126        if (parent != null && parent != activity) {
5127            info.append("Parent: ").append(parent.shortComponentName).append("\n");
5128        }
5129
5130        final ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
5131
5132        File tracesFile = dumpStackTraces(true, firstPids, processCpuTracker, lastPids,
5133                NATIVE_STACKS_OF_INTEREST);
5134
5135        String cpuInfo = null;
5136        if (MONITOR_CPU_USAGE) {
5137            updateCpuStatsNow();
5138            synchronized (mProcessCpuTracker) {
5139                cpuInfo = mProcessCpuTracker.printCurrentState(anrTime);
5140            }
5141            info.append(processCpuTracker.printCurrentLoad());
5142            info.append(cpuInfo);
5143        }
5144
5145        info.append(processCpuTracker.printCurrentState(anrTime));
5146
5147        Slog.e(TAG, info.toString());
5148        if (tracesFile == null) {
5149            // There is no trace file, so dump (only) the alleged culprit's threads to the log
5150            Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
5151        }
5152
5153        addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
5154                cpuInfo, tracesFile, null);
5155
5156        if (mController != null) {
5157            try {
5158                // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
5159                int res = mController.appNotResponding(app.processName, app.pid, info.toString());
5160                if (res != 0) {
5161                    if (res < 0 && app.pid != MY_PID) {
5162                        app.kill("anr", true);
5163                    } else {
5164                        synchronized (this) {
5165                            mServices.scheduleServiceTimeoutLocked(app);
5166                        }
5167                    }
5168                    return;
5169                }
5170            } catch (RemoteException e) {
5171                mController = null;
5172                Watchdog.getInstance().setActivityController(null);
5173            }
5174        }
5175
5176        // Unless configured otherwise, swallow ANRs in background processes & kill the process.
5177        boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
5178                Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
5179
5180        synchronized (this) {
5181            if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
5182                app.kill("bg anr", true);
5183                return;
5184            }
5185
5186            // Set the app's notResponding state, and look up the errorReportReceiver
5187            makeAppNotRespondingLocked(app,
5188                    activity != null ? activity.shortComponentName : null,
5189                    annotation != null ? "ANR " + annotation : "ANR",
5190                    info.toString());
5191
5192            // Bring up the infamous App Not Responding dialog
5193            Message msg = Message.obtain();
5194            HashMap<String, Object> map = new HashMap<String, Object>();
5195            msg.what = SHOW_NOT_RESPONDING_MSG;
5196            msg.obj = map;
5197            msg.arg1 = aboveSystem ? 1 : 0;
5198            map.put("app", app);
5199            if (activity != null) {
5200                map.put("activity", activity);
5201            }
5202
5203            mHandler.sendMessage(msg);
5204        }
5205    }
5206
5207    final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
5208        if (!mLaunchWarningShown) {
5209            mLaunchWarningShown = true;
5210            mHandler.post(new Runnable() {
5211                @Override
5212                public void run() {
5213                    synchronized (ActivityManagerService.this) {
5214                        final Dialog d = new LaunchWarningWindow(mContext, cur, next);
5215                        d.show();
5216                        mHandler.postDelayed(new Runnable() {
5217                            @Override
5218                            public void run() {
5219                                synchronized (ActivityManagerService.this) {
5220                                    d.dismiss();
5221                                    mLaunchWarningShown = false;
5222                                }
5223                            }
5224                        }, 4000);
5225                    }
5226                }
5227            });
5228        }
5229    }
5230
5231    @Override
5232    public boolean clearApplicationUserData(final String packageName,
5233            final IPackageDataObserver observer, int userId) {
5234        enforceNotIsolatedCaller("clearApplicationUserData");
5235        int uid = Binder.getCallingUid();
5236        int pid = Binder.getCallingPid();
5237        userId = handleIncomingUser(pid, uid,
5238                userId, false, ALLOW_FULL_ONLY, "clearApplicationUserData", null);
5239        long callingId = Binder.clearCallingIdentity();
5240        try {
5241            IPackageManager pm = AppGlobals.getPackageManager();
5242            int pkgUid = -1;
5243            synchronized(this) {
5244                try {
5245                    pkgUid = pm.getPackageUid(packageName, userId);
5246                } catch (RemoteException e) {
5247                }
5248                if (pkgUid == -1) {
5249                    Slog.w(TAG, "Invalid packageName: " + packageName);
5250                    if (observer != null) {
5251                        try {
5252                            observer.onRemoveCompleted(packageName, false);
5253                        } catch (RemoteException e) {
5254                            Slog.i(TAG, "Observer no longer exists.");
5255                        }
5256                    }
5257                    return false;
5258                }
5259                if (uid == pkgUid || checkComponentPermission(
5260                        android.Manifest.permission.CLEAR_APP_USER_DATA,
5261                        pid, uid, -1, true)
5262                        == PackageManager.PERMISSION_GRANTED) {
5263                    forceStopPackageLocked(packageName, pkgUid, "clear data");
5264                } else {
5265                    throw new SecurityException("PID " + pid + " does not have permission "
5266                            + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
5267                                    + " of package " + packageName);
5268                }
5269
5270                // Remove all tasks match the cleared application package and user
5271                for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
5272                    final TaskRecord tr = mRecentTasks.get(i);
5273                    final String taskPackageName =
5274                            tr.getBaseIntent().getComponent().getPackageName();
5275                    if (tr.userId != userId) continue;
5276                    if (!taskPackageName.equals(packageName)) continue;
5277                    removeTaskByIdLocked(tr.taskId, 0);
5278                }
5279            }
5280
5281            try {
5282                // Clear application user data
5283                pm.clearApplicationUserData(packageName, observer, userId);
5284
5285                synchronized(this) {
5286                    // Remove all permissions granted from/to this package
5287                    removeUriPermissionsForPackageLocked(packageName, userId, true);
5288                }
5289
5290                Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
5291                        Uri.fromParts("package", packageName, null));
5292                intent.putExtra(Intent.EXTRA_UID, pkgUid);
5293                broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
5294                        null, null, 0, null, null, null, false, false, userId);
5295            } catch (RemoteException e) {
5296            }
5297        } finally {
5298            Binder.restoreCallingIdentity(callingId);
5299        }
5300        return true;
5301    }
5302
5303    @Override
5304    public void killBackgroundProcesses(final String packageName, int userId) {
5305        if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
5306                != PackageManager.PERMISSION_GRANTED &&
5307                checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
5308                        != PackageManager.PERMISSION_GRANTED) {
5309            String msg = "Permission Denial: killBackgroundProcesses() from pid="
5310                    + Binder.getCallingPid()
5311                    + ", uid=" + Binder.getCallingUid()
5312                    + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
5313            Slog.w(TAG, msg);
5314            throw new SecurityException(msg);
5315        }
5316
5317        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
5318                userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
5319        long callingId = Binder.clearCallingIdentity();
5320        try {
5321            IPackageManager pm = AppGlobals.getPackageManager();
5322            synchronized(this) {
5323                int appId = -1;
5324                try {
5325                    appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
5326                } catch (RemoteException e) {
5327                }
5328                if (appId == -1) {
5329                    Slog.w(TAG, "Invalid packageName: " + packageName);
5330                    return;
5331                }
5332                killPackageProcessesLocked(packageName, appId, userId,
5333                        ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
5334            }
5335        } finally {
5336            Binder.restoreCallingIdentity(callingId);
5337        }
5338    }
5339
5340    @Override
5341    public void killAllBackgroundProcesses() {
5342        if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
5343                != PackageManager.PERMISSION_GRANTED) {
5344            String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
5345                    + Binder.getCallingPid()
5346                    + ", uid=" + Binder.getCallingUid()
5347                    + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
5348            Slog.w(TAG, msg);
5349            throw new SecurityException(msg);
5350        }
5351
5352        long callingId = Binder.clearCallingIdentity();
5353        try {
5354            synchronized(this) {
5355                ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5356                final int NP = mProcessNames.getMap().size();
5357                for (int ip=0; ip<NP; ip++) {
5358                    SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
5359                    final int NA = apps.size();
5360                    for (int ia=0; ia<NA; ia++) {
5361                        ProcessRecord app = apps.valueAt(ia);
5362                        if (app.persistent) {
5363                            // we don't kill persistent processes
5364                            continue;
5365                        }
5366                        if (app.removed) {
5367                            procs.add(app);
5368                        } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
5369                            app.removed = true;
5370                            procs.add(app);
5371                        }
5372                    }
5373                }
5374
5375                int N = procs.size();
5376                for (int i=0; i<N; i++) {
5377                    removeProcessLocked(procs.get(i), false, true, "kill all background");
5378                }
5379                mAllowLowerMemLevel = true;
5380                updateOomAdjLocked();
5381                doLowMemReportIfNeededLocked(null);
5382            }
5383        } finally {
5384            Binder.restoreCallingIdentity(callingId);
5385        }
5386    }
5387
5388    @Override
5389    public void forceStopPackage(final String packageName, int userId) {
5390        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
5391                != PackageManager.PERMISSION_GRANTED) {
5392            String msg = "Permission Denial: forceStopPackage() from pid="
5393                    + Binder.getCallingPid()
5394                    + ", uid=" + Binder.getCallingUid()
5395                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
5396            Slog.w(TAG, msg);
5397            throw new SecurityException(msg);
5398        }
5399        final int callingPid = Binder.getCallingPid();
5400        userId = handleIncomingUser(callingPid, Binder.getCallingUid(),
5401                userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
5402        long callingId = Binder.clearCallingIdentity();
5403        try {
5404            IPackageManager pm = AppGlobals.getPackageManager();
5405            synchronized(this) {
5406                int[] users = userId == UserHandle.USER_ALL
5407                        ? getUsersLocked() : new int[] { userId };
5408                for (int user : users) {
5409                    int pkgUid = -1;
5410                    try {
5411                        pkgUid = pm.getPackageUid(packageName, user);
5412                    } catch (RemoteException e) {
5413                    }
5414                    if (pkgUid == -1) {
5415                        Slog.w(TAG, "Invalid packageName: " + packageName);
5416                        continue;
5417                    }
5418                    try {
5419                        pm.setPackageStoppedState(packageName, true, user);
5420                    } catch (RemoteException e) {
5421                    } catch (IllegalArgumentException e) {
5422                        Slog.w(TAG, "Failed trying to unstop package "
5423                                + packageName + ": " + e);
5424                    }
5425                    if (isUserRunningLocked(user, false)) {
5426                        forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
5427                    }
5428                }
5429            }
5430        } finally {
5431            Binder.restoreCallingIdentity(callingId);
5432        }
5433    }
5434
5435    @Override
5436    public void addPackageDependency(String packageName) {
5437        synchronized (this) {
5438            int callingPid = Binder.getCallingPid();
5439            if (callingPid == Process.myPid()) {
5440                //  Yeah, um, no.
5441                Slog.w(TAG, "Can't addPackageDependency on system process");
5442                return;
5443            }
5444            ProcessRecord proc;
5445            synchronized (mPidsSelfLocked) {
5446                proc = mPidsSelfLocked.get(Binder.getCallingPid());
5447            }
5448            if (proc != null) {
5449                if (proc.pkgDeps == null) {
5450                    proc.pkgDeps = new ArraySet<String>(1);
5451                }
5452                proc.pkgDeps.add(packageName);
5453            }
5454        }
5455    }
5456
5457    /*
5458     * The pkg name and app id have to be specified.
5459     */
5460    @Override
5461    public void killApplicationWithAppId(String pkg, int appid, String reason) {
5462        if (pkg == null) {
5463            return;
5464        }
5465        // Make sure the uid is valid.
5466        if (appid < 0) {
5467            Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
5468            return;
5469        }
5470        int callerUid = Binder.getCallingUid();
5471        // Only the system server can kill an application
5472        if (callerUid == Process.SYSTEM_UID) {
5473            // Post an aysnc message to kill the application
5474            Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
5475            msg.arg1 = appid;
5476            msg.arg2 = 0;
5477            Bundle bundle = new Bundle();
5478            bundle.putString("pkg", pkg);
5479            bundle.putString("reason", reason);
5480            msg.obj = bundle;
5481            mHandler.sendMessage(msg);
5482        } else {
5483            throw new SecurityException(callerUid + " cannot kill pkg: " +
5484                    pkg);
5485        }
5486    }
5487
5488    @Override
5489    public void closeSystemDialogs(String reason) {
5490        enforceNotIsolatedCaller("closeSystemDialogs");
5491
5492        final int pid = Binder.getCallingPid();
5493        final int uid = Binder.getCallingUid();
5494        final long origId = Binder.clearCallingIdentity();
5495        try {
5496            synchronized (this) {
5497                // Only allow this from foreground processes, so that background
5498                // applications can't abuse it to prevent system UI from being shown.
5499                if (uid >= Process.FIRST_APPLICATION_UID) {
5500                    ProcessRecord proc;
5501                    synchronized (mPidsSelfLocked) {
5502                        proc = mPidsSelfLocked.get(pid);
5503                    }
5504                    if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
5505                        Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
5506                                + " from background process " + proc);
5507                        return;
5508                    }
5509                }
5510                closeSystemDialogsLocked(reason);
5511            }
5512        } finally {
5513            Binder.restoreCallingIdentity(origId);
5514        }
5515    }
5516
5517    void closeSystemDialogsLocked(String reason) {
5518        Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
5519        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
5520                | Intent.FLAG_RECEIVER_FOREGROUND);
5521        if (reason != null) {
5522            intent.putExtra("reason", reason);
5523        }
5524        mWindowManager.closeSystemDialogs(reason);
5525
5526        mStackSupervisor.closeSystemDialogsLocked();
5527
5528        broadcastIntentLocked(null, null, intent, null,
5529                null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1,
5530                Process.SYSTEM_UID, UserHandle.USER_ALL);
5531    }
5532
5533    @Override
5534    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
5535        enforceNotIsolatedCaller("getProcessMemoryInfo");
5536        Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
5537        for (int i=pids.length-1; i>=0; i--) {
5538            ProcessRecord proc;
5539            int oomAdj;
5540            synchronized (this) {
5541                synchronized (mPidsSelfLocked) {
5542                    proc = mPidsSelfLocked.get(pids[i]);
5543                    oomAdj = proc != null ? proc.setAdj : 0;
5544                }
5545            }
5546            infos[i] = new Debug.MemoryInfo();
5547            Debug.getMemoryInfo(pids[i], infos[i]);
5548            if (proc != null) {
5549                synchronized (this) {
5550                    if (proc.thread != null && proc.setAdj == oomAdj) {
5551                        // Record this for posterity if the process has been stable.
5552                        proc.baseProcessTracker.addPss(infos[i].getTotalPss(),
5553                                infos[i].getTotalUss(), false, proc.pkgList);
5554                    }
5555                }
5556            }
5557        }
5558        return infos;
5559    }
5560
5561    @Override
5562    public long[] getProcessPss(int[] pids) {
5563        enforceNotIsolatedCaller("getProcessPss");
5564        long[] pss = new long[pids.length];
5565        for (int i=pids.length-1; i>=0; i--) {
5566            ProcessRecord proc;
5567            int oomAdj;
5568            synchronized (this) {
5569                synchronized (mPidsSelfLocked) {
5570                    proc = mPidsSelfLocked.get(pids[i]);
5571                    oomAdj = proc != null ? proc.setAdj : 0;
5572                }
5573            }
5574            long[] tmpUss = new long[1];
5575            pss[i] = Debug.getPss(pids[i], tmpUss);
5576            if (proc != null) {
5577                synchronized (this) {
5578                    if (proc.thread != null && proc.setAdj == oomAdj) {
5579                        // Record this for posterity if the process has been stable.
5580                        proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList);
5581                    }
5582                }
5583            }
5584        }
5585        return pss;
5586    }
5587
5588    @Override
5589    public void killApplicationProcess(String processName, int uid) {
5590        if (processName == null) {
5591            return;
5592        }
5593
5594        int callerUid = Binder.getCallingUid();
5595        // Only the system server can kill an application
5596        if (callerUid == Process.SYSTEM_UID) {
5597            synchronized (this) {
5598                ProcessRecord app = getProcessRecordLocked(processName, uid, true);
5599                if (app != null && app.thread != null) {
5600                    try {
5601                        app.thread.scheduleSuicide();
5602                    } catch (RemoteException e) {
5603                        // If the other end already died, then our work here is done.
5604                    }
5605                } else {
5606                    Slog.w(TAG, "Process/uid not found attempting kill of "
5607                            + processName + " / " + uid);
5608                }
5609            }
5610        } else {
5611            throw new SecurityException(callerUid + " cannot kill app process: " +
5612                    processName);
5613        }
5614    }
5615
5616    private void forceStopPackageLocked(final String packageName, int uid, String reason) {
5617        forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
5618                false, true, false, false, UserHandle.getUserId(uid), reason);
5619        Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
5620                Uri.fromParts("package", packageName, null));
5621        if (!mProcessesReady) {
5622            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
5623                    | Intent.FLAG_RECEIVER_FOREGROUND);
5624        }
5625        intent.putExtra(Intent.EXTRA_UID, uid);
5626        intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
5627        broadcastIntentLocked(null, null, intent,
5628                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
5629                false, false,
5630                MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
5631    }
5632
5633    private void forceStopUserLocked(int userId, String reason) {
5634        forceStopPackageLocked(null, -1, false, false, true, false, false, userId, reason);
5635        Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
5636        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
5637                | Intent.FLAG_RECEIVER_FOREGROUND);
5638        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
5639        broadcastIntentLocked(null, null, intent,
5640                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
5641                false, false,
5642                MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
5643    }
5644
5645    private final boolean killPackageProcessesLocked(String packageName, int appId,
5646            int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
5647            boolean doit, boolean evenPersistent, String reason) {
5648        ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5649
5650        // Remove all processes this package may have touched: all with the
5651        // same UID (except for the system or root user), and all whose name
5652        // matches the package name.
5653        final int NP = mProcessNames.getMap().size();
5654        for (int ip=0; ip<NP; ip++) {
5655            SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
5656            final int NA = apps.size();
5657            for (int ia=0; ia<NA; ia++) {
5658                ProcessRecord app = apps.valueAt(ia);
5659                if (app.persistent && !evenPersistent) {
5660                    // we don't kill persistent processes
5661                    continue;
5662                }
5663                if (app.removed) {
5664                    if (doit) {
5665                        procs.add(app);
5666                    }
5667                    continue;
5668                }
5669
5670                // Skip process if it doesn't meet our oom adj requirement.
5671                if (app.setAdj < minOomAdj) {
5672                    continue;
5673                }
5674
5675                // If no package is specified, we call all processes under the
5676                // give user id.
5677                if (packageName == null) {
5678                    if (app.userId != userId) {
5679                        continue;
5680                    }
5681                    if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) {
5682                        continue;
5683                    }
5684                // Package has been specified, we want to hit all processes
5685                // that match it.  We need to qualify this by the processes
5686                // that are running under the specified app and user ID.
5687                } else {
5688                    final boolean isDep = app.pkgDeps != null
5689                            && app.pkgDeps.contains(packageName);
5690                    if (!isDep && UserHandle.getAppId(app.uid) != appId) {
5691                        continue;
5692                    }
5693                    if (userId != UserHandle.USER_ALL && app.userId != userId) {
5694                        continue;
5695                    }
5696                    if (!app.pkgList.containsKey(packageName) && !isDep) {
5697                        continue;
5698                    }
5699                }
5700
5701                // Process has passed all conditions, kill it!
5702                if (!doit) {
5703                    return true;
5704                }
5705                app.removed = true;
5706                procs.add(app);
5707            }
5708        }
5709
5710        int N = procs.size();
5711        for (int i=0; i<N; i++) {
5712            removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
5713        }
5714        updateOomAdjLocked();
5715        return N > 0;
5716    }
5717
5718    private final boolean forceStopPackageLocked(String name, int appId,
5719            boolean callerWillRestart, boolean purgeCache, boolean doit,
5720            boolean evenPersistent, boolean uninstalling, int userId, String reason) {
5721        int i;
5722        int N;
5723
5724        if (userId == UserHandle.USER_ALL && name == null) {
5725            Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
5726        }
5727
5728        if (appId < 0 && name != null) {
5729            try {
5730                appId = UserHandle.getAppId(
5731                        AppGlobals.getPackageManager().getPackageUid(name, 0));
5732            } catch (RemoteException e) {
5733            }
5734        }
5735
5736        if (doit) {
5737            if (name != null) {
5738                Slog.i(TAG, "Force stopping " + name + " appid=" + appId
5739                        + " user=" + userId + ": " + reason);
5740            } else {
5741                Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
5742            }
5743
5744            final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
5745            for (int ip=pmap.size()-1; ip>=0; ip--) {
5746                SparseArray<Long> ba = pmap.valueAt(ip);
5747                for (i=ba.size()-1; i>=0; i--) {
5748                    boolean remove = false;
5749                    final int entUid = ba.keyAt(i);
5750                    if (name != null) {
5751                        if (userId == UserHandle.USER_ALL) {
5752                            if (UserHandle.getAppId(entUid) == appId) {
5753                                remove = true;
5754                            }
5755                        } else {
5756                            if (entUid == UserHandle.getUid(userId, appId)) {
5757                                remove = true;
5758                            }
5759                        }
5760                    } else if (UserHandle.getUserId(entUid) == userId) {
5761                        remove = true;
5762                    }
5763                    if (remove) {
5764                        ba.removeAt(i);
5765                    }
5766                }
5767                if (ba.size() == 0) {
5768                    pmap.removeAt(ip);
5769                }
5770            }
5771        }
5772
5773        boolean didSomething = killPackageProcessesLocked(name, appId, userId,
5774                -100, callerWillRestart, true, doit, evenPersistent,
5775                name == null ? ("stop user " + userId) : ("stop " + name));
5776
5777        if (mStackSupervisor.forceStopPackageLocked(name, doit, evenPersistent, userId)) {
5778            if (!doit) {
5779                return true;
5780            }
5781            didSomething = true;
5782        }
5783
5784        if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
5785            if (!doit) {
5786                return true;
5787            }
5788            didSomething = true;
5789        }
5790
5791        if (name == null) {
5792            // Remove all sticky broadcasts from this user.
5793            mStickyBroadcasts.remove(userId);
5794        }
5795
5796        ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
5797        if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
5798                userId, providers)) {
5799            if (!doit) {
5800                return true;
5801            }
5802            didSomething = true;
5803        }
5804        N = providers.size();
5805        for (i=0; i<N; i++) {
5806            removeDyingProviderLocked(null, providers.get(i), true);
5807        }
5808
5809        // Remove transient permissions granted from/to this package/user
5810        removeUriPermissionsForPackageLocked(name, userId, false);
5811
5812        if (name == null || uninstalling) {
5813            // Remove pending intents.  For now we only do this when force
5814            // stopping users, because we have some problems when doing this
5815            // for packages -- app widgets are not currently cleaned up for
5816            // such packages, so they can be left with bad pending intents.
5817            if (mIntentSenderRecords.size() > 0) {
5818                Iterator<WeakReference<PendingIntentRecord>> it
5819                        = mIntentSenderRecords.values().iterator();
5820                while (it.hasNext()) {
5821                    WeakReference<PendingIntentRecord> wpir = it.next();
5822                    if (wpir == null) {
5823                        it.remove();
5824                        continue;
5825                    }
5826                    PendingIntentRecord pir = wpir.get();
5827                    if (pir == null) {
5828                        it.remove();
5829                        continue;
5830                    }
5831                    if (name == null) {
5832                        // Stopping user, remove all objects for the user.
5833                        if (pir.key.userId != userId) {
5834                            // Not the same user, skip it.
5835                            continue;
5836                        }
5837                    } else {
5838                        if (UserHandle.getAppId(pir.uid) != appId) {
5839                            // Different app id, skip it.
5840                            continue;
5841                        }
5842                        if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
5843                            // Different user, skip it.
5844                            continue;
5845                        }
5846                        if (!pir.key.packageName.equals(name)) {
5847                            // Different package, skip it.
5848                            continue;
5849                        }
5850                    }
5851                    if (!doit) {
5852                        return true;
5853                    }
5854                    didSomething = true;
5855                    it.remove();
5856                    pir.canceled = true;
5857                    if (pir.key.activity != null) {
5858                        pir.key.activity.pendingResults.remove(pir.ref);
5859                    }
5860                }
5861            }
5862        }
5863
5864        if (doit) {
5865            if (purgeCache && name != null) {
5866                AttributeCache ac = AttributeCache.instance();
5867                if (ac != null) {
5868                    ac.removePackage(name);
5869                }
5870            }
5871            if (mBooted) {
5872                mStackSupervisor.resumeTopActivitiesLocked();
5873                mStackSupervisor.scheduleIdleLocked();
5874            }
5875        }
5876
5877        return didSomething;
5878    }
5879
5880    private final boolean removeProcessLocked(ProcessRecord app,
5881            boolean callerWillRestart, boolean allowRestart, String reason) {
5882        final String name = app.processName;
5883        final int uid = app.uid;
5884        if (DEBUG_PROCESSES) Slog.d(
5885            TAG, "Force removing proc " + app.toShortString() + " (" + name
5886            + "/" + uid + ")");
5887
5888        mProcessNames.remove(name, uid);
5889        mIsolatedProcesses.remove(app.uid);
5890        if (mHeavyWeightProcess == app) {
5891            mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
5892                    mHeavyWeightProcess.userId, 0));
5893            mHeavyWeightProcess = null;
5894        }
5895        boolean needRestart = false;
5896        if (app.pid > 0 && app.pid != MY_PID) {
5897            int pid = app.pid;
5898            synchronized (mPidsSelfLocked) {
5899                mPidsSelfLocked.remove(pid);
5900                mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5901            }
5902            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
5903            if (app.isolated) {
5904                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
5905            }
5906            app.kill(reason, true);
5907            handleAppDiedLocked(app, true, allowRestart);
5908            removeLruProcessLocked(app);
5909
5910            if (app.persistent && !app.isolated) {
5911                if (!callerWillRestart) {
5912                    addAppLocked(app.info, false, null /* ABI override */);
5913                } else {
5914                    needRestart = true;
5915                }
5916            }
5917        } else {
5918            mRemovedProcesses.add(app);
5919        }
5920
5921        return needRestart;
5922    }
5923
5924    private final void processStartTimedOutLocked(ProcessRecord app) {
5925        final int pid = app.pid;
5926        boolean gone = false;
5927        synchronized (mPidsSelfLocked) {
5928            ProcessRecord knownApp = mPidsSelfLocked.get(pid);
5929            if (knownApp != null && knownApp.thread == null) {
5930                mPidsSelfLocked.remove(pid);
5931                gone = true;
5932            }
5933        }
5934
5935        if (gone) {
5936            Slog.w(TAG, "Process " + app + " failed to attach");
5937            EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
5938                    pid, app.uid, app.processName);
5939            mProcessNames.remove(app.processName, app.uid);
5940            mIsolatedProcesses.remove(app.uid);
5941            if (mHeavyWeightProcess == app) {
5942                mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
5943                        mHeavyWeightProcess.userId, 0));
5944                mHeavyWeightProcess = null;
5945            }
5946            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
5947            if (app.isolated) {
5948                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
5949            }
5950            // Take care of any launching providers waiting for this process.
5951            checkAppInLaunchingProvidersLocked(app, true);
5952            // Take care of any services that are waiting for the process.
5953            mServices.processStartTimedOutLocked(app);
5954            app.kill("start timeout", true);
5955            if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
5956                Slog.w(TAG, "Unattached app died before backup, skipping");
5957                try {
5958                    IBackupManager bm = IBackupManager.Stub.asInterface(
5959                            ServiceManager.getService(Context.BACKUP_SERVICE));
5960                    bm.agentDisconnected(app.info.packageName);
5961                } catch (RemoteException e) {
5962                    // Can't happen; the backup manager is local
5963                }
5964            }
5965            if (isPendingBroadcastProcessLocked(pid)) {
5966                Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
5967                skipPendingBroadcastLocked(pid);
5968            }
5969        } else {
5970            Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
5971        }
5972    }
5973
5974    private final boolean attachApplicationLocked(IApplicationThread thread,
5975            int pid) {
5976
5977        // Find the application record that is being attached...  either via
5978        // the pid if we are running in multiple processes, or just pull the
5979        // next app record if we are emulating process with anonymous threads.
5980        ProcessRecord app;
5981        if (pid != MY_PID && pid >= 0) {
5982            synchronized (mPidsSelfLocked) {
5983                app = mPidsSelfLocked.get(pid);
5984            }
5985        } else {
5986            app = null;
5987        }
5988
5989        if (app == null) {
5990            Slog.w(TAG, "No pending application record for pid " + pid
5991                    + " (IApplicationThread " + thread + "); dropping process");
5992            EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
5993            if (pid > 0 && pid != MY_PID) {
5994                Process.killProcessQuiet(pid);
5995                //TODO: Process.killProcessGroup(app.info.uid, pid);
5996            } else {
5997                try {
5998                    thread.scheduleExit();
5999                } catch (Exception e) {
6000                    // Ignore exceptions.
6001                }
6002            }
6003            return false;
6004        }
6005
6006        // If this application record is still attached to a previous
6007        // process, clean it up now.
6008        if (app.thread != null) {
6009            handleAppDiedLocked(app, true, true);
6010        }
6011
6012        // Tell the process all about itself.
6013
6014        if (localLOGV) Slog.v(
6015                TAG, "Binding process pid " + pid + " to record " + app);
6016
6017        final String processName = app.processName;
6018        try {
6019            AppDeathRecipient adr = new AppDeathRecipient(
6020                    app, pid, thread);
6021            thread.asBinder().linkToDeath(adr, 0);
6022            app.deathRecipient = adr;
6023        } catch (RemoteException e) {
6024            app.resetPackageList(mProcessStats);
6025            startProcessLocked(app, "link fail", processName);
6026            return false;
6027        }
6028
6029        EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
6030
6031        app.makeActive(thread, mProcessStats);
6032        app.curAdj = app.setAdj = -100;
6033        app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT;
6034        app.forcingToForeground = null;
6035        updateProcessForegroundLocked(app, false, false);
6036        app.hasShownUi = false;
6037        app.debugging = false;
6038        app.cached = false;
6039
6040        mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
6041
6042        boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
6043        List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
6044
6045        if (!normalMode) {
6046            Slog.i(TAG, "Launching preboot mode app: " + app);
6047        }
6048
6049        if (localLOGV) Slog.v(
6050            TAG, "New app record " + app
6051            + " thread=" + thread.asBinder() + " pid=" + pid);
6052        try {
6053            int testMode = IApplicationThread.DEBUG_OFF;
6054            if (mDebugApp != null && mDebugApp.equals(processName)) {
6055                testMode = mWaitForDebugger
6056                    ? IApplicationThread.DEBUG_WAIT
6057                    : IApplicationThread.DEBUG_ON;
6058                app.debugging = true;
6059                if (mDebugTransient) {
6060                    mDebugApp = mOrigDebugApp;
6061                    mWaitForDebugger = mOrigWaitForDebugger;
6062                }
6063            }
6064            String profileFile = app.instrumentationProfileFile;
6065            ParcelFileDescriptor profileFd = null;
6066            int samplingInterval = 0;
6067            boolean profileAutoStop = false;
6068            if (mProfileApp != null && mProfileApp.equals(processName)) {
6069                mProfileProc = app;
6070                profileFile = mProfileFile;
6071                profileFd = mProfileFd;
6072                samplingInterval = mSamplingInterval;
6073                profileAutoStop = mAutoStopProfiler;
6074            }
6075            boolean enableOpenGlTrace = false;
6076            if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
6077                enableOpenGlTrace = true;
6078                mOpenGlTraceApp = null;
6079            }
6080
6081            // If the app is being launched for restore or full backup, set it up specially
6082            boolean isRestrictedBackupMode = false;
6083            if (mBackupTarget != null && mBackupAppName.equals(processName)) {
6084                isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
6085                        || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
6086                        || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
6087            }
6088
6089            ensurePackageDexOpt(app.instrumentationInfo != null
6090                    ? app.instrumentationInfo.packageName
6091                    : app.info.packageName);
6092            if (app.instrumentationClass != null) {
6093                ensurePackageDexOpt(app.instrumentationClass.getPackageName());
6094            }
6095            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
6096                    + processName + " with config " + mConfiguration);
6097            ApplicationInfo appInfo = app.instrumentationInfo != null
6098                    ? app.instrumentationInfo : app.info;
6099            app.compat = compatibilityInfoForPackageLocked(appInfo);
6100            if (profileFd != null) {
6101                profileFd = profileFd.dup();
6102            }
6103            ProfilerInfo profilerInfo = profileFile == null ? null
6104                    : new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop);
6105            thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
6106                    profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
6107                    app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
6108                    isRestrictedBackupMode || !normalMode, app.persistent,
6109                    new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
6110                    mCoreSettingsObserver.getCoreSettingsLocked());
6111            updateLruProcessLocked(app, false, null);
6112            app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
6113        } catch (Exception e) {
6114            // todo: Yikes!  What should we do?  For now we will try to
6115            // start another process, but that could easily get us in
6116            // an infinite loop of restarting processes...
6117            Slog.w(TAG, "Exception thrown during bind!", e);
6118
6119            app.resetPackageList(mProcessStats);
6120            app.unlinkDeathRecipient();
6121            startProcessLocked(app, "bind fail", processName);
6122            return false;
6123        }
6124
6125        // Remove this record from the list of starting applications.
6126        mPersistentStartingProcesses.remove(app);
6127        if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
6128                "Attach application locked removing on hold: " + app);
6129        mProcessesOnHold.remove(app);
6130
6131        boolean badApp = false;
6132        boolean didSomething = false;
6133
6134        // See if the top visible activity is waiting to run in this process...
6135        if (normalMode) {
6136            try {
6137                if (mStackSupervisor.attachApplicationLocked(app)) {
6138                    didSomething = true;
6139                }
6140            } catch (Exception e) {
6141                badApp = true;
6142            }
6143        }
6144
6145        // Find any services that should be running in this process...
6146        if (!badApp) {
6147            try {
6148                didSomething |= mServices.attachApplicationLocked(app, processName);
6149            } catch (Exception e) {
6150                badApp = true;
6151            }
6152        }
6153
6154        // Check if a next-broadcast receiver is in this process...
6155        if (!badApp && isPendingBroadcastProcessLocked(pid)) {
6156            try {
6157                didSomething |= sendPendingBroadcastsLocked(app);
6158            } catch (Exception e) {
6159                // If the app died trying to launch the receiver we declare it 'bad'
6160                badApp = true;
6161            }
6162        }
6163
6164        // Check whether the next backup agent is in this process...
6165        if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
6166            if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
6167            ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
6168            try {
6169                thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
6170                        compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
6171                        mBackupTarget.backupMode);
6172            } catch (Exception e) {
6173                Slog.w(TAG, "Exception scheduling backup agent creation: ");
6174                e.printStackTrace();
6175            }
6176        }
6177
6178        if (badApp) {
6179            // todo: Also need to kill application to deal with all
6180            // kinds of exceptions.
6181            handleAppDiedLocked(app, false, true);
6182            return false;
6183        }
6184
6185        if (!didSomething) {
6186            updateOomAdjLocked();
6187        }
6188
6189        return true;
6190    }
6191
6192    @Override
6193    public final void attachApplication(IApplicationThread thread) {
6194        synchronized (this) {
6195            int callingPid = Binder.getCallingPid();
6196            final long origId = Binder.clearCallingIdentity();
6197            attachApplicationLocked(thread, callingPid);
6198            Binder.restoreCallingIdentity(origId);
6199        }
6200    }
6201
6202    @Override
6203    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
6204        final long origId = Binder.clearCallingIdentity();
6205        synchronized (this) {
6206            ActivityStack stack = ActivityRecord.getStackLocked(token);
6207            if (stack != null) {
6208                ActivityRecord r =
6209                        mStackSupervisor.activityIdleInternalLocked(token, false, config);
6210                if (stopProfiling) {
6211                    if ((mProfileProc == r.app) && (mProfileFd != null)) {
6212                        try {
6213                            mProfileFd.close();
6214                        } catch (IOException e) {
6215                        }
6216                        clearProfilerLocked();
6217                    }
6218                }
6219            }
6220        }
6221        Binder.restoreCallingIdentity(origId);
6222    }
6223
6224    void postEnableScreenAfterBootLocked() {
6225        mHandler.sendEmptyMessage(ENABLE_SCREEN_AFTER_BOOT_MSG);
6226    }
6227
6228    void enableScreenAfterBoot() {
6229        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6230                SystemClock.uptimeMillis());
6231        mWindowManager.enableScreenAfterBoot();
6232
6233        synchronized (this) {
6234            updateEventDispatchingLocked();
6235        }
6236    }
6237
6238    @Override
6239    public void showBootMessage(final CharSequence msg, final boolean always) {
6240        enforceNotIsolatedCaller("showBootMessage");
6241        mWindowManager.showBootMessage(msg, always);
6242    }
6243
6244    @Override
6245    public void keyguardWaitingForActivityDrawn() {
6246        enforceNotIsolatedCaller("keyguardWaitingForActivityDrawn");
6247        final long token = Binder.clearCallingIdentity();
6248        try {
6249            synchronized (this) {
6250                if (DEBUG_LOCKSCREEN) logLockScreen("");
6251                mWindowManager.keyguardWaitingForActivityDrawn();
6252                mKeyguardWaitingForDraw = true;
6253            }
6254        } finally {
6255            Binder.restoreCallingIdentity(token);
6256        }
6257    }
6258
6259    final void finishBooting() {
6260        synchronized (this) {
6261            if (!mBootAnimationComplete) {
6262                mCallFinishBooting = true;
6263                return;
6264            }
6265            mCallFinishBooting = false;
6266        }
6267
6268        // Register receivers to handle package update events
6269        mPackageMonitor.register(mContext, Looper.getMainLooper(), false);
6270
6271        // Let system services know.
6272        mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
6273
6274        synchronized (this) {
6275            // Ensure that any processes we had put on hold are now started
6276            // up.
6277            final int NP = mProcessesOnHold.size();
6278            if (NP > 0) {
6279                ArrayList<ProcessRecord> procs =
6280                    new ArrayList<ProcessRecord>(mProcessesOnHold);
6281                for (int ip=0; ip<NP; ip++) {
6282                    if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
6283                            + procs.get(ip));
6284                    startProcessLocked(procs.get(ip), "on-hold", null);
6285                }
6286            }
6287
6288            if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6289                // Start looking for apps that are abusing wake locks.
6290                Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6291                mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6292                // Tell anyone interested that we are done booting!
6293                SystemProperties.set("sys.boot_completed", "1");
6294                SystemProperties.set("dev.bootcomplete", "1");
6295                for (int i=0; i<mStartedUsers.size(); i++) {
6296                    UserStartedState uss = mStartedUsers.valueAt(i);
6297                    if (uss.mState == UserStartedState.STATE_BOOTING) {
6298                        uss.mState = UserStartedState.STATE_RUNNING;
6299                        final int userId = mStartedUsers.keyAt(i);
6300                        Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
6301                        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
6302                        intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
6303                        broadcastIntentLocked(null, null, intent, null,
6304                                new IIntentReceiver.Stub() {
6305                                    @Override
6306                                    public void performReceive(Intent intent, int resultCode,
6307                                            String data, Bundle extras, boolean ordered,
6308                                            boolean sticky, int sendingUser) {
6309                                        synchronized (ActivityManagerService.this) {
6310                                            requestPssAllProcsLocked(SystemClock.uptimeMillis(),
6311                                                    true, false);
6312                                        }
6313                                    }
6314                                },
6315                                0, null, null,
6316                                android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
6317                                AppOpsManager.OP_NONE, true, false, MY_PID, Process.SYSTEM_UID,
6318                                userId);
6319                    }
6320                }
6321                scheduleStartProfilesLocked();
6322            }
6323        }
6324    }
6325
6326    @Override
6327    public void bootAnimationComplete() {
6328        final boolean callFinishBooting;
6329        synchronized (this) {
6330            callFinishBooting = mCallFinishBooting;
6331            mBootAnimationComplete = true;
6332        }
6333        if (callFinishBooting) {
6334            finishBooting();
6335        }
6336    }
6337
6338    final void ensureBootCompleted() {
6339        boolean booting;
6340        boolean enableScreen;
6341        synchronized (this) {
6342            booting = mBooting;
6343            mBooting = false;
6344            enableScreen = !mBooted;
6345            mBooted = true;
6346        }
6347
6348        if (booting) {
6349            finishBooting();
6350        }
6351
6352        if (enableScreen) {
6353            enableScreenAfterBoot();
6354        }
6355    }
6356
6357    @Override
6358    public final void activityResumed(IBinder token) {
6359        final long origId = Binder.clearCallingIdentity();
6360        synchronized(this) {
6361            ActivityStack stack = ActivityRecord.getStackLocked(token);
6362            if (stack != null) {
6363                ActivityRecord.activityResumedLocked(token);
6364            }
6365        }
6366        Binder.restoreCallingIdentity(origId);
6367    }
6368
6369    @Override
6370    public final void activityPaused(IBinder token) {
6371        final long origId = Binder.clearCallingIdentity();
6372        synchronized(this) {
6373            ActivityStack stack = ActivityRecord.getStackLocked(token);
6374            if (stack != null) {
6375                stack.activityPausedLocked(token, false);
6376            }
6377        }
6378        Binder.restoreCallingIdentity(origId);
6379    }
6380
6381    @Override
6382    public final void activityStopped(IBinder token, Bundle icicle,
6383            PersistableBundle persistentState, CharSequence description) {
6384        if (localLOGV) Slog.v(TAG, "Activity stopped: token=" + token);
6385
6386        // Refuse possible leaked file descriptors
6387        if (icicle != null && icicle.hasFileDescriptors()) {
6388            throw new IllegalArgumentException("File descriptors passed in Bundle");
6389        }
6390
6391        final long origId = Binder.clearCallingIdentity();
6392
6393        synchronized (this) {
6394            ActivityRecord r = ActivityRecord.isInStackLocked(token);
6395            if (r != null) {
6396                r.task.stack.activityStoppedLocked(r, icicle, persistentState, description);
6397            }
6398        }
6399
6400        trimApplications();
6401
6402        Binder.restoreCallingIdentity(origId);
6403    }
6404
6405    @Override
6406    public final void activityDestroyed(IBinder token) {
6407        if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
6408        synchronized (this) {
6409            ActivityStack stack = ActivityRecord.getStackLocked(token);
6410            if (stack != null) {
6411                stack.activityDestroyedLocked(token);
6412            }
6413        }
6414    }
6415
6416    @Override
6417    public final void backgroundResourcesReleased(IBinder token) {
6418        final long origId = Binder.clearCallingIdentity();
6419        try {
6420            synchronized (this) {
6421                ActivityStack stack = ActivityRecord.getStackLocked(token);
6422                if (stack != null) {
6423                    stack.backgroundResourcesReleased(token);
6424                }
6425            }
6426        } finally {
6427            Binder.restoreCallingIdentity(origId);
6428        }
6429    }
6430
6431    @Override
6432    public final void notifyLaunchTaskBehindComplete(IBinder token) {
6433        mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
6434    }
6435
6436    @Override
6437    public final void notifyEnterAnimationComplete(IBinder token) {
6438        mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token));
6439    }
6440
6441    @Override
6442    public String getCallingPackage(IBinder token) {
6443        synchronized (this) {
6444            ActivityRecord r = getCallingRecordLocked(token);
6445            return r != null ? r.info.packageName : null;
6446        }
6447    }
6448
6449    @Override
6450    public ComponentName getCallingActivity(IBinder token) {
6451        synchronized (this) {
6452            ActivityRecord r = getCallingRecordLocked(token);
6453            return r != null ? r.intent.getComponent() : null;
6454        }
6455    }
6456
6457    private ActivityRecord getCallingRecordLocked(IBinder token) {
6458        ActivityRecord r = ActivityRecord.isInStackLocked(token);
6459        if (r == null) {
6460            return null;
6461        }
6462        return r.resultTo;
6463    }
6464
6465    @Override
6466    public ComponentName getActivityClassForToken(IBinder token) {
6467        synchronized(this) {
6468            ActivityRecord r = ActivityRecord.isInStackLocked(token);
6469            if (r == null) {
6470                return null;
6471            }
6472            return r.intent.getComponent();
6473        }
6474    }
6475
6476    @Override
6477    public String getPackageForToken(IBinder token) {
6478        synchronized(this) {
6479            ActivityRecord r = ActivityRecord.isInStackLocked(token);
6480            if (r == null) {
6481                return null;
6482            }
6483            return r.packageName;
6484        }
6485    }
6486
6487    @Override
6488    public IIntentSender getIntentSender(int type,
6489            String packageName, IBinder token, String resultWho,
6490            int requestCode, Intent[] intents, String[] resolvedTypes,
6491            int flags, Bundle options, int userId) {
6492        enforceNotIsolatedCaller("getIntentSender");
6493        // Refuse possible leaked file descriptors
6494        if (intents != null) {
6495            if (intents.length < 1) {
6496                throw new IllegalArgumentException("Intents array length must be >= 1");
6497            }
6498            for (int i=0; i<intents.length; i++) {
6499                Intent intent = intents[i];
6500                if (intent != null) {
6501                    if (intent.hasFileDescriptors()) {
6502                        throw new IllegalArgumentException("File descriptors passed in Intent");
6503                    }
6504                    if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
6505                            (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
6506                        throw new IllegalArgumentException(
6507                                "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
6508                    }
6509                    intents[i] = new Intent(intent);
6510                }
6511            }
6512            if (resolvedTypes != null && resolvedTypes.length != intents.length) {
6513                throw new IllegalArgumentException(
6514                        "Intent array length does not match resolvedTypes length");
6515            }
6516        }
6517        if (options != null) {
6518            if (options.hasFileDescriptors()) {
6519                throw new IllegalArgumentException("File descriptors passed in options");
6520            }
6521        }
6522
6523        synchronized(this) {
6524            int callingUid = Binder.getCallingUid();
6525            int origUserId = userId;
6526            userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
6527                    type == ActivityManager.INTENT_SENDER_BROADCAST,
6528                    ALLOW_NON_FULL, "getIntentSender", null);
6529            if (origUserId == UserHandle.USER_CURRENT) {
6530                // We don't want to evaluate this until the pending intent is
6531                // actually executed.  However, we do want to always do the
6532                // security checking for it above.
6533                userId = UserHandle.USER_CURRENT;
6534            }
6535            try {
6536                if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
6537                    int uid = AppGlobals.getPackageManager()
6538                            .getPackageUid(packageName, UserHandle.getUserId(callingUid));
6539                    if (!UserHandle.isSameApp(callingUid, uid)) {
6540                        String msg = "Permission Denial: getIntentSender() from pid="
6541                            + Binder.getCallingPid()
6542                            + ", uid=" + Binder.getCallingUid()
6543                            + ", (need uid=" + uid + ")"
6544                            + " is not allowed to send as package " + packageName;
6545                        Slog.w(TAG, msg);
6546                        throw new SecurityException(msg);
6547                    }
6548                }
6549
6550                return getIntentSenderLocked(type, packageName, callingUid, userId,
6551                        token, resultWho, requestCode, intents, resolvedTypes, flags, options);
6552
6553            } catch (RemoteException e) {
6554                throw new SecurityException(e);
6555            }
6556        }
6557    }
6558
6559    IIntentSender getIntentSenderLocked(int type, String packageName,
6560            int callingUid, int userId, IBinder token, String resultWho,
6561            int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6562            Bundle options) {
6563        if (DEBUG_MU)
6564            Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
6565        ActivityRecord activity = null;
6566        if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
6567            activity = ActivityRecord.isInStackLocked(token);
6568            if (activity == null) {
6569                return null;
6570            }
6571            if (activity.finishing) {
6572                return null;
6573            }
6574        }
6575
6576        final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
6577        final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
6578        final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
6579        flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
6580                |PendingIntent.FLAG_UPDATE_CURRENT);
6581
6582        PendingIntentRecord.Key key = new PendingIntentRecord.Key(
6583                type, packageName, activity, resultWho,
6584                requestCode, intents, resolvedTypes, flags, options, userId);
6585        WeakReference<PendingIntentRecord> ref;
6586        ref = mIntentSenderRecords.get(key);
6587        PendingIntentRecord rec = ref != null ? ref.get() : null;
6588        if (rec != null) {
6589            if (!cancelCurrent) {
6590                if (updateCurrent) {
6591                    if (rec.key.requestIntent != null) {
6592                        rec.key.requestIntent.replaceExtras(intents != null ?
6593                                intents[intents.length - 1] : null);
6594                    }
6595                    if (intents != null) {
6596                        intents[intents.length-1] = rec.key.requestIntent;
6597                        rec.key.allIntents = intents;
6598                        rec.key.allResolvedTypes = resolvedTypes;
6599                    } else {
6600                        rec.key.allIntents = null;
6601                        rec.key.allResolvedTypes = null;
6602                    }
6603                }
6604                return rec;
6605            }
6606            rec.canceled = true;
6607            mIntentSenderRecords.remove(key);
6608        }
6609        if (noCreate) {
6610            return rec;
6611        }
6612        rec = new PendingIntentRecord(this, key, callingUid);
6613        mIntentSenderRecords.put(key, rec.ref);
6614        if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
6615            if (activity.pendingResults == null) {
6616                activity.pendingResults
6617                        = new HashSet<WeakReference<PendingIntentRecord>>();
6618            }
6619            activity.pendingResults.add(rec.ref);
6620        }
6621        return rec;
6622    }
6623
6624    @Override
6625    public void cancelIntentSender(IIntentSender sender) {
6626        if (!(sender instanceof PendingIntentRecord)) {
6627            return;
6628        }
6629        synchronized(this) {
6630            PendingIntentRecord rec = (PendingIntentRecord)sender;
6631            try {
6632                int uid = AppGlobals.getPackageManager()
6633                        .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
6634                if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
6635                    String msg = "Permission Denial: cancelIntentSender() from pid="
6636                        + Binder.getCallingPid()
6637                        + ", uid=" + Binder.getCallingUid()
6638                        + " is not allowed to cancel packges "
6639                        + rec.key.packageName;
6640                    Slog.w(TAG, msg);
6641                    throw new SecurityException(msg);
6642                }
6643            } catch (RemoteException e) {
6644                throw new SecurityException(e);
6645            }
6646            cancelIntentSenderLocked(rec, true);
6647        }
6648    }
6649
6650    void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
6651        rec.canceled = true;
6652        mIntentSenderRecords.remove(rec.key);
6653        if (cleanActivity && rec.key.activity != null) {
6654            rec.key.activity.pendingResults.remove(rec.ref);
6655        }
6656    }
6657
6658    @Override
6659    public String getPackageForIntentSender(IIntentSender pendingResult) {
6660        if (!(pendingResult instanceof PendingIntentRecord)) {
6661            return null;
6662        }
6663        try {
6664            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6665            return res.key.packageName;
6666        } catch (ClassCastException e) {
6667        }
6668        return null;
6669    }
6670
6671    @Override
6672    public int getUidForIntentSender(IIntentSender sender) {
6673        if (sender instanceof PendingIntentRecord) {
6674            try {
6675                PendingIntentRecord res = (PendingIntentRecord)sender;
6676                return res.uid;
6677            } catch (ClassCastException e) {
6678            }
6679        }
6680        return -1;
6681    }
6682
6683    @Override
6684    public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
6685        if (!(pendingResult instanceof PendingIntentRecord)) {
6686            return false;
6687        }
6688        try {
6689            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6690            if (res.key.allIntents == null) {
6691                return false;
6692            }
6693            for (int i=0; i<res.key.allIntents.length; i++) {
6694                Intent intent = res.key.allIntents[i];
6695                if (intent.getPackage() != null && intent.getComponent() != null) {
6696                    return false;
6697                }
6698            }
6699            return true;
6700        } catch (ClassCastException e) {
6701        }
6702        return false;
6703    }
6704
6705    @Override
6706    public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
6707        if (!(pendingResult instanceof PendingIntentRecord)) {
6708            return false;
6709        }
6710        try {
6711            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6712            if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
6713                return true;
6714            }
6715            return false;
6716        } catch (ClassCastException e) {
6717        }
6718        return false;
6719    }
6720
6721    @Override
6722    public Intent getIntentForIntentSender(IIntentSender pendingResult) {
6723        if (!(pendingResult instanceof PendingIntentRecord)) {
6724            return null;
6725        }
6726        try {
6727            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6728            return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
6729        } catch (ClassCastException e) {
6730        }
6731        return null;
6732    }
6733
6734    @Override
6735    public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
6736        if (!(pendingResult instanceof PendingIntentRecord)) {
6737            return null;
6738        }
6739        try {
6740            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6741            Intent intent = res.key.requestIntent;
6742            if (intent != null) {
6743                if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
6744                        || res.lastTagPrefix.equals(prefix))) {
6745                    return res.lastTag;
6746                }
6747                res.lastTagPrefix = prefix;
6748                StringBuilder sb = new StringBuilder(128);
6749                if (prefix != null) {
6750                    sb.append(prefix);
6751                }
6752                if (intent.getAction() != null) {
6753                    sb.append(intent.getAction());
6754                } else if (intent.getComponent() != null) {
6755                    intent.getComponent().appendShortString(sb);
6756                } else {
6757                    sb.append("?");
6758                }
6759                return res.lastTag = sb.toString();
6760            }
6761        } catch (ClassCastException e) {
6762        }
6763        return null;
6764    }
6765
6766    @Override
6767    public void setProcessLimit(int max) {
6768        enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
6769                "setProcessLimit()");
6770        synchronized (this) {
6771            mProcessLimit = max < 0 ? ProcessList.MAX_CACHED_APPS : max;
6772            mProcessLimitOverride = max;
6773        }
6774        trimApplications();
6775    }
6776
6777    @Override
6778    public int getProcessLimit() {
6779        synchronized (this) {
6780            return mProcessLimitOverride;
6781        }
6782    }
6783
6784    void foregroundTokenDied(ForegroundToken token) {
6785        synchronized (ActivityManagerService.this) {
6786            synchronized (mPidsSelfLocked) {
6787                ForegroundToken cur
6788                    = mForegroundProcesses.get(token.pid);
6789                if (cur != token) {
6790                    return;
6791                }
6792                mForegroundProcesses.remove(token.pid);
6793                ProcessRecord pr = mPidsSelfLocked.get(token.pid);
6794                if (pr == null) {
6795                    return;
6796                }
6797                pr.forcingToForeground = null;
6798                updateProcessForegroundLocked(pr, false, false);
6799            }
6800            updateOomAdjLocked();
6801        }
6802    }
6803
6804    @Override
6805    public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
6806        enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
6807                "setProcessForeground()");
6808        synchronized(this) {
6809            boolean changed = false;
6810
6811            synchronized (mPidsSelfLocked) {
6812                ProcessRecord pr = mPidsSelfLocked.get(pid);
6813                if (pr == null && isForeground) {
6814                    Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
6815                    return;
6816                }
6817                ForegroundToken oldToken = mForegroundProcesses.get(pid);
6818                if (oldToken != null) {
6819                    oldToken.token.unlinkToDeath(oldToken, 0);
6820                    mForegroundProcesses.remove(pid);
6821                    if (pr != null) {
6822                        pr.forcingToForeground = null;
6823                    }
6824                    changed = true;
6825                }
6826                if (isForeground && token != null) {
6827                    ForegroundToken newToken = new ForegroundToken() {
6828                        @Override
6829                        public void binderDied() {
6830                            foregroundTokenDied(this);
6831                        }
6832                    };
6833                    newToken.pid = pid;
6834                    newToken.token = token;
6835                    try {
6836                        token.linkToDeath(newToken, 0);
6837                        mForegroundProcesses.put(pid, newToken);
6838                        pr.forcingToForeground = token;
6839                        changed = true;
6840                    } catch (RemoteException e) {
6841                        // If the process died while doing this, we will later
6842                        // do the cleanup with the process death link.
6843                    }
6844                }
6845            }
6846
6847            if (changed) {
6848                updateOomAdjLocked();
6849            }
6850        }
6851    }
6852
6853    // =========================================================
6854    // PERMISSIONS
6855    // =========================================================
6856
6857    static class PermissionController extends IPermissionController.Stub {
6858        ActivityManagerService mActivityManagerService;
6859        PermissionController(ActivityManagerService activityManagerService) {
6860            mActivityManagerService = activityManagerService;
6861        }
6862
6863        @Override
6864        public boolean checkPermission(String permission, int pid, int uid) {
6865            return mActivityManagerService.checkPermission(permission, pid,
6866                    uid) == PackageManager.PERMISSION_GRANTED;
6867        }
6868    }
6869
6870    class IntentFirewallInterface implements IntentFirewall.AMSInterface {
6871        @Override
6872        public int checkComponentPermission(String permission, int pid, int uid,
6873                int owningUid, boolean exported) {
6874            return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
6875                    owningUid, exported);
6876        }
6877
6878        @Override
6879        public Object getAMSLock() {
6880            return ActivityManagerService.this;
6881        }
6882    }
6883
6884    /**
6885     * This can be called with or without the global lock held.
6886     */
6887    int checkComponentPermission(String permission, int pid, int uid,
6888            int owningUid, boolean exported) {
6889        // We might be performing an operation on behalf of an indirect binder
6890        // invocation, e.g. via {@link #openContentUri}.  Check and adjust the
6891        // client identity accordingly before proceeding.
6892        Identity tlsIdentity = sCallerIdentity.get();
6893        if (tlsIdentity != null) {
6894            Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
6895                    + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
6896            uid = tlsIdentity.uid;
6897            pid = tlsIdentity.pid;
6898        }
6899
6900        if (pid == MY_PID) {
6901            return PackageManager.PERMISSION_GRANTED;
6902        }
6903
6904        return ActivityManager.checkComponentPermission(permission, uid,
6905                owningUid, exported);
6906    }
6907
6908    /**
6909     * As the only public entry point for permissions checking, this method
6910     * can enforce the semantic that requesting a check on a null global
6911     * permission is automatically denied.  (Internally a null permission
6912     * string is used when calling {@link #checkComponentPermission} in cases
6913     * when only uid-based security is needed.)
6914     *
6915     * This can be called with or without the global lock held.
6916     */
6917    @Override
6918    public int checkPermission(String permission, int pid, int uid) {
6919        if (permission == null) {
6920            return PackageManager.PERMISSION_DENIED;
6921        }
6922        return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
6923    }
6924
6925    /**
6926     * Binder IPC calls go through the public entry point.
6927     * This can be called with or without the global lock held.
6928     */
6929    int checkCallingPermission(String permission) {
6930        return checkPermission(permission,
6931                Binder.getCallingPid(),
6932                UserHandle.getAppId(Binder.getCallingUid()));
6933    }
6934
6935    /**
6936     * This can be called with or without the global lock held.
6937     */
6938    void enforceCallingPermission(String permission, String func) {
6939        if (checkCallingPermission(permission)
6940                == PackageManager.PERMISSION_GRANTED) {
6941            return;
6942        }
6943
6944        String msg = "Permission Denial: " + func + " from pid="
6945                + Binder.getCallingPid()
6946                + ", uid=" + Binder.getCallingUid()
6947                + " requires " + permission;
6948        Slog.w(TAG, msg);
6949        throw new SecurityException(msg);
6950    }
6951
6952    /**
6953     * Determine if UID is holding permissions required to access {@link Uri} in
6954     * the given {@link ProviderInfo}. Final permission checking is always done
6955     * in {@link ContentProvider}.
6956     */
6957    private final boolean checkHoldingPermissionsLocked(
6958            IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) {
6959        if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6960                "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid);
6961        if (UserHandle.getUserId(uid) != grantUri.sourceUserId) {
6962            if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true)
6963                    != PERMISSION_GRANTED) {
6964                return false;
6965            }
6966        }
6967        return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true);
6968    }
6969
6970    private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi,
6971            GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) {
6972        if (pi.applicationInfo.uid == uid) {
6973            return true;
6974        } else if (!pi.exported) {
6975            return false;
6976        }
6977
6978        boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
6979        boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
6980        try {
6981            // check if target holds top-level <provider> permissions
6982            if (!readMet && pi.readPermission != null && considerUidPermissions
6983                    && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
6984                readMet = true;
6985            }
6986            if (!writeMet && pi.writePermission != null && considerUidPermissions
6987                    && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
6988                writeMet = true;
6989            }
6990
6991            // track if unprotected read/write is allowed; any denied
6992            // <path-permission> below removes this ability
6993            boolean allowDefaultRead = pi.readPermission == null;
6994            boolean allowDefaultWrite = pi.writePermission == null;
6995
6996            // check if target holds any <path-permission> that match uri
6997            final PathPermission[] pps = pi.pathPermissions;
6998            if (pps != null) {
6999                final String path = grantUri.uri.getPath();
7000                int i = pps.length;
7001                while (i > 0 && (!readMet || !writeMet)) {
7002                    i--;
7003                    PathPermission pp = pps[i];
7004                    if (pp.match(path)) {
7005                        if (!readMet) {
7006                            final String pprperm = pp.getReadPermission();
7007                            if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
7008                                    + pprperm + " for " + pp.getPath()
7009                                    + ": match=" + pp.match(path)
7010                                    + " check=" + pm.checkUidPermission(pprperm, uid));
7011                            if (pprperm != null) {
7012                                if (considerUidPermissions && pm.checkUidPermission(pprperm, uid)
7013                                        == PERMISSION_GRANTED) {
7014                                    readMet = true;
7015                                } else {
7016                                    allowDefaultRead = false;
7017                                }
7018                            }
7019                        }
7020                        if (!writeMet) {
7021                            final String ppwperm = pp.getWritePermission();
7022                            if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
7023                                    + ppwperm + " for " + pp.getPath()
7024                                    + ": match=" + pp.match(path)
7025                                    + " check=" + pm.checkUidPermission(ppwperm, uid));
7026                            if (ppwperm != null) {
7027                                if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid)
7028                                        == PERMISSION_GRANTED) {
7029                                    writeMet = true;
7030                                } else {
7031                                    allowDefaultWrite = false;
7032                                }
7033                            }
7034                        }
7035                    }
7036                }
7037            }
7038
7039            // grant unprotected <provider> read/write, if not blocked by
7040            // <path-permission> above
7041            if (allowDefaultRead) readMet = true;
7042            if (allowDefaultWrite) writeMet = true;
7043
7044        } catch (RemoteException e) {
7045            return false;
7046        }
7047
7048        return readMet && writeMet;
7049    }
7050
7051    private ProviderInfo getProviderInfoLocked(String authority, int userHandle) {
7052        ProviderInfo pi = null;
7053        ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle);
7054        if (cpr != null) {
7055            pi = cpr.info;
7056        } else {
7057            try {
7058                pi = AppGlobals.getPackageManager().resolveContentProvider(
7059                        authority, PackageManager.GET_URI_PERMISSION_PATTERNS, userHandle);
7060            } catch (RemoteException ex) {
7061            }
7062        }
7063        return pi;
7064    }
7065
7066    private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) {
7067        final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
7068        if (targetUris != null) {
7069            return targetUris.get(grantUri);
7070        }
7071        return null;
7072    }
7073
7074    private UriPermission findOrCreateUriPermissionLocked(String sourcePkg,
7075            String targetPkg, int targetUid, GrantUri grantUri) {
7076        ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
7077        if (targetUris == null) {
7078            targetUris = Maps.newArrayMap();
7079            mGrantedUriPermissions.put(targetUid, targetUris);
7080        }
7081
7082        UriPermission perm = targetUris.get(grantUri);
7083        if (perm == null) {
7084            perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri);
7085            targetUris.put(grantUri, perm);
7086        }
7087
7088        return perm;
7089    }
7090
7091    private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid,
7092            final int modeFlags) {
7093        final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0;
7094        final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE
7095                : UriPermission.STRENGTH_OWNED;
7096
7097        // Root gets to do everything.
7098        if (uid == 0) {
7099            return true;
7100        }
7101
7102        final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
7103        if (perms == null) return false;
7104
7105        // First look for exact match
7106        final UriPermission exactPerm = perms.get(grantUri);
7107        if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) {
7108            return true;
7109        }
7110
7111        // No exact match, look for prefixes
7112        final int N = perms.size();
7113        for (int i = 0; i < N; i++) {
7114            final UriPermission perm = perms.valueAt(i);
7115            if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri)
7116                    && perm.getStrength(modeFlags) >= minStrength) {
7117                return true;
7118            }
7119        }
7120
7121        return false;
7122    }
7123
7124    /**
7125     * @param uri This uri must NOT contain an embedded userId.
7126     * @param userId The userId in which the uri is to be resolved.
7127     */
7128    @Override
7129    public int checkUriPermission(Uri uri, int pid, int uid,
7130            final int modeFlags, int userId) {
7131        enforceNotIsolatedCaller("checkUriPermission");
7132
7133        // Another redirected-binder-call permissions check as in
7134        // {@link checkComponentPermission}.
7135        Identity tlsIdentity = sCallerIdentity.get();
7136        if (tlsIdentity != null) {
7137            uid = tlsIdentity.uid;
7138            pid = tlsIdentity.pid;
7139        }
7140
7141        // Our own process gets to do everything.
7142        if (pid == MY_PID) {
7143            return PackageManager.PERMISSION_GRANTED;
7144        }
7145        synchronized (this) {
7146            return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags)
7147                    ? PackageManager.PERMISSION_GRANTED
7148                    : PackageManager.PERMISSION_DENIED;
7149        }
7150    }
7151
7152    /**
7153     * Check if the targetPkg can be granted permission to access uri by
7154     * the callingUid using the given modeFlags.  Throws a security exception
7155     * if callingUid is not allowed to do this.  Returns the uid of the target
7156     * if the URI permission grant should be performed; returns -1 if it is not
7157     * needed (for example targetPkg already has permission to access the URI).
7158     * If you already know the uid of the target, you can supply it in
7159     * lastTargetUid else set that to -1.
7160     */
7161    int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
7162            final int modeFlags, int lastTargetUid) {
7163        if (!Intent.isAccessUriMode(modeFlags)) {
7164            return -1;
7165        }
7166
7167        if (targetPkg != null) {
7168            if (DEBUG_URI_PERMISSION) Slog.v(TAG,
7169                    "Checking grant " + targetPkg + " permission to " + grantUri);
7170        }
7171
7172        final IPackageManager pm = AppGlobals.getPackageManager();
7173
7174        // If this is not a content: uri, we can't do anything with it.
7175        if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) {
7176            if (DEBUG_URI_PERMISSION) Slog.v(TAG,
7177                    "Can't grant URI permission for non-content URI: " + grantUri);
7178            return -1;
7179        }
7180
7181        final String authority = grantUri.uri.getAuthority();
7182        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
7183        if (pi == null) {
7184            Slog.w(TAG, "No content provider found for permission check: " +
7185                    grantUri.uri.toSafeString());
7186            return -1;
7187        }
7188
7189        int targetUid = lastTargetUid;
7190        if (targetUid < 0 && targetPkg != null) {
7191            try {
7192                targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
7193                if (targetUid < 0) {
7194                    if (DEBUG_URI_PERMISSION) Slog.v(TAG,
7195                            "Can't grant URI permission no uid for: " + targetPkg);
7196                    return -1;
7197                }
7198            } catch (RemoteException ex) {
7199                return -1;
7200            }
7201        }
7202
7203        if (targetUid >= 0) {
7204            // First...  does the target actually need this permission?
7205            if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) {
7206                // No need to grant the target this permission.
7207                if (DEBUG_URI_PERMISSION) Slog.v(TAG,
7208                        "Target " + targetPkg + " already has full permission to " + grantUri);
7209                return -1;
7210            }
7211        } else {
7212            // First...  there is no target package, so can anyone access it?
7213            boolean allowed = pi.exported;
7214            if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
7215                if (pi.readPermission != null) {
7216                    allowed = false;
7217                }
7218            }
7219            if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
7220                if (pi.writePermission != null) {
7221                    allowed = false;
7222                }
7223            }
7224            if (allowed) {
7225                return -1;
7226            }
7227        }
7228
7229        /* There is a special cross user grant if:
7230         * - The target is on another user.
7231         * - Apps on the current user can access the uri without any uid permissions.
7232         * In this case, we grant a uri permission, even if the ContentProvider does not normally
7233         * grant uri permissions.
7234         */
7235        boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId
7236                && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid,
7237                modeFlags, false /*without considering the uid permissions*/);
7238
7239        // Second...  is the provider allowing granting of URI permissions?
7240        if (!specialCrossUserGrant) {
7241            if (!pi.grantUriPermissions) {
7242                throw new SecurityException("Provider " + pi.packageName
7243                        + "/" + pi.name
7244                        + " does not allow granting of Uri permissions (uri "
7245                        + grantUri + ")");
7246            }
7247            if (pi.uriPermissionPatterns != null) {
7248                final int N = pi.uriPermissionPatterns.length;
7249                boolean allowed = false;
7250                for (int i=0; i<N; i++) {
7251                    if (pi.uriPermissionPatterns[i] != null
7252                            && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) {
7253                        allowed = true;
7254                        break;
7255                    }
7256                }
7257                if (!allowed) {
7258                    throw new SecurityException("Provider " + pi.packageName
7259                            + "/" + pi.name
7260                            + " does not allow granting of permission to path of Uri "
7261                            + grantUri);
7262                }
7263            }
7264        }
7265
7266        // Third...  does the caller itself have permission to access
7267        // this uri?
7268        if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
7269            if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
7270                // Require they hold a strong enough Uri permission
7271                if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) {
7272                    throw new SecurityException("Uid " + callingUid
7273                            + " does not have permission to uri " + grantUri);
7274                }
7275            }
7276        }
7277        return targetUid;
7278    }
7279
7280    /**
7281     * @param uri This uri must NOT contain an embedded userId.
7282     * @param userId The userId in which the uri is to be resolved.
7283     */
7284    @Override
7285    public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri,
7286            final int modeFlags, int userId) {
7287        enforceNotIsolatedCaller("checkGrantUriPermission");
7288        synchronized(this) {
7289            return checkGrantUriPermissionLocked(callingUid, targetPkg,
7290                    new GrantUri(userId, uri, false), modeFlags, -1);
7291        }
7292    }
7293
7294    void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri,
7295            final int modeFlags, UriPermissionOwner owner) {
7296        if (!Intent.isAccessUriMode(modeFlags)) {
7297            return;
7298        }
7299
7300        // So here we are: the caller has the assumed permission
7301        // to the uri, and the target doesn't.  Let's now give this to
7302        // the target.
7303
7304        if (DEBUG_URI_PERMISSION) Slog.v(TAG,
7305                "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri);
7306
7307        final String authority = grantUri.uri.getAuthority();
7308        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
7309        if (pi == null) {
7310            Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString());
7311            return;
7312        }
7313
7314        if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
7315            grantUri.prefix = true;
7316        }
7317        final UriPermission perm = findOrCreateUriPermissionLocked(
7318                pi.packageName, targetPkg, targetUid, grantUri);
7319        perm.grantModes(modeFlags, owner);
7320    }
7321
7322    void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
7323            final int modeFlags, UriPermissionOwner owner, int targetUserId) {
7324        if (targetPkg == null) {
7325            throw new NullPointerException("targetPkg");
7326        }
7327        int targetUid;
7328        final IPackageManager pm = AppGlobals.getPackageManager();
7329        try {
7330            targetUid = pm.getPackageUid(targetPkg, targetUserId);
7331        } catch (RemoteException ex) {
7332            return;
7333        }
7334
7335        targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags,
7336                targetUid);
7337        if (targetUid < 0) {
7338            return;
7339        }
7340
7341        grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags,
7342                owner);
7343    }
7344
7345    static class NeededUriGrants extends ArrayList<GrantUri> {
7346        final String targetPkg;
7347        final int targetUid;
7348        final int flags;
7349
7350        NeededUriGrants(String targetPkg, int targetUid, int flags) {
7351            this.targetPkg = targetPkg;
7352            this.targetUid = targetUid;
7353            this.flags = flags;
7354        }
7355    }
7356
7357    /**
7358     * Like checkGrantUriPermissionLocked, but takes an Intent.
7359     */
7360    NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
7361            String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) {
7362        if (DEBUG_URI_PERMISSION) Slog.v(TAG,
7363                "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
7364                + " clip=" + (intent != null ? intent.getClipData() : null)
7365                + " from " + intent + "; flags=0x"
7366                + Integer.toHexString(intent != null ? intent.getFlags() : 0));
7367
7368        if (targetPkg == null) {
7369            throw new NullPointerException("targetPkg");
7370        }
7371
7372        if (intent == null) {
7373            return null;
7374        }
7375        Uri data = intent.getData();
7376        ClipData clip = intent.getClipData();
7377        if (data == null && clip == null) {
7378            return null;
7379        }
7380        // Default userId for uris in the intent (if they don't specify it themselves)
7381        int contentUserHint = intent.getContentUserHint();
7382        if (contentUserHint == UserHandle.USER_CURRENT) {
7383            contentUserHint = UserHandle.getUserId(callingUid);
7384        }
7385        final IPackageManager pm = AppGlobals.getPackageManager();
7386        int targetUid;
7387        if (needed != null) {
7388            targetUid = needed.targetUid;
7389        } else {
7390            try {
7391                targetUid = pm.getPackageUid(targetPkg, targetUserId);
7392            } catch (RemoteException ex) {
7393                return null;
7394            }
7395            if (targetUid < 0) {
7396                if (DEBUG_URI_PERMISSION) {
7397                    Slog.v(TAG, "Can't grant URI permission no uid for: " + targetPkg
7398                            + " on user " + targetUserId);
7399                }
7400                return null;
7401            }
7402        }
7403        if (data != null) {
7404            GrantUri grantUri = GrantUri.resolve(contentUserHint, data);
7405            targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
7406                    targetUid);
7407            if (targetUid > 0) {
7408                if (needed == null) {
7409                    needed = new NeededUriGrants(targetPkg, targetUid, mode);
7410                }
7411                needed.add(grantUri);
7412            }
7413        }
7414        if (clip != null) {
7415            for (int i=0; i<clip.getItemCount(); i++) {
7416                Uri uri = clip.getItemAt(i).getUri();
7417                if (uri != null) {
7418                    GrantUri grantUri = GrantUri.resolve(contentUserHint, uri);
7419                    targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
7420                            targetUid);
7421                    if (targetUid > 0) {
7422                        if (needed == null) {
7423                            needed = new NeededUriGrants(targetPkg, targetUid, mode);
7424                        }
7425                        needed.add(grantUri);
7426                    }
7427                } else {
7428                    Intent clipIntent = clip.getItemAt(i).getIntent();
7429                    if (clipIntent != null) {
7430                        NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
7431                                callingUid, targetPkg, clipIntent, mode, needed, targetUserId);
7432                        if (newNeeded != null) {
7433                            needed = newNeeded;
7434                        }
7435                    }
7436                }
7437            }
7438        }
7439
7440        return needed;
7441    }
7442
7443    /**
7444     * Like grantUriPermissionUncheckedLocked, but takes an Intent.
7445     */
7446    void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
7447            UriPermissionOwner owner) {
7448        if (needed != null) {
7449            for (int i=0; i<needed.size(); i++) {
7450                GrantUri grantUri = needed.get(i);
7451                grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
7452                        grantUri, needed.flags, owner);
7453            }
7454        }
7455    }
7456
7457    void grantUriPermissionFromIntentLocked(int callingUid,
7458            String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) {
7459        NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
7460                intent, intent != null ? intent.getFlags() : 0, null, targetUserId);
7461        if (needed == null) {
7462            return;
7463        }
7464
7465        grantUriPermissionUncheckedFromIntentLocked(needed, owner);
7466    }
7467
7468    /**
7469     * @param uri This uri must NOT contain an embedded userId.
7470     * @param userId The userId in which the uri is to be resolved.
7471     */
7472    @Override
7473    public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
7474            final int modeFlags, int userId) {
7475        enforceNotIsolatedCaller("grantUriPermission");
7476        GrantUri grantUri = new GrantUri(userId, uri, false);
7477        synchronized(this) {
7478            final ProcessRecord r = getRecordForAppLocked(caller);
7479            if (r == null) {
7480                throw new SecurityException("Unable to find app for caller "
7481                        + caller
7482                        + " when granting permission to uri " + grantUri);
7483            }
7484            if (targetPkg == null) {
7485                throw new IllegalArgumentException("null target");
7486            }
7487            if (grantUri == null) {
7488                throw new IllegalArgumentException("null uri");
7489            }
7490
7491            Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
7492                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
7493                    | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
7494                    | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
7495
7496            grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null,
7497                    UserHandle.getUserId(r.uid));
7498        }
7499    }
7500
7501    void removeUriPermissionIfNeededLocked(UriPermission perm) {
7502        if (perm.modeFlags == 0) {
7503            final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
7504                    perm.targetUid);
7505            if (perms != null) {
7506                if (DEBUG_URI_PERMISSION) Slog.v(TAG,
7507                        "Removing " + perm.targetUid + " permission to " + perm.uri);
7508
7509                perms.remove(perm.uri);
7510                if (perms.isEmpty()) {
7511                    mGrantedUriPermissions.remove(perm.targetUid);
7512                }
7513            }
7514        }
7515    }
7516
7517    private void revokeUriPermissionLocked(int callingUid, GrantUri grantUri, final int modeFlags) {
7518        if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Revoking all granted permissions to " + grantUri);
7519
7520        final IPackageManager pm = AppGlobals.getPackageManager();
7521        final String authority = grantUri.uri.getAuthority();
7522        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
7523        if (pi == null) {
7524            Slog.w(TAG, "No content provider found for permission revoke: "
7525                    + grantUri.toSafeString());
7526            return;
7527        }
7528
7529        // Does the caller have this permission on the URI?
7530        if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
7531            // Have they don't have direct access to the URI, then revoke any URI
7532            // permissions that have been granted to them.
7533            final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
7534            if (perms != null) {
7535                boolean persistChanged = false;
7536                for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
7537                    final UriPermission perm = it.next();
7538                    if (perm.uri.sourceUserId == grantUri.sourceUserId
7539                            && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) {
7540                        if (DEBUG_URI_PERMISSION)
7541                            Slog.v(TAG,
7542                                    "Revoking " + perm.targetUid + " permission to " + perm.uri);
7543                        persistChanged |= perm.revokeModes(
7544                                modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
7545                        if (perm.modeFlags == 0) {
7546                            it.remove();
7547                        }
7548                    }
7549                }
7550                if (perms.isEmpty()) {
7551                    mGrantedUriPermissions.remove(callingUid);
7552                }
7553                if (persistChanged) {
7554                    schedulePersistUriGrants();
7555                }
7556            }
7557            return;
7558        }
7559
7560        boolean persistChanged = false;
7561
7562        // Go through all of the permissions and remove any that match.
7563        int N = mGrantedUriPermissions.size();
7564        for (int i = 0; i < N; i++) {
7565            final int targetUid = mGrantedUriPermissions.keyAt(i);
7566            final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
7567
7568            for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
7569                final UriPermission perm = it.next();
7570                if (perm.uri.sourceUserId == grantUri.sourceUserId
7571                        && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) {
7572                    if (DEBUG_URI_PERMISSION)
7573                        Slog.v(TAG,
7574                                "Revoking " + perm.targetUid + " permission to " + perm.uri);
7575                    persistChanged |= perm.revokeModes(
7576                            modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
7577                    if (perm.modeFlags == 0) {
7578                        it.remove();
7579                    }
7580                }
7581            }
7582
7583            if (perms.isEmpty()) {
7584                mGrantedUriPermissions.remove(targetUid);
7585                N--;
7586                i--;
7587            }
7588        }
7589
7590        if (persistChanged) {
7591            schedulePersistUriGrants();
7592        }
7593    }
7594
7595    /**
7596     * @param uri This uri must NOT contain an embedded userId.
7597     * @param userId The userId in which the uri is to be resolved.
7598     */
7599    @Override
7600    public void revokeUriPermission(IApplicationThread caller, Uri uri, final int modeFlags,
7601            int userId) {
7602        enforceNotIsolatedCaller("revokeUriPermission");
7603        synchronized(this) {
7604            final ProcessRecord r = getRecordForAppLocked(caller);
7605            if (r == null) {
7606                throw new SecurityException("Unable to find app for caller "
7607                        + caller
7608                        + " when revoking permission to uri " + uri);
7609            }
7610            if (uri == null) {
7611                Slog.w(TAG, "revokeUriPermission: null uri");
7612                return;
7613            }
7614
7615            if (!Intent.isAccessUriMode(modeFlags)) {
7616                return;
7617            }
7618
7619            final IPackageManager pm = AppGlobals.getPackageManager();
7620            final String authority = uri.getAuthority();
7621            final ProviderInfo pi = getProviderInfoLocked(authority, userId);
7622            if (pi == null) {
7623                Slog.w(TAG, "No content provider found for permission revoke: "
7624                        + uri.toSafeString());
7625                return;
7626            }
7627
7628            revokeUriPermissionLocked(r.uid, new GrantUri(userId, uri, false), modeFlags);
7629        }
7630    }
7631
7632    /**
7633     * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the
7634     * given package.
7635     *
7636     * @param packageName Package name to match, or {@code null} to apply to all
7637     *            packages.
7638     * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply
7639     *            to all users.
7640     * @param persistable If persistable grants should be removed.
7641     */
7642    private void removeUriPermissionsForPackageLocked(
7643            String packageName, int userHandle, boolean persistable) {
7644        if (userHandle == UserHandle.USER_ALL && packageName == null) {
7645            throw new IllegalArgumentException("Must narrow by either package or user");
7646        }
7647
7648        boolean persistChanged = false;
7649
7650        int N = mGrantedUriPermissions.size();
7651        for (int i = 0; i < N; i++) {
7652            final int targetUid = mGrantedUriPermissions.keyAt(i);
7653            final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
7654
7655            // Only inspect grants matching user
7656            if (userHandle == UserHandle.USER_ALL
7657                    || userHandle == UserHandle.getUserId(targetUid)) {
7658                for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
7659                    final UriPermission perm = it.next();
7660
7661                    // Only inspect grants matching package
7662                    if (packageName == null || perm.sourcePkg.equals(packageName)
7663                            || perm.targetPkg.equals(packageName)) {
7664                        persistChanged |= perm.revokeModes(
7665                                persistable ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
7666
7667                        // Only remove when no modes remain; any persisted grants
7668                        // will keep this alive.
7669                        if (perm.modeFlags == 0) {
7670                            it.remove();
7671                        }
7672                    }
7673                }
7674
7675                if (perms.isEmpty()) {
7676                    mGrantedUriPermissions.remove(targetUid);
7677                    N--;
7678                    i--;
7679                }
7680            }
7681        }
7682
7683        if (persistChanged) {
7684            schedulePersistUriGrants();
7685        }
7686    }
7687
7688    @Override
7689    public IBinder newUriPermissionOwner(String name) {
7690        enforceNotIsolatedCaller("newUriPermissionOwner");
7691        synchronized(this) {
7692            UriPermissionOwner owner = new UriPermissionOwner(this, name);
7693            return owner.getExternalTokenLocked();
7694        }
7695    }
7696
7697    /**
7698     * @param uri This uri must NOT contain an embedded userId.
7699     * @param sourceUserId The userId in which the uri is to be resolved.
7700     * @param targetUserId The userId of the app that receives the grant.
7701     */
7702    @Override
7703    public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri,
7704            final int modeFlags, int sourceUserId, int targetUserId) {
7705        targetUserId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7706                targetUserId, false, ALLOW_FULL_ONLY, "grantUriPermissionFromOwner", null);
7707        synchronized(this) {
7708            UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
7709            if (owner == null) {
7710                throw new IllegalArgumentException("Unknown owner: " + token);
7711            }
7712            if (fromUid != Binder.getCallingUid()) {
7713                if (Binder.getCallingUid() != Process.myUid()) {
7714                    // Only system code can grant URI permissions on behalf
7715                    // of other users.
7716                    throw new SecurityException("nice try");
7717                }
7718            }
7719            if (targetPkg == null) {
7720                throw new IllegalArgumentException("null target");
7721            }
7722            if (uri == null) {
7723                throw new IllegalArgumentException("null uri");
7724            }
7725
7726            grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false),
7727                    modeFlags, owner, targetUserId);
7728        }
7729    }
7730
7731    /**
7732     * @param uri This uri must NOT contain an embedded userId.
7733     * @param userId The userId in which the uri is to be resolved.
7734     */
7735    @Override
7736    public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) {
7737        synchronized(this) {
7738            UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
7739            if (owner == null) {
7740                throw new IllegalArgumentException("Unknown owner: " + token);
7741            }
7742
7743            if (uri == null) {
7744                owner.removeUriPermissionsLocked(mode);
7745            } else {
7746                owner.removeUriPermissionLocked(new GrantUri(userId, uri, false), mode);
7747            }
7748        }
7749    }
7750
7751    private void schedulePersistUriGrants() {
7752        if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) {
7753            mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG),
7754                    10 * DateUtils.SECOND_IN_MILLIS);
7755        }
7756    }
7757
7758    private void writeGrantedUriPermissions() {
7759        if (DEBUG_URI_PERMISSION) Slog.v(TAG, "writeGrantedUriPermissions()");
7760
7761        // Snapshot permissions so we can persist without lock
7762        ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList();
7763        synchronized (this) {
7764            final int size = mGrantedUriPermissions.size();
7765            for (int i = 0; i < size; i++) {
7766                final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
7767                for (UriPermission perm : perms.values()) {
7768                    if (perm.persistedModeFlags != 0) {
7769                        persist.add(perm.snapshot());
7770                    }
7771                }
7772            }
7773        }
7774
7775        FileOutputStream fos = null;
7776        try {
7777            fos = mGrantFile.startWrite();
7778
7779            XmlSerializer out = new FastXmlSerializer();
7780            out.setOutput(fos, "utf-8");
7781            out.startDocument(null, true);
7782            out.startTag(null, TAG_URI_GRANTS);
7783            for (UriPermission.Snapshot perm : persist) {
7784                out.startTag(null, TAG_URI_GRANT);
7785                writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId);
7786                writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId);
7787                out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg);
7788                out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg);
7789                out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri));
7790                writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix);
7791                writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags);
7792                writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime);
7793                out.endTag(null, TAG_URI_GRANT);
7794            }
7795            out.endTag(null, TAG_URI_GRANTS);
7796            out.endDocument();
7797
7798            mGrantFile.finishWrite(fos);
7799        } catch (IOException e) {
7800            if (fos != null) {
7801                mGrantFile.failWrite(fos);
7802            }
7803        }
7804    }
7805
7806    private void readGrantedUriPermissionsLocked() {
7807        if (DEBUG_URI_PERMISSION) Slog.v(TAG, "readGrantedUriPermissions()");
7808
7809        final long now = System.currentTimeMillis();
7810
7811        FileInputStream fis = null;
7812        try {
7813            fis = mGrantFile.openRead();
7814            final XmlPullParser in = Xml.newPullParser();
7815            in.setInput(fis, null);
7816
7817            int type;
7818            while ((type = in.next()) != END_DOCUMENT) {
7819                final String tag = in.getName();
7820                if (type == START_TAG) {
7821                    if (TAG_URI_GRANT.equals(tag)) {
7822                        final int sourceUserId;
7823                        final int targetUserId;
7824                        final int userHandle = readIntAttribute(in,
7825                                ATTR_USER_HANDLE, UserHandle.USER_NULL);
7826                        if (userHandle != UserHandle.USER_NULL) {
7827                            // For backwards compatibility.
7828                            sourceUserId = userHandle;
7829                            targetUserId = userHandle;
7830                        } else {
7831                            sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID);
7832                            targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID);
7833                        }
7834                        final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG);
7835                        final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG);
7836                        final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI));
7837                        final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX);
7838                        final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS);
7839                        final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now);
7840
7841                        // Sanity check that provider still belongs to source package
7842                        final ProviderInfo pi = getProviderInfoLocked(
7843                                uri.getAuthority(), sourceUserId);
7844                        if (pi != null && sourcePkg.equals(pi.packageName)) {
7845                            int targetUid = -1;
7846                            try {
7847                                targetUid = AppGlobals.getPackageManager()
7848                                        .getPackageUid(targetPkg, targetUserId);
7849                            } catch (RemoteException e) {
7850                            }
7851                            if (targetUid != -1) {
7852                                final UriPermission perm = findOrCreateUriPermissionLocked(
7853                                        sourcePkg, targetPkg, targetUid,
7854                                        new GrantUri(sourceUserId, uri, prefix));
7855                                perm.initPersistedModes(modeFlags, createdTime);
7856                            }
7857                        } else {
7858                            Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg
7859                                    + " but instead found " + pi);
7860                        }
7861                    }
7862                }
7863            }
7864        } catch (FileNotFoundException e) {
7865            // Missing grants is okay
7866        } catch (IOException e) {
7867            Log.wtf(TAG, "Failed reading Uri grants", e);
7868        } catch (XmlPullParserException e) {
7869            Log.wtf(TAG, "Failed reading Uri grants", e);
7870        } finally {
7871            IoUtils.closeQuietly(fis);
7872        }
7873    }
7874
7875    /**
7876     * @param uri This uri must NOT contain an embedded userId.
7877     * @param userId The userId in which the uri is to be resolved.
7878     */
7879    @Override
7880    public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
7881        enforceNotIsolatedCaller("takePersistableUriPermission");
7882
7883        Preconditions.checkFlagsArgument(modeFlags,
7884                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
7885
7886        synchronized (this) {
7887            final int callingUid = Binder.getCallingUid();
7888            boolean persistChanged = false;
7889            GrantUri grantUri = new GrantUri(userId, uri, false);
7890
7891            UriPermission exactPerm = findUriPermissionLocked(callingUid,
7892                    new GrantUri(userId, uri, false));
7893            UriPermission prefixPerm = findUriPermissionLocked(callingUid,
7894                    new GrantUri(userId, uri, true));
7895
7896            final boolean exactValid = (exactPerm != null)
7897                    && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags);
7898            final boolean prefixValid = (prefixPerm != null)
7899                    && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags);
7900
7901            if (!(exactValid || prefixValid)) {
7902                throw new SecurityException("No persistable permission grants found for UID "
7903                        + callingUid + " and Uri " + grantUri.toSafeString());
7904            }
7905
7906            if (exactValid) {
7907                persistChanged |= exactPerm.takePersistableModes(modeFlags);
7908            }
7909            if (prefixValid) {
7910                persistChanged |= prefixPerm.takePersistableModes(modeFlags);
7911            }
7912
7913            persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid);
7914
7915            if (persistChanged) {
7916                schedulePersistUriGrants();
7917            }
7918        }
7919    }
7920
7921    /**
7922     * @param uri This uri must NOT contain an embedded userId.
7923     * @param userId The userId in which the uri is to be resolved.
7924     */
7925    @Override
7926    public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
7927        enforceNotIsolatedCaller("releasePersistableUriPermission");
7928
7929        Preconditions.checkFlagsArgument(modeFlags,
7930                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
7931
7932        synchronized (this) {
7933            final int callingUid = Binder.getCallingUid();
7934            boolean persistChanged = false;
7935
7936            UriPermission exactPerm = findUriPermissionLocked(callingUid,
7937                    new GrantUri(userId, uri, false));
7938            UriPermission prefixPerm = findUriPermissionLocked(callingUid,
7939                    new GrantUri(userId, uri, true));
7940            if (exactPerm == null && prefixPerm == null) {
7941                throw new SecurityException("No permission grants found for UID " + callingUid
7942                        + " and Uri " + uri.toSafeString());
7943            }
7944
7945            if (exactPerm != null) {
7946                persistChanged |= exactPerm.releasePersistableModes(modeFlags);
7947                removeUriPermissionIfNeededLocked(exactPerm);
7948            }
7949            if (prefixPerm != null) {
7950                persistChanged |= prefixPerm.releasePersistableModes(modeFlags);
7951                removeUriPermissionIfNeededLocked(prefixPerm);
7952            }
7953
7954            if (persistChanged) {
7955                schedulePersistUriGrants();
7956            }
7957        }
7958    }
7959
7960    /**
7961     * Prune any older {@link UriPermission} for the given UID until outstanding
7962     * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}.
7963     *
7964     * @return if any mutations occured that require persisting.
7965     */
7966    private boolean maybePrunePersistedUriGrantsLocked(int uid) {
7967        final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
7968        if (perms == null) return false;
7969        if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false;
7970
7971        final ArrayList<UriPermission> persisted = Lists.newArrayList();
7972        for (UriPermission perm : perms.values()) {
7973            if (perm.persistedModeFlags != 0) {
7974                persisted.add(perm);
7975            }
7976        }
7977
7978        final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS;
7979        if (trimCount <= 0) return false;
7980
7981        Collections.sort(persisted, new UriPermission.PersistedTimeComparator());
7982        for (int i = 0; i < trimCount; i++) {
7983            final UriPermission perm = persisted.get(i);
7984
7985            if (DEBUG_URI_PERMISSION) {
7986                Slog.v(TAG, "Trimming grant created at " + perm.persistedCreateTime);
7987            }
7988
7989            perm.releasePersistableModes(~0);
7990            removeUriPermissionIfNeededLocked(perm);
7991        }
7992
7993        return true;
7994    }
7995
7996    @Override
7997    public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions(
7998            String packageName, boolean incoming) {
7999        enforceNotIsolatedCaller("getPersistedUriPermissions");
8000        Preconditions.checkNotNull(packageName, "packageName");
8001
8002        final int callingUid = Binder.getCallingUid();
8003        final IPackageManager pm = AppGlobals.getPackageManager();
8004        try {
8005            final int packageUid = pm.getPackageUid(packageName, UserHandle.getUserId(callingUid));
8006            if (packageUid != callingUid) {
8007                throw new SecurityException(
8008                        "Package " + packageName + " does not belong to calling UID " + callingUid);
8009            }
8010        } catch (RemoteException e) {
8011            throw new SecurityException("Failed to verify package name ownership");
8012        }
8013
8014        final ArrayList<android.content.UriPermission> result = Lists.newArrayList();
8015        synchronized (this) {
8016            if (incoming) {
8017                final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
8018                        callingUid);
8019                if (perms == null) {
8020                    Slog.w(TAG, "No permission grants found for " + packageName);
8021                } else {
8022                    for (UriPermission perm : perms.values()) {
8023                        if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) {
8024                            result.add(perm.buildPersistedPublicApiObject());
8025                        }
8026                    }
8027                }
8028            } else {
8029                final int size = mGrantedUriPermissions.size();
8030                for (int i = 0; i < size; i++) {
8031                    final ArrayMap<GrantUri, UriPermission> perms =
8032                            mGrantedUriPermissions.valueAt(i);
8033                    for (UriPermission perm : perms.values()) {
8034                        if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) {
8035                            result.add(perm.buildPersistedPublicApiObject());
8036                        }
8037                    }
8038                }
8039            }
8040        }
8041        return new ParceledListSlice<android.content.UriPermission>(result);
8042    }
8043
8044    @Override
8045    public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
8046        synchronized (this) {
8047            ProcessRecord app =
8048                who != null ? getRecordForAppLocked(who) : null;
8049            if (app == null) return;
8050
8051            Message msg = Message.obtain();
8052            msg.what = WAIT_FOR_DEBUGGER_MSG;
8053            msg.obj = app;
8054            msg.arg1 = waiting ? 1 : 0;
8055            mHandler.sendMessage(msg);
8056        }
8057    }
8058
8059    @Override
8060    public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
8061        final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
8062        final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ);
8063        outInfo.availMem = Process.getFreeMemory();
8064        outInfo.totalMem = Process.getTotalMemory();
8065        outInfo.threshold = homeAppMem;
8066        outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2));
8067        outInfo.hiddenAppThreshold = cachedAppMem;
8068        outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
8069                ProcessList.SERVICE_ADJ);
8070        outInfo.visibleAppThreshold = mProcessList.getMemLevel(
8071                ProcessList.VISIBLE_APP_ADJ);
8072        outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
8073                ProcessList.FOREGROUND_APP_ADJ);
8074    }
8075
8076    // =========================================================
8077    // TASK MANAGEMENT
8078    // =========================================================
8079
8080    @Override
8081    public List<IAppTask> getAppTasks(String callingPackage) {
8082        int callingUid = Binder.getCallingUid();
8083        long ident = Binder.clearCallingIdentity();
8084
8085        synchronized(this) {
8086            ArrayList<IAppTask> list = new ArrayList<IAppTask>();
8087            try {
8088                if (localLOGV) Slog.v(TAG, "getAppTasks");
8089
8090                final int N = mRecentTasks.size();
8091                for (int i = 0; i < N; i++) {
8092                    TaskRecord tr = mRecentTasks.get(i);
8093                    // Skip tasks that do not match the caller.  We don't need to verify
8094                    // callingPackage, because we are also limiting to callingUid and know
8095                    // that will limit to the correct security sandbox.
8096                    if (tr.effectiveUid != callingUid) {
8097                        continue;
8098                    }
8099                    Intent intent = tr.getBaseIntent();
8100                    if (intent == null ||
8101                            !callingPackage.equals(intent.getComponent().getPackageName())) {
8102                        continue;
8103                    }
8104                    ActivityManager.RecentTaskInfo taskInfo =
8105                            createRecentTaskInfoFromTaskRecord(tr);
8106                    AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid);
8107                    list.add(taskImpl);
8108                }
8109            } finally {
8110                Binder.restoreCallingIdentity(ident);
8111            }
8112            return list;
8113        }
8114    }
8115
8116    @Override
8117    public List<RunningTaskInfo> getTasks(int maxNum, int flags) {
8118        final int callingUid = Binder.getCallingUid();
8119        ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>();
8120
8121        synchronized(this) {
8122            if (localLOGV) Slog.v(
8123                TAG, "getTasks: max=" + maxNum + ", flags=" + flags);
8124
8125            final boolean allowed = checkCallingPermission(
8126                    android.Manifest.permission.GET_TASKS)
8127                    == PackageManager.PERMISSION_GRANTED;
8128            if (!allowed) {
8129                Slog.w(TAG, "getTasks: caller " + callingUid
8130                        + " does not hold GET_TASKS; limiting output");
8131            }
8132
8133            // TODO: Improve with MRU list from all ActivityStacks.
8134            mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed);
8135        }
8136
8137        return list;
8138    }
8139
8140    TaskRecord getMostRecentTask() {
8141        return mRecentTasks.get(0);
8142    }
8143
8144    /**
8145     * Creates a new RecentTaskInfo from a TaskRecord.
8146     */
8147    private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) {
8148        // Update the task description to reflect any changes in the task stack
8149        tr.updateTaskDescription();
8150
8151        // Compose the recent task info
8152        ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
8153        rti.id = tr.getTopActivity() == null ? -1 : tr.taskId;
8154        rti.persistentId = tr.taskId;
8155        rti.baseIntent = new Intent(tr.getBaseIntent());
8156        rti.origActivity = tr.origActivity;
8157        rti.description = tr.lastDescription;
8158        rti.stackId = tr.stack != null ? tr.stack.mStackId : -1;
8159        rti.userId = tr.userId;
8160        rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription);
8161        rti.firstActiveTime = tr.firstActiveTime;
8162        rti.lastActiveTime = tr.lastActiveTime;
8163        rti.affiliatedTaskId = tr.mAffiliatedTaskId;
8164        rti.affiliatedTaskColor = tr.mAffiliatedTaskColor;
8165        return rti;
8166    }
8167
8168    @Override
8169    public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) {
8170        final int callingUid = Binder.getCallingUid();
8171        userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
8172                false, ALLOW_FULL_ONLY, "getRecentTasks", null);
8173
8174        final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0;
8175        final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0;
8176        synchronized (this) {
8177            final boolean allowed = checkCallingPermission(android.Manifest.permission.GET_TASKS)
8178                    == PackageManager.PERMISSION_GRANTED;
8179            if (!allowed) {
8180                Slog.w(TAG, "getRecentTasks: caller " + callingUid
8181                        + " does not hold GET_TASKS; limiting output");
8182            }
8183            final boolean detailed = checkCallingPermission(
8184                    android.Manifest.permission.GET_DETAILED_TASKS)
8185                    == PackageManager.PERMISSION_GRANTED;
8186
8187            final int N = mRecentTasks.size();
8188            ArrayList<ActivityManager.RecentTaskInfo> res
8189                    = new ArrayList<ActivityManager.RecentTaskInfo>(
8190                            maxNum < N ? maxNum : N);
8191
8192            final Set<Integer> includedUsers;
8193            if (includeProfiles) {
8194                includedUsers = getProfileIdsLocked(userId);
8195            } else {
8196                includedUsers = new HashSet<Integer>();
8197            }
8198            includedUsers.add(Integer.valueOf(userId));
8199
8200            for (int i=0; i<N && maxNum > 0; i++) {
8201                TaskRecord tr = mRecentTasks.get(i);
8202                // Only add calling user or related users recent tasks
8203                if (!includedUsers.contains(Integer.valueOf(tr.userId))) {
8204                    if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, not user: " + tr);
8205                    continue;
8206                }
8207
8208                // Return the entry if desired by the caller.  We always return
8209                // the first entry, because callers always expect this to be the
8210                // foreground app.  We may filter others if the caller has
8211                // not supplied RECENT_WITH_EXCLUDED and there is some reason
8212                // we should exclude the entry.
8213
8214                if (i == 0
8215                        || withExcluded
8216                        || (tr.intent == null)
8217                        || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
8218                                == 0)) {
8219                    if (!allowed) {
8220                        // If the caller doesn't have the GET_TASKS permission, then only
8221                        // allow them to see a small subset of tasks -- their own and home.
8222                        if (!tr.isHomeTask() && tr.effectiveUid != callingUid) {
8223                            if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, not allowed: " + tr);
8224                            continue;
8225                        }
8226                    }
8227                    if ((flags & ActivityManager.RECENT_IGNORE_HOME_STACK_TASKS) != 0) {
8228                        if (tr.stack != null && tr.stack.isHomeStack()) {
8229                            if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, home stack task: " + tr);
8230                            continue;
8231                        }
8232                    }
8233                    if (tr.autoRemoveRecents && tr.getTopActivity() == null) {
8234                        // Don't include auto remove tasks that are finished or finishing.
8235                        if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, auto-remove without activity: "
8236                                + tr);
8237                        continue;
8238                    }
8239                    if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0
8240                            && !tr.isAvailable) {
8241                        if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, unavail real act: " + tr);
8242                        continue;
8243                    }
8244
8245                    ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr);
8246                    if (!detailed) {
8247                        rti.baseIntent.replaceExtras((Bundle)null);
8248                    }
8249
8250                    res.add(rti);
8251                    maxNum--;
8252                }
8253            }
8254            return res;
8255        }
8256    }
8257
8258    private TaskRecord recentTaskForIdLocked(int id) {
8259        final int N = mRecentTasks.size();
8260            for (int i=0; i<N; i++) {
8261                TaskRecord tr = mRecentTasks.get(i);
8262                if (tr.taskId == id) {
8263                    return tr;
8264                }
8265            }
8266            return null;
8267    }
8268
8269    @Override
8270    public ActivityManager.TaskThumbnail getTaskThumbnail(int id) {
8271        synchronized (this) {
8272            enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
8273                    "getTaskThumbnail()");
8274            TaskRecord tr = recentTaskForIdLocked(id);
8275            if (tr != null) {
8276                return tr.getTaskThumbnailLocked();
8277            }
8278        }
8279        return null;
8280    }
8281
8282    @Override
8283    public int addAppTask(IBinder activityToken, Intent intent,
8284            ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
8285        final int callingUid = Binder.getCallingUid();
8286        final long callingIdent = Binder.clearCallingIdentity();
8287
8288        try {
8289            synchronized (this) {
8290                ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
8291                if (r == null) {
8292                    throw new IllegalArgumentException("Activity does not exist; token="
8293                            + activityToken);
8294                }
8295                ComponentName comp = intent.getComponent();
8296                if (comp == null) {
8297                    throw new IllegalArgumentException("Intent " + intent
8298                            + " must specify explicit component");
8299                }
8300                if (thumbnail.getWidth() != mThumbnailWidth
8301                        || thumbnail.getHeight() != mThumbnailHeight) {
8302                    throw new IllegalArgumentException("Bad thumbnail size: got "
8303                            + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
8304                            + mThumbnailWidth + "x" + mThumbnailHeight);
8305                }
8306                if (intent.getSelector() != null) {
8307                    intent.setSelector(null);
8308                }
8309                if (intent.getSourceBounds() != null) {
8310                    intent.setSourceBounds(null);
8311                }
8312                if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
8313                    if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
8314                        // The caller has added this as an auto-remove task...  that makes no
8315                        // sense, so turn off auto-remove.
8316                        intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
8317                    }
8318                } else if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
8319                    // Must be a new task.
8320                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8321                }
8322                if (!comp.equals(mLastAddedTaskComponent) || callingUid != mLastAddedTaskUid) {
8323                    mLastAddedTaskActivity = null;
8324                }
8325                ActivityInfo ainfo = mLastAddedTaskActivity;
8326                if (ainfo == null) {
8327                    ainfo = mLastAddedTaskActivity = AppGlobals.getPackageManager().getActivityInfo(
8328                            comp, 0, UserHandle.getUserId(callingUid));
8329                    if (ainfo.applicationInfo.uid != callingUid) {
8330                        throw new SecurityException(
8331                                "Can't add task for another application: target uid="
8332                                + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
8333                    }
8334                }
8335
8336                TaskRecord task = new TaskRecord(this, mStackSupervisor.getNextTaskId(), ainfo,
8337                        intent, description);
8338
8339                int trimIdx = trimRecentsForTask(task, false);
8340                if (trimIdx >= 0) {
8341                    // If this would have caused a trim, then we'll abort because that
8342                    // means it would be added at the end of the list but then just removed.
8343                    return -1;
8344                }
8345
8346                final int N = mRecentTasks.size();
8347                if (N >= (ActivityManager.getMaxRecentTasksStatic()-1)) {
8348                    final TaskRecord tr = mRecentTasks.remove(N - 1);
8349                    tr.removedFromRecents(mTaskPersister);
8350                }
8351
8352                task.inRecents = true;
8353                mRecentTasks.add(task);
8354                r.task.stack.addTask(task, false, false);
8355
8356                task.setLastThumbnail(thumbnail);
8357                task.freeLastThumbnail();
8358
8359                return task.taskId;
8360            }
8361        } finally {
8362            Binder.restoreCallingIdentity(callingIdent);
8363        }
8364    }
8365
8366    @Override
8367    public Point getAppTaskThumbnailSize() {
8368        synchronized (this) {
8369            return new Point(mThumbnailWidth,  mThumbnailHeight);
8370        }
8371    }
8372
8373    @Override
8374    public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
8375        synchronized (this) {
8376            ActivityRecord r = ActivityRecord.isInStackLocked(token);
8377            if (r != null) {
8378                r.taskDescription = td;
8379                r.task.updateTaskDescription();
8380            }
8381        }
8382    }
8383
8384    private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
8385        mRecentTasks.remove(tr);
8386        tr.removedFromRecents(mTaskPersister);
8387        final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
8388        Intent baseIntent = new Intent(
8389                tr.intent != null ? tr.intent : tr.affinityIntent);
8390        ComponentName component = baseIntent.getComponent();
8391        if (component == null) {
8392            Slog.w(TAG, "Now component for base intent of task: " + tr);
8393            return;
8394        }
8395
8396        // Find any running services associated with this app.
8397        mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
8398
8399        if (killProcesses) {
8400            // Find any running processes associated with this app.
8401            final String pkg = component.getPackageName();
8402            ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
8403            ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
8404            for (int i=0; i<pmap.size(); i++) {
8405                SparseArray<ProcessRecord> uids = pmap.valueAt(i);
8406                for (int j=0; j<uids.size(); j++) {
8407                    ProcessRecord proc = uids.valueAt(j);
8408                    if (proc.userId != tr.userId) {
8409                        continue;
8410                    }
8411                    if (!proc.pkgList.containsKey(pkg)) {
8412                        continue;
8413                    }
8414                    procs.add(proc);
8415                }
8416            }
8417
8418            // Kill the running processes.
8419            for (int i=0; i<procs.size(); i++) {
8420                ProcessRecord pr = procs.get(i);
8421                if (pr == mHomeProcess) {
8422                    // Don't kill the home process along with tasks from the same package.
8423                    continue;
8424                }
8425                if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
8426                    pr.kill("remove task", true);
8427                } else {
8428                    pr.waitingToKill = "remove task";
8429                }
8430            }
8431        }
8432    }
8433
8434    /**
8435     * Removes the task with the specified task id.
8436     *
8437     * @param taskId Identifier of the task to be removed.
8438     * @param flags Additional operational flags.  May be 0 or
8439     * {@link ActivityManager#REMOVE_TASK_KILL_PROCESS}.
8440     * @return Returns true if the given task was found and removed.
8441     */
8442    private boolean removeTaskByIdLocked(int taskId, int flags) {
8443        TaskRecord tr = recentTaskForIdLocked(taskId);
8444        if (tr != null) {
8445            tr.removeTaskActivitiesLocked();
8446            cleanUpRemovedTaskLocked(tr, flags);
8447            if (tr.isPersistable) {
8448                notifyTaskPersisterLocked(null, true);
8449            }
8450            return true;
8451        }
8452        return false;
8453    }
8454
8455    @Override
8456    public boolean removeTask(int taskId, int flags) {
8457        synchronized (this) {
8458            enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
8459                    "removeTask()");
8460            long ident = Binder.clearCallingIdentity();
8461            try {
8462                return removeTaskByIdLocked(taskId, flags);
8463            } finally {
8464                Binder.restoreCallingIdentity(ident);
8465            }
8466        }
8467    }
8468
8469    /**
8470     * TODO: Add mController hook
8471     */
8472    @Override
8473    public void moveTaskToFront(int taskId, int flags, Bundle options) {
8474        enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
8475                "moveTaskToFront()");
8476
8477        if (DEBUG_STACK) Slog.d(TAG, "moveTaskToFront: moving taskId=" + taskId);
8478        synchronized(this) {
8479            moveTaskToFrontLocked(taskId, flags, options);
8480        }
8481    }
8482
8483    void moveTaskToFrontLocked(int taskId, int flags, Bundle options) {
8484        if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
8485                Binder.getCallingUid(), -1, -1, "Task to front")) {
8486            ActivityOptions.abort(options);
8487            return;
8488        }
8489        final long origId = Binder.clearCallingIdentity();
8490        try {
8491            final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
8492            if (task == null) {
8493                return;
8494            }
8495            if (mStackSupervisor.isLockTaskModeViolation(task)) {
8496                mStackSupervisor.showLockTaskToast();
8497                Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
8498                return;
8499            }
8500            final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked();
8501            if (prev != null && prev.isRecentsActivity()) {
8502                task.setTaskToReturnTo(ActivityRecord.RECENTS_ACTIVITY_TYPE);
8503            }
8504            mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options);
8505        } finally {
8506            Binder.restoreCallingIdentity(origId);
8507        }
8508        ActivityOptions.abort(options);
8509    }
8510
8511    @Override
8512    public void moveTaskToBack(int taskId) {
8513        enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
8514                "moveTaskToBack()");
8515
8516        synchronized(this) {
8517            TaskRecord tr = recentTaskForIdLocked(taskId);
8518            if (tr != null) {
8519                if (tr == mStackSupervisor.mLockTaskModeTask) {
8520                    mStackSupervisor.showLockTaskToast();
8521                    return;
8522                }
8523                if (DEBUG_STACK) Slog.d(TAG, "moveTaskToBack: moving task=" + tr);
8524                ActivityStack stack = tr.stack;
8525                if (stack.mResumedActivity != null && stack.mResumedActivity.task == tr) {
8526                    if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
8527                            Binder.getCallingUid(), -1, -1, "Task to back")) {
8528                        return;
8529                    }
8530                }
8531                final long origId = Binder.clearCallingIdentity();
8532                try {
8533                    stack.moveTaskToBackLocked(taskId, null);
8534                } finally {
8535                    Binder.restoreCallingIdentity(origId);
8536                }
8537            }
8538        }
8539    }
8540
8541    /**
8542     * Moves an activity, and all of the other activities within the same task, to the bottom
8543     * of the history stack.  The activity's order within the task is unchanged.
8544     *
8545     * @param token A reference to the activity we wish to move
8546     * @param nonRoot If false then this only works if the activity is the root
8547     *                of a task; if true it will work for any activity in a task.
8548     * @return Returns true if the move completed, false if not.
8549     */
8550    @Override
8551    public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
8552        enforceNotIsolatedCaller("moveActivityTaskToBack");
8553        synchronized(this) {
8554            final long origId = Binder.clearCallingIdentity();
8555            try {
8556                int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
8557                if (taskId >= 0) {
8558                    if ((mStackSupervisor.mLockTaskModeTask != null)
8559                            && (mStackSupervisor.mLockTaskModeTask.taskId == taskId)) {
8560                        mStackSupervisor.showLockTaskToast();
8561                        return false;
8562                    }
8563                    return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId, null);
8564                }
8565            } finally {
8566                Binder.restoreCallingIdentity(origId);
8567            }
8568        }
8569        return false;
8570    }
8571
8572    @Override
8573    public void moveTaskBackwards(int task) {
8574        enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
8575                "moveTaskBackwards()");
8576
8577        synchronized(this) {
8578            if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
8579                    Binder.getCallingUid(), -1, -1, "Task backwards")) {
8580                return;
8581            }
8582            final long origId = Binder.clearCallingIdentity();
8583            moveTaskBackwardsLocked(task);
8584            Binder.restoreCallingIdentity(origId);
8585        }
8586    }
8587
8588    private final void moveTaskBackwardsLocked(int task) {
8589        Slog.e(TAG, "moveTaskBackwards not yet implemented!");
8590    }
8591
8592    @Override
8593    public IBinder getHomeActivityToken() throws RemoteException {
8594        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8595                "getHomeActivityToken()");
8596        synchronized (this) {
8597            return mStackSupervisor.getHomeActivityToken();
8598        }
8599    }
8600
8601    @Override
8602    public IActivityContainer createActivityContainer(IBinder parentActivityToken,
8603            IActivityContainerCallback callback) throws RemoteException {
8604        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8605                "createActivityContainer()");
8606        synchronized (this) {
8607            if (parentActivityToken == null) {
8608                throw new IllegalArgumentException("parent token must not be null");
8609            }
8610            ActivityRecord r = ActivityRecord.forToken(parentActivityToken);
8611            if (r == null) {
8612                return null;
8613            }
8614            if (callback == null) {
8615                throw new IllegalArgumentException("callback must not be null");
8616            }
8617            return mStackSupervisor.createActivityContainer(r, callback);
8618        }
8619    }
8620
8621    @Override
8622    public void deleteActivityContainer(IActivityContainer container) throws RemoteException {
8623        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8624                "deleteActivityContainer()");
8625        synchronized (this) {
8626            mStackSupervisor.deleteActivityContainer(container);
8627        }
8628    }
8629
8630    @Override
8631    public IActivityContainer getEnclosingActivityContainer(IBinder activityToken)
8632            throws RemoteException {
8633        synchronized (this) {
8634            ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
8635            if (stack != null) {
8636                return stack.mActivityContainer;
8637            }
8638            return null;
8639        }
8640    }
8641
8642    @Override
8643    public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
8644        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8645                "moveTaskToStack()");
8646        if (stackId == HOME_STACK_ID) {
8647            Slog.e(TAG, "moveTaskToStack: Attempt to move task " + taskId + " to home stack",
8648                    new RuntimeException("here").fillInStackTrace());
8649        }
8650        synchronized (this) {
8651            long ident = Binder.clearCallingIdentity();
8652            try {
8653                if (DEBUG_STACK) Slog.d(TAG, "moveTaskToStack: moving task=" + taskId + " to stackId="
8654                        + stackId + " toTop=" + toTop);
8655                mStackSupervisor.moveTaskToStack(taskId, stackId, toTop);
8656            } finally {
8657                Binder.restoreCallingIdentity(ident);
8658            }
8659        }
8660    }
8661
8662    @Override
8663    public void resizeStack(int stackBoxId, Rect bounds) {
8664        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8665                "resizeStackBox()");
8666        long ident = Binder.clearCallingIdentity();
8667        try {
8668            mWindowManager.resizeStack(stackBoxId, bounds);
8669        } finally {
8670            Binder.restoreCallingIdentity(ident);
8671        }
8672    }
8673
8674    @Override
8675    public List<StackInfo> getAllStackInfos() {
8676        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8677                "getAllStackInfos()");
8678        long ident = Binder.clearCallingIdentity();
8679        try {
8680            synchronized (this) {
8681                return mStackSupervisor.getAllStackInfosLocked();
8682            }
8683        } finally {
8684            Binder.restoreCallingIdentity(ident);
8685        }
8686    }
8687
8688    @Override
8689    public StackInfo getStackInfo(int stackId) {
8690        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8691                "getStackInfo()");
8692        long ident = Binder.clearCallingIdentity();
8693        try {
8694            synchronized (this) {
8695                return mStackSupervisor.getStackInfoLocked(stackId);
8696            }
8697        } finally {
8698            Binder.restoreCallingIdentity(ident);
8699        }
8700    }
8701
8702    @Override
8703    public boolean isInHomeStack(int taskId) {
8704        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8705                "getStackInfo()");
8706        long ident = Binder.clearCallingIdentity();
8707        try {
8708            synchronized (this) {
8709                TaskRecord tr = recentTaskForIdLocked(taskId);
8710                return tr != null && tr.stack != null && tr.stack.isHomeStack();
8711            }
8712        } finally {
8713            Binder.restoreCallingIdentity(ident);
8714        }
8715    }
8716
8717    @Override
8718    public int getTaskForActivity(IBinder token, boolean onlyRoot) {
8719        synchronized(this) {
8720            return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
8721        }
8722    }
8723
8724    private boolean isLockTaskAuthorized(String pkg) {
8725        final DevicePolicyManager dpm = (DevicePolicyManager)
8726                mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
8727        try {
8728            int uid = mContext.getPackageManager().getPackageUid(pkg,
8729                    Binder.getCallingUserHandle().getIdentifier());
8730            return (uid == Binder.getCallingUid()) && dpm != null && dpm.isLockTaskPermitted(pkg);
8731        } catch (NameNotFoundException e) {
8732            return false;
8733        }
8734    }
8735
8736    void startLockTaskMode(TaskRecord task) {
8737        final String pkg;
8738        synchronized (this) {
8739            pkg = task.intent.getComponent().getPackageName();
8740        }
8741        boolean isSystemInitiated = Binder.getCallingUid() == Process.SYSTEM_UID;
8742        if (!isSystemInitiated && !isLockTaskAuthorized(pkg)) {
8743            final TaskRecord taskRecord = task;
8744            mHandler.post(new Runnable() {
8745                @Override
8746                public void run() {
8747                    mLockToAppRequest.showLockTaskPrompt(taskRecord);
8748                }
8749            });
8750            return;
8751        }
8752        long ident = Binder.clearCallingIdentity();
8753        try {
8754            synchronized (this) {
8755                // Since we lost lock on task, make sure it is still there.
8756                task = mStackSupervisor.anyTaskForIdLocked(task.taskId);
8757                if (task != null) {
8758                    if (!isSystemInitiated
8759                            && ((mFocusedActivity == null) || (task != mFocusedActivity.task))) {
8760                        throw new IllegalArgumentException("Invalid task, not in foreground");
8761                    }
8762                    mStackSupervisor.setLockTaskModeLocked(task, !isSystemInitiated);
8763                }
8764            }
8765        } finally {
8766            Binder.restoreCallingIdentity(ident);
8767        }
8768    }
8769
8770    @Override
8771    public void startLockTaskMode(int taskId) {
8772        final TaskRecord task;
8773        long ident = Binder.clearCallingIdentity();
8774        try {
8775            synchronized (this) {
8776                task = mStackSupervisor.anyTaskForIdLocked(taskId);
8777            }
8778        } finally {
8779            Binder.restoreCallingIdentity(ident);
8780        }
8781        if (task != null) {
8782            startLockTaskMode(task);
8783        }
8784    }
8785
8786    @Override
8787    public void startLockTaskMode(IBinder token) {
8788        final TaskRecord task;
8789        long ident = Binder.clearCallingIdentity();
8790        try {
8791            synchronized (this) {
8792                final ActivityRecord r = ActivityRecord.forToken(token);
8793                if (r == null) {
8794                    return;
8795                }
8796                task = r.task;
8797            }
8798        } finally {
8799            Binder.restoreCallingIdentity(ident);
8800        }
8801        if (task != null) {
8802            startLockTaskMode(task);
8803        }
8804    }
8805
8806    @Override
8807    public void startLockTaskModeOnCurrent() throws RemoteException {
8808        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8809                "startLockTaskModeOnCurrent");
8810        ActivityRecord r = null;
8811        synchronized (this) {
8812            r = mStackSupervisor.topRunningActivityLocked();
8813        }
8814        startLockTaskMode(r.task);
8815    }
8816
8817    @Override
8818    public void stopLockTaskMode() {
8819        // Verify that the user matches the package of the intent for the TaskRecord
8820        // we are locked to or systtem.  This will ensure the same caller for startLockTaskMode
8821        // and stopLockTaskMode.
8822        final int callingUid = Binder.getCallingUid();
8823        if (callingUid != Process.SYSTEM_UID) {
8824            try {
8825                String pkg =
8826                        mStackSupervisor.mLockTaskModeTask.intent.getComponent().getPackageName();
8827                int uid = mContext.getPackageManager().getPackageUid(pkg,
8828                        Binder.getCallingUserHandle().getIdentifier());
8829                if (uid != callingUid) {
8830                    throw new SecurityException("Invalid uid, expected " + uid);
8831                }
8832            } catch (NameNotFoundException e) {
8833                Log.d(TAG, "stopLockTaskMode " + e);
8834                return;
8835            }
8836        }
8837        long ident = Binder.clearCallingIdentity();
8838        try {
8839            Log.d(TAG, "stopLockTaskMode");
8840            // Stop lock task
8841            synchronized (this) {
8842                mStackSupervisor.setLockTaskModeLocked(null, false);
8843            }
8844        } finally {
8845            Binder.restoreCallingIdentity(ident);
8846        }
8847    }
8848
8849    @Override
8850    public void stopLockTaskModeOnCurrent() throws RemoteException {
8851        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
8852                "stopLockTaskModeOnCurrent");
8853        long ident = Binder.clearCallingIdentity();
8854        try {
8855            stopLockTaskMode();
8856        } finally {
8857            Binder.restoreCallingIdentity(ident);
8858        }
8859    }
8860
8861    @Override
8862    public boolean isInLockTaskMode() {
8863        synchronized (this) {
8864            return mStackSupervisor.isInLockTaskMode();
8865        }
8866    }
8867
8868    // =========================================================
8869    // CONTENT PROVIDERS
8870    // =========================================================
8871
8872    private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
8873        List<ProviderInfo> providers = null;
8874        try {
8875            providers = AppGlobals.getPackageManager().
8876                queryContentProviders(app.processName, app.uid,
8877                        STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
8878        } catch (RemoteException ex) {
8879        }
8880        if (DEBUG_MU)
8881            Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
8882        int userId = app.userId;
8883        if (providers != null) {
8884            int N = providers.size();
8885            app.pubProviders.ensureCapacity(N + app.pubProviders.size());
8886            for (int i=0; i<N; i++) {
8887                ProviderInfo cpi =
8888                    (ProviderInfo)providers.get(i);
8889                boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
8890                        cpi.name, cpi.flags);
8891                if (singleton && UserHandle.getUserId(app.uid) != 0) {
8892                    // This is a singleton provider, but a user besides the
8893                    // default user is asking to initialize a process it runs
8894                    // in...  well, no, it doesn't actually run in this process,
8895                    // it runs in the process of the default user.  Get rid of it.
8896                    providers.remove(i);
8897                    N--;
8898                    i--;
8899                    continue;
8900                }
8901
8902                ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
8903                ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
8904                if (cpr == null) {
8905                    cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
8906                    mProviderMap.putProviderByClass(comp, cpr);
8907                }
8908                if (DEBUG_MU)
8909                    Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
8910                app.pubProviders.put(cpi.name, cpr);
8911                if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
8912                    // Don't add this if it is a platform component that is marked
8913                    // to run in multiple processes, because this is actually
8914                    // part of the framework so doesn't make sense to track as a
8915                    // separate apk in the process.
8916                    app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode,
8917                            mProcessStats);
8918                }
8919                ensurePackageDexOpt(cpi.applicationInfo.packageName);
8920            }
8921        }
8922        return providers;
8923    }
8924
8925    /**
8926     * Check if {@link ProcessRecord} has a possible chance at accessing the
8927     * given {@link ProviderInfo}. Final permission checking is always done
8928     * in {@link ContentProvider}.
8929     */
8930    private final String checkContentProviderPermissionLocked(
8931            ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) {
8932        final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
8933        final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
8934        boolean checkedGrants = false;
8935        if (checkUser) {
8936            // Looking for cross-user grants before enforcing the typical cross-users permissions
8937            int tmpTargetUserId = unsafeConvertIncomingUser(userId);
8938            if (tmpTargetUserId != UserHandle.getUserId(callingUid)) {
8939                if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) {
8940                    return null;
8941                }
8942                checkedGrants = true;
8943            }
8944            userId = handleIncomingUser(callingPid, callingUid, userId,
8945                    false, ALLOW_NON_FULL,
8946                    "checkContentProviderPermissionLocked " + cpi.authority, null);
8947            if (userId != tmpTargetUserId) {
8948                // When we actually went to determine the final targer user ID, this ended
8949                // up different than our initial check for the authority.  This is because
8950                // they had asked for USER_CURRENT_OR_SELF and we ended up switching to
8951                // SELF.  So we need to re-check the grants again.
8952                checkedGrants = false;
8953            }
8954        }
8955        if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
8956                cpi.applicationInfo.uid, cpi.exported)
8957                == PackageManager.PERMISSION_GRANTED) {
8958            return null;
8959        }
8960        if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
8961                cpi.applicationInfo.uid, cpi.exported)
8962                == PackageManager.PERMISSION_GRANTED) {
8963            return null;
8964        }
8965
8966        PathPermission[] pps = cpi.pathPermissions;
8967        if (pps != null) {
8968            int i = pps.length;
8969            while (i > 0) {
8970                i--;
8971                PathPermission pp = pps[i];
8972                String pprperm = pp.getReadPermission();
8973                if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid,
8974                        cpi.applicationInfo.uid, cpi.exported)
8975                        == PackageManager.PERMISSION_GRANTED) {
8976                    return null;
8977                }
8978                String ppwperm = pp.getWritePermission();
8979                if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid,
8980                        cpi.applicationInfo.uid, cpi.exported)
8981                        == PackageManager.PERMISSION_GRANTED) {
8982                    return null;
8983                }
8984            }
8985        }
8986        if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) {
8987            return null;
8988        }
8989
8990        String msg;
8991        if (!cpi.exported) {
8992            msg = "Permission Denial: opening provider " + cpi.name
8993                    + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
8994                    + ", uid=" + callingUid + ") that is not exported from uid "
8995                    + cpi.applicationInfo.uid;
8996        } else {
8997            msg = "Permission Denial: opening provider " + cpi.name
8998                    + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
8999                    + ", uid=" + callingUid + ") requires "
9000                    + cpi.readPermission + " or " + cpi.writePermission;
9001        }
9002        Slog.w(TAG, msg);
9003        return msg;
9004    }
9005
9006    /**
9007     * Returns if the ContentProvider has granted a uri to callingUid
9008     */
9009    boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) {
9010        final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
9011        if (perms != null) {
9012            for (int i=perms.size()-1; i>=0; i--) {
9013                GrantUri grantUri = perms.keyAt(i);
9014                if (grantUri.sourceUserId == userId || !checkUser) {
9015                    if (matchesProvider(grantUri.uri, cpi)) {
9016                        return true;
9017                    }
9018                }
9019            }
9020        }
9021        return false;
9022    }
9023
9024    /**
9025     * Returns true if the uri authority is one of the authorities specified in the provider.
9026     */
9027    boolean matchesProvider(Uri uri, ProviderInfo cpi) {
9028        String uriAuth = uri.getAuthority();
9029        String cpiAuth = cpi.authority;
9030        if (cpiAuth.indexOf(';') == -1) {
9031            return cpiAuth.equals(uriAuth);
9032        }
9033        String[] cpiAuths = cpiAuth.split(";");
9034        int length = cpiAuths.length;
9035        for (int i = 0; i < length; i++) {
9036            if (cpiAuths[i].equals(uriAuth)) return true;
9037        }
9038        return false;
9039    }
9040
9041    ContentProviderConnection incProviderCountLocked(ProcessRecord r,
9042            final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
9043        if (r != null) {
9044            for (int i=0; i<r.conProviders.size(); i++) {
9045                ContentProviderConnection conn = r.conProviders.get(i);
9046                if (conn.provider == cpr) {
9047                    if (DEBUG_PROVIDER) Slog.v(TAG,
9048                            "Adding provider requested by "
9049                            + r.processName + " from process "
9050                            + cpr.info.processName + ": " + cpr.name.flattenToShortString()
9051                            + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
9052                    if (stable) {
9053                        conn.stableCount++;
9054                        conn.numStableIncs++;
9055                    } else {
9056                        conn.unstableCount++;
9057                        conn.numUnstableIncs++;
9058                    }
9059                    return conn;
9060                }
9061            }
9062            ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
9063            if (stable) {
9064                conn.stableCount = 1;
9065                conn.numStableIncs = 1;
9066            } else {
9067                conn.unstableCount = 1;
9068                conn.numUnstableIncs = 1;
9069            }
9070            cpr.connections.add(conn);
9071            r.conProviders.add(conn);
9072            return conn;
9073        }
9074        cpr.addExternalProcessHandleLocked(externalProcessToken);
9075        return null;
9076    }
9077
9078    boolean decProviderCountLocked(ContentProviderConnection conn,
9079            ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
9080        if (conn != null) {
9081            cpr = conn.provider;
9082            if (DEBUG_PROVIDER) Slog.v(TAG,
9083                    "Removing provider requested by "
9084                    + conn.client.processName + " from process "
9085                    + cpr.info.processName + ": " + cpr.name.flattenToShortString()
9086                    + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
9087            if (stable) {
9088                conn.stableCount--;
9089            } else {
9090                conn.unstableCount--;
9091            }
9092            if (conn.stableCount == 0 && conn.unstableCount == 0) {
9093                cpr.connections.remove(conn);
9094                conn.client.conProviders.remove(conn);
9095                return true;
9096            }
9097            return false;
9098        }
9099        cpr.removeExternalProcessHandleLocked(externalProcessToken);
9100        return false;
9101    }
9102
9103    private void checkTime(long startTime, String where) {
9104        long now = SystemClock.elapsedRealtime();
9105        if ((now-startTime) > 1000) {
9106            // If we are taking more than a second, log about it.
9107            Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where);
9108        }
9109    }
9110
9111    private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
9112            String name, IBinder token, boolean stable, int userId) {
9113        ContentProviderRecord cpr;
9114        ContentProviderConnection conn = null;
9115        ProviderInfo cpi = null;
9116
9117        synchronized(this) {
9118            long startTime = SystemClock.elapsedRealtime();
9119
9120            ProcessRecord r = null;
9121            if (caller != null) {
9122                r = getRecordForAppLocked(caller);
9123                if (r == null) {
9124                    throw new SecurityException(
9125                            "Unable to find app for caller " + caller
9126                          + " (pid=" + Binder.getCallingPid()
9127                          + ") when getting content provider " + name);
9128                }
9129            }
9130
9131            boolean checkCrossUser = true;
9132
9133            checkTime(startTime, "getContentProviderImpl: getProviderByName");
9134
9135            // First check if this content provider has been published...
9136            cpr = mProviderMap.getProviderByName(name, userId);
9137            // If that didn't work, check if it exists for user 0 and then
9138            // verify that it's a singleton provider before using it.
9139            if (cpr == null && userId != UserHandle.USER_OWNER) {
9140                cpr = mProviderMap.getProviderByName(name, UserHandle.USER_OWNER);
9141                if (cpr != null) {
9142                    cpi = cpr.info;
9143                    if (isSingleton(cpi.processName, cpi.applicationInfo,
9144                            cpi.name, cpi.flags)
9145                            && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) {
9146                        userId = UserHandle.USER_OWNER;
9147                        checkCrossUser = false;
9148                    } else {
9149                        cpr = null;
9150                        cpi = null;
9151                    }
9152                }
9153            }
9154
9155            boolean providerRunning = cpr != null;
9156            if (providerRunning) {
9157                cpi = cpr.info;
9158                String msg;
9159                checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
9160                if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
9161                        != null) {
9162                    throw new SecurityException(msg);
9163                }
9164                checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission");
9165
9166                if (r != null && cpr.canRunHere(r)) {
9167                    // This provider has been published or is in the process
9168                    // of being published...  but it is also allowed to run
9169                    // in the caller's process, so don't make a connection
9170                    // and just let the caller instantiate its own instance.
9171                    ContentProviderHolder holder = cpr.newHolder(null);
9172                    // don't give caller the provider object, it needs
9173                    // to make its own.
9174                    holder.provider = null;
9175                    return holder;
9176                }
9177
9178                final long origId = Binder.clearCallingIdentity();
9179
9180                checkTime(startTime, "getContentProviderImpl: incProviderCountLocked");
9181
9182                // In this case the provider instance already exists, so we can
9183                // return it right away.
9184                conn = incProviderCountLocked(r, cpr, token, stable);
9185                if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
9186                    if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
9187                        // If this is a perceptible app accessing the provider,
9188                        // make sure to count it as being accessed and thus
9189                        // back up on the LRU list.  This is good because
9190                        // content providers are often expensive to start.
9191                        checkTime(startTime, "getContentProviderImpl: before updateLruProcess");
9192                        updateLruProcessLocked(cpr.proc, false, null);
9193                        checkTime(startTime, "getContentProviderImpl: after updateLruProcess");
9194                    }
9195                }
9196
9197                if (cpr.proc != null) {
9198                    if (false) {
9199                        if (cpr.name.flattenToShortString().equals(
9200                                "com.android.providers.calendar/.CalendarProvider2")) {
9201                            Slog.v(TAG, "****************** KILLING "
9202                                + cpr.name.flattenToShortString());
9203                            Process.killProcess(cpr.proc.pid);
9204                        }
9205                    }
9206                    checkTime(startTime, "getContentProviderImpl: before updateOomAdj");
9207                    boolean success = updateOomAdjLocked(cpr.proc);
9208                    checkTime(startTime, "getContentProviderImpl: after updateOomAdj");
9209                    if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
9210                    // NOTE: there is still a race here where a signal could be
9211                    // pending on the process even though we managed to update its
9212                    // adj level.  Not sure what to do about this, but at least
9213                    // the race is now smaller.
9214                    if (!success) {
9215                        // Uh oh...  it looks like the provider's process
9216                        // has been killed on us.  We need to wait for a new
9217                        // process to be started, and make sure its death
9218                        // doesn't kill our process.
9219                        Slog.i(TAG,
9220                                "Existing provider " + cpr.name.flattenToShortString()
9221                                + " is crashing; detaching " + r);
9222                        boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
9223                        checkTime(startTime, "getContentProviderImpl: before appDied");
9224                        appDiedLocked(cpr.proc);
9225                        checkTime(startTime, "getContentProviderImpl: after appDied");
9226                        if (!lastRef) {
9227                            // This wasn't the last ref our process had on
9228                            // the provider...  we have now been killed, bail.
9229                            return null;
9230                        }
9231                        providerRunning = false;
9232                        conn = null;
9233                    }
9234                }
9235
9236                Binder.restoreCallingIdentity(origId);
9237            }
9238
9239            boolean singleton;
9240            if (!providerRunning) {
9241                try {
9242                    checkTime(startTime, "getContentProviderImpl: before resolveContentProvider");
9243                    cpi = AppGlobals.getPackageManager().
9244                        resolveContentProvider(name,
9245                            STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
9246                    checkTime(startTime, "getContentProviderImpl: after resolveContentProvider");
9247                } catch (RemoteException ex) {
9248                }
9249                if (cpi == null) {
9250                    return null;
9251                }
9252                // If the provider is a singleton AND
9253                // (it's a call within the same user || the provider is a
9254                // privileged app)
9255                // Then allow connecting to the singleton provider
9256                singleton = isSingleton(cpi.processName, cpi.applicationInfo,
9257                        cpi.name, cpi.flags)
9258                        && isValidSingletonCall(r.uid, cpi.applicationInfo.uid);
9259                if (singleton) {
9260                    userId = UserHandle.USER_OWNER;
9261                }
9262                cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
9263                checkTime(startTime, "getContentProviderImpl: got app info for user");
9264
9265                String msg;
9266                checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
9267                if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton))
9268                        != null) {
9269                    throw new SecurityException(msg);
9270                }
9271                checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission");
9272
9273                if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
9274                        && !cpi.processName.equals("system")) {
9275                    // If this content provider does not run in the system
9276                    // process, and the system is not yet ready to run other
9277                    // processes, then fail fast instead of hanging.
9278                    throw new IllegalArgumentException(
9279                            "Attempt to launch content provider before system ready");
9280                }
9281
9282                // Make sure that the user who owns this provider is started.  If not,
9283                // we don't want to allow it to run.
9284                if (mStartedUsers.get(userId) == null) {
9285                    Slog.w(TAG, "Unable to launch app "
9286                            + cpi.applicationInfo.packageName + "/"
9287                            + cpi.applicationInfo.uid + " for provider "
9288                            + name + ": user " + userId + " is stopped");
9289                    return null;
9290                }
9291
9292                ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
9293                checkTime(startTime, "getContentProviderImpl: before getProviderByClass");
9294                cpr = mProviderMap.getProviderByClass(comp, userId);
9295                checkTime(startTime, "getContentProviderImpl: after getProviderByClass");
9296                final boolean firstClass = cpr == null;
9297                if (firstClass) {
9298                    try {
9299                        checkTime(startTime, "getContentProviderImpl: before getApplicationInfo");
9300                        ApplicationInfo ai =
9301                            AppGlobals.getPackageManager().
9302                                getApplicationInfo(
9303                                        cpi.applicationInfo.packageName,
9304                                        STOCK_PM_FLAGS, userId);
9305                        checkTime(startTime, "getContentProviderImpl: after getApplicationInfo");
9306                        if (ai == null) {
9307                            Slog.w(TAG, "No package info for content provider "
9308                                    + cpi.name);
9309                            return null;
9310                        }
9311                        ai = getAppInfoForUser(ai, userId);
9312                        cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
9313                    } catch (RemoteException ex) {
9314                        // pm is in same process, this will never happen.
9315                    }
9316                }
9317
9318                checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord");
9319
9320                if (r != null && cpr.canRunHere(r)) {
9321                    // If this is a multiprocess provider, then just return its
9322                    // info and allow the caller to instantiate it.  Only do
9323                    // this if the provider is the same user as the caller's
9324                    // process, or can run as root (so can be in any process).
9325                    return cpr.newHolder(null);
9326                }
9327
9328                if (DEBUG_PROVIDER) {
9329                    RuntimeException e = new RuntimeException("here");
9330                    Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + (r != null ? r.uid : null)
9331                          + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
9332                }
9333
9334                // This is single process, and our app is now connecting to it.
9335                // See if we are already in the process of launching this
9336                // provider.
9337                final int N = mLaunchingProviders.size();
9338                int i;
9339                for (i=0; i<N; i++) {
9340                    if (mLaunchingProviders.get(i) == cpr) {
9341                        break;
9342                    }
9343                }
9344
9345                // If the provider is not already being launched, then get it
9346                // started.
9347                if (i >= N) {
9348                    final long origId = Binder.clearCallingIdentity();
9349
9350                    try {
9351                        // Content provider is now in use, its package can't be stopped.
9352                        try {
9353                            checkTime(startTime, "getContentProviderImpl: before set stopped state");
9354                            AppGlobals.getPackageManager().setPackageStoppedState(
9355                                    cpr.appInfo.packageName, false, userId);
9356                            checkTime(startTime, "getContentProviderImpl: after set stopped state");
9357                        } catch (RemoteException e) {
9358                        } catch (IllegalArgumentException e) {
9359                            Slog.w(TAG, "Failed trying to unstop package "
9360                                    + cpr.appInfo.packageName + ": " + e);
9361                        }
9362
9363                        // Use existing process if already started
9364                        checkTime(startTime, "getContentProviderImpl: looking for process record");
9365                        ProcessRecord proc = getProcessRecordLocked(
9366                                cpi.processName, cpr.appInfo.uid, false);
9367                        if (proc != null && proc.thread != null) {
9368                            if (DEBUG_PROVIDER) {
9369                                Slog.d(TAG, "Installing in existing process " + proc);
9370                            }
9371                            checkTime(startTime, "getContentProviderImpl: scheduling install");
9372                            proc.pubProviders.put(cpi.name, cpr);
9373                            try {
9374                                proc.thread.scheduleInstallProvider(cpi);
9375                            } catch (RemoteException e) {
9376                            }
9377                        } else {
9378                            checkTime(startTime, "getContentProviderImpl: before start process");
9379                            proc = startProcessLocked(cpi.processName,
9380                                    cpr.appInfo, false, 0, "content provider",
9381                                    new ComponentName(cpi.applicationInfo.packageName,
9382                                            cpi.name), false, false, false);
9383                            checkTime(startTime, "getContentProviderImpl: after start process");
9384                            if (proc == null) {
9385                                Slog.w(TAG, "Unable to launch app "
9386                                        + cpi.applicationInfo.packageName + "/"
9387                                        + cpi.applicationInfo.uid + " for provider "
9388                                        + name + ": process is bad");
9389                                return null;
9390                            }
9391                        }
9392                        cpr.launchingApp = proc;
9393                        mLaunchingProviders.add(cpr);
9394                    } finally {
9395                        Binder.restoreCallingIdentity(origId);
9396                    }
9397                }
9398
9399                checkTime(startTime, "getContentProviderImpl: updating data structures");
9400
9401                // Make sure the provider is published (the same provider class
9402                // may be published under multiple names).
9403                if (firstClass) {
9404                    mProviderMap.putProviderByClass(comp, cpr);
9405                }
9406
9407                mProviderMap.putProviderByName(name, cpr);
9408                conn = incProviderCountLocked(r, cpr, token, stable);
9409                if (conn != null) {
9410                    conn.waiting = true;
9411                }
9412            }
9413            checkTime(startTime, "getContentProviderImpl: done!");
9414        }
9415
9416        // Wait for the provider to be published...
9417        synchronized (cpr) {
9418            while (cpr.provider == null) {
9419                if (cpr.launchingApp == null) {
9420                    Slog.w(TAG, "Unable to launch app "
9421                            + cpi.applicationInfo.packageName + "/"
9422                            + cpi.applicationInfo.uid + " for provider "
9423                            + name + ": launching app became null");
9424                    EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
9425                            UserHandle.getUserId(cpi.applicationInfo.uid),
9426                            cpi.applicationInfo.packageName,
9427                            cpi.applicationInfo.uid, name);
9428                    return null;
9429                }
9430                try {
9431                    if (DEBUG_MU) {
9432                        Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
9433                                + cpr.launchingApp);
9434                    }
9435                    if (conn != null) {
9436                        conn.waiting = true;
9437                    }
9438                    cpr.wait();
9439                } catch (InterruptedException ex) {
9440                } finally {
9441                    if (conn != null) {
9442                        conn.waiting = false;
9443                    }
9444                }
9445            }
9446        }
9447        return cpr != null ? cpr.newHolder(conn) : null;
9448    }
9449
9450    @Override
9451    public final ContentProviderHolder getContentProvider(
9452            IApplicationThread caller, String name, int userId, boolean stable) {
9453        enforceNotIsolatedCaller("getContentProvider");
9454        if (caller == null) {
9455            String msg = "null IApplicationThread when getting content provider "
9456                    + name;
9457            Slog.w(TAG, msg);
9458            throw new SecurityException(msg);
9459        }
9460        // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal
9461        // with cross-user grant.
9462        return getContentProviderImpl(caller, name, null, stable, userId);
9463    }
9464
9465    public ContentProviderHolder getContentProviderExternal(
9466            String name, int userId, IBinder token) {
9467        enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
9468            "Do not have permission in call getContentProviderExternal()");
9469        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
9470                false, ALLOW_FULL_ONLY, "getContentProvider", null);
9471        return getContentProviderExternalUnchecked(name, token, userId);
9472    }
9473
9474    private ContentProviderHolder getContentProviderExternalUnchecked(String name,
9475            IBinder token, int userId) {
9476        return getContentProviderImpl(null, name, token, true, userId);
9477    }
9478
9479    /**
9480     * Drop a content provider from a ProcessRecord's bookkeeping
9481     */
9482    public void removeContentProvider(IBinder connection, boolean stable) {
9483        enforceNotIsolatedCaller("removeContentProvider");
9484        long ident = Binder.clearCallingIdentity();
9485        try {
9486            synchronized (this) {
9487                ContentProviderConnection conn;
9488                try {
9489                    conn = (ContentProviderConnection)connection;
9490                } catch (ClassCastException e) {
9491                    String msg ="removeContentProvider: " + connection
9492                            + " not a ContentProviderConnection";
9493                    Slog.w(TAG, msg);
9494                    throw new IllegalArgumentException(msg);
9495                }
9496                if (conn == null) {
9497                    throw new NullPointerException("connection is null");
9498                }
9499                if (decProviderCountLocked(conn, null, null, stable)) {
9500                    updateOomAdjLocked();
9501                }
9502            }
9503        } finally {
9504            Binder.restoreCallingIdentity(ident);
9505        }
9506    }
9507
9508    public void removeContentProviderExternal(String name, IBinder token) {
9509        enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
9510            "Do not have permission in call removeContentProviderExternal()");
9511        removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
9512    }
9513
9514    private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
9515        synchronized (this) {
9516            ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
9517            if(cpr == null) {
9518                //remove from mProvidersByClass
9519                if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
9520                return;
9521            }
9522
9523            //update content provider record entry info
9524            ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
9525            ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
9526            if (localCpr.hasExternalProcessHandles()) {
9527                if (localCpr.removeExternalProcessHandleLocked(token)) {
9528                    updateOomAdjLocked();
9529                } else {
9530                    Slog.e(TAG, "Attmpt to remove content provider " + localCpr
9531                            + " with no external reference for token: "
9532                            + token + ".");
9533                }
9534            } else {
9535                Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
9536                        + " with no external references.");
9537            }
9538        }
9539    }
9540
9541    public final void publishContentProviders(IApplicationThread caller,
9542            List<ContentProviderHolder> providers) {
9543        if (providers == null) {
9544            return;
9545        }
9546
9547        enforceNotIsolatedCaller("publishContentProviders");
9548        synchronized (this) {
9549            final ProcessRecord r = getRecordForAppLocked(caller);
9550            if (DEBUG_MU)
9551                Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
9552            if (r == null) {
9553                throw new SecurityException(
9554                        "Unable to find app for caller " + caller
9555                      + " (pid=" + Binder.getCallingPid()
9556                      + ") when publishing content providers");
9557            }
9558
9559            final long origId = Binder.clearCallingIdentity();
9560
9561            final int N = providers.size();
9562            for (int i=0; i<N; i++) {
9563                ContentProviderHolder src = providers.get(i);
9564                if (src == null || src.info == null || src.provider == null) {
9565                    continue;
9566                }
9567                ContentProviderRecord dst = r.pubProviders.get(src.info.name);
9568                if (DEBUG_MU)
9569                    Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
9570                if (dst != null) {
9571                    ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
9572                    mProviderMap.putProviderByClass(comp, dst);
9573                    String names[] = dst.info.authority.split(";");
9574                    for (int j = 0; j < names.length; j++) {
9575                        mProviderMap.putProviderByName(names[j], dst);
9576                    }
9577
9578                    int NL = mLaunchingProviders.size();
9579                    int j;
9580                    for (j=0; j<NL; j++) {
9581                        if (mLaunchingProviders.get(j) == dst) {
9582                            mLaunchingProviders.remove(j);
9583                            j--;
9584                            NL--;
9585                        }
9586                    }
9587                    synchronized (dst) {
9588                        dst.provider = src.provider;
9589                        dst.proc = r;
9590                        dst.notifyAll();
9591                    }
9592                    updateOomAdjLocked(r);
9593                }
9594            }
9595
9596            Binder.restoreCallingIdentity(origId);
9597        }
9598    }
9599
9600    public boolean refContentProvider(IBinder connection, int stable, int unstable) {
9601        ContentProviderConnection conn;
9602        try {
9603            conn = (ContentProviderConnection)connection;
9604        } catch (ClassCastException e) {
9605            String msg ="refContentProvider: " + connection
9606                    + " not a ContentProviderConnection";
9607            Slog.w(TAG, msg);
9608            throw new IllegalArgumentException(msg);
9609        }
9610        if (conn == null) {
9611            throw new NullPointerException("connection is null");
9612        }
9613
9614        synchronized (this) {
9615            if (stable > 0) {
9616                conn.numStableIncs += stable;
9617            }
9618            stable = conn.stableCount + stable;
9619            if (stable < 0) {
9620                throw new IllegalStateException("stableCount < 0: " + stable);
9621            }
9622
9623            if (unstable > 0) {
9624                conn.numUnstableIncs += unstable;
9625            }
9626            unstable = conn.unstableCount + unstable;
9627            if (unstable < 0) {
9628                throw new IllegalStateException("unstableCount < 0: " + unstable);
9629            }
9630
9631            if ((stable+unstable) <= 0) {
9632                throw new IllegalStateException("ref counts can't go to zero here: stable="
9633                        + stable + " unstable=" + unstable);
9634            }
9635            conn.stableCount = stable;
9636            conn.unstableCount = unstable;
9637            return !conn.dead;
9638        }
9639    }
9640
9641    public void unstableProviderDied(IBinder connection) {
9642        ContentProviderConnection conn;
9643        try {
9644            conn = (ContentProviderConnection)connection;
9645        } catch (ClassCastException e) {
9646            String msg ="refContentProvider: " + connection
9647                    + " not a ContentProviderConnection";
9648            Slog.w(TAG, msg);
9649            throw new IllegalArgumentException(msg);
9650        }
9651        if (conn == null) {
9652            throw new NullPointerException("connection is null");
9653        }
9654
9655        // Safely retrieve the content provider associated with the connection.
9656        IContentProvider provider;
9657        synchronized (this) {
9658            provider = conn.provider.provider;
9659        }
9660
9661        if (provider == null) {
9662            // Um, yeah, we're way ahead of you.
9663            return;
9664        }
9665
9666        // Make sure the caller is being honest with us.
9667        if (provider.asBinder().pingBinder()) {
9668            // Er, no, still looks good to us.
9669            synchronized (this) {
9670                Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
9671                        + " says " + conn + " died, but we don't agree");
9672                return;
9673            }
9674        }
9675
9676        // Well look at that!  It's dead!
9677        synchronized (this) {
9678            if (conn.provider.provider != provider) {
9679                // But something changed...  good enough.
9680                return;
9681            }
9682
9683            ProcessRecord proc = conn.provider.proc;
9684            if (proc == null || proc.thread == null) {
9685                // Seems like the process is already cleaned up.
9686                return;
9687            }
9688
9689            // As far as we're concerned, this is just like receiving a
9690            // death notification...  just a bit prematurely.
9691            Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
9692                    + ") early provider death");
9693            final long ident = Binder.clearCallingIdentity();
9694            try {
9695                appDiedLocked(proc);
9696            } finally {
9697                Binder.restoreCallingIdentity(ident);
9698            }
9699        }
9700    }
9701
9702    @Override
9703    public void appNotRespondingViaProvider(IBinder connection) {
9704        enforceCallingPermission(
9705                android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()");
9706
9707        final ContentProviderConnection conn = (ContentProviderConnection) connection;
9708        if (conn == null) {
9709            Slog.w(TAG, "ContentProviderConnection is null");
9710            return;
9711        }
9712
9713        final ProcessRecord host = conn.provider.proc;
9714        if (host == null) {
9715            Slog.w(TAG, "Failed to find hosting ProcessRecord");
9716            return;
9717        }
9718
9719        final long token = Binder.clearCallingIdentity();
9720        try {
9721            appNotResponding(host, null, null, false, "ContentProvider not responding");
9722        } finally {
9723            Binder.restoreCallingIdentity(token);
9724        }
9725    }
9726
9727    public final void installSystemProviders() {
9728        List<ProviderInfo> providers;
9729        synchronized (this) {
9730            ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID);
9731            providers = generateApplicationProvidersLocked(app);
9732            if (providers != null) {
9733                for (int i=providers.size()-1; i>=0; i--) {
9734                    ProviderInfo pi = (ProviderInfo)providers.get(i);
9735                    if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9736                        Slog.w(TAG, "Not installing system proc provider " + pi.name
9737                                + ": not system .apk");
9738                        providers.remove(i);
9739                    }
9740                }
9741            }
9742        }
9743        if (providers != null) {
9744            mSystemThread.installSystemProviders(providers);
9745        }
9746
9747        mCoreSettingsObserver = new CoreSettingsObserver(this);
9748
9749        //mUsageStatsService.monitorPackages();
9750    }
9751
9752    /**
9753     * Allows apps to retrieve the MIME type of a URI.
9754     * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
9755     * users, then it does not need permission to access the ContentProvider.
9756     * Either, it needs cross-user uri grants.
9757     *
9758     * CTS tests for this functionality can be run with "runtest cts-appsecurity".
9759     *
9760     * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
9761     *     src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
9762     */
9763    public String getProviderMimeType(Uri uri, int userId) {
9764        enforceNotIsolatedCaller("getProviderMimeType");
9765        final String name = uri.getAuthority();
9766        int callingUid = Binder.getCallingUid();
9767        int callingPid = Binder.getCallingPid();
9768        long ident = 0;
9769        boolean clearedIdentity = false;
9770        userId = unsafeConvertIncomingUser(userId);
9771        if (canClearIdentity(callingPid, callingUid, userId)) {
9772            clearedIdentity = true;
9773            ident = Binder.clearCallingIdentity();
9774        }
9775        ContentProviderHolder holder = null;
9776        try {
9777            holder = getContentProviderExternalUnchecked(name, null, userId);
9778            if (holder != null) {
9779                return holder.provider.getType(uri);
9780            }
9781        } catch (RemoteException e) {
9782            Log.w(TAG, "Content provider dead retrieving " + uri, e);
9783            return null;
9784        } finally {
9785            // We need to clear the identity to call removeContentProviderExternalUnchecked
9786            if (!clearedIdentity) {
9787                ident = Binder.clearCallingIdentity();
9788            }
9789            try {
9790                if (holder != null) {
9791                    removeContentProviderExternalUnchecked(name, null, userId);
9792                }
9793            } finally {
9794                Binder.restoreCallingIdentity(ident);
9795            }
9796        }
9797
9798        return null;
9799    }
9800
9801    private boolean canClearIdentity(int callingPid, int callingUid, int userId) {
9802        if (UserHandle.getUserId(callingUid) == userId) {
9803            return true;
9804        }
9805        if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
9806                callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
9807                || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
9808                callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
9809                return true;
9810        }
9811        return false;
9812    }
9813
9814    // =========================================================
9815    // GLOBAL MANAGEMENT
9816    // =========================================================
9817
9818    final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess,
9819            boolean isolated, int isolatedUid) {
9820        String proc = customProcess != null ? customProcess : info.processName;
9821        BatteryStatsImpl.Uid.Proc ps = null;
9822        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
9823        int uid = info.uid;
9824        if (isolated) {
9825            if (isolatedUid == 0) {
9826                int userId = UserHandle.getUserId(uid);
9827                int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
9828                while (true) {
9829                    if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
9830                            || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
9831                        mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
9832                    }
9833                    uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
9834                    mNextIsolatedProcessUid++;
9835                    if (mIsolatedProcesses.indexOfKey(uid) < 0) {
9836                        // No process for this uid, use it.
9837                        break;
9838                    }
9839                    stepsLeft--;
9840                    if (stepsLeft <= 0) {
9841                        return null;
9842                    }
9843                }
9844            } else {
9845                // Special case for startIsolatedProcess (internal only), where
9846                // the uid of the isolated process is specified by the caller.
9847                uid = isolatedUid;
9848            }
9849        }
9850        return new ProcessRecord(stats, info, proc, uid);
9851    }
9852
9853    final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated,
9854            String abiOverride) {
9855        ProcessRecord app;
9856        if (!isolated) {
9857            app = getProcessRecordLocked(info.processName, info.uid, true);
9858        } else {
9859            app = null;
9860        }
9861
9862        if (app == null) {
9863            app = newProcessRecordLocked(info, null, isolated, 0);
9864            mProcessNames.put(info.processName, app.uid, app);
9865            if (isolated) {
9866                mIsolatedProcesses.put(app.uid, app);
9867            }
9868            updateLruProcessLocked(app, false, null);
9869            updateOomAdjLocked();
9870        }
9871
9872        // This package really, really can not be stopped.
9873        try {
9874            AppGlobals.getPackageManager().setPackageStoppedState(
9875                    info.packageName, false, UserHandle.getUserId(app.uid));
9876        } catch (RemoteException e) {
9877        } catch (IllegalArgumentException e) {
9878            Slog.w(TAG, "Failed trying to unstop package "
9879                    + info.packageName + ": " + e);
9880        }
9881
9882        if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
9883                == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
9884            app.persistent = true;
9885            app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
9886        }
9887        if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
9888            mPersistentStartingProcesses.add(app);
9889            startProcessLocked(app, "added application", app.processName, abiOverride,
9890                    null /* entryPoint */, null /* entryPointArgs */);
9891        }
9892
9893        return app;
9894    }
9895
9896    public void unhandledBack() {
9897        enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
9898                "unhandledBack()");
9899
9900        synchronized(this) {
9901            final long origId = Binder.clearCallingIdentity();
9902            try {
9903                getFocusedStack().unhandledBackLocked();
9904            } finally {
9905                Binder.restoreCallingIdentity(origId);
9906            }
9907        }
9908    }
9909
9910    public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
9911        enforceNotIsolatedCaller("openContentUri");
9912        final int userId = UserHandle.getCallingUserId();
9913        String name = uri.getAuthority();
9914        ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
9915        ParcelFileDescriptor pfd = null;
9916        if (cph != null) {
9917            // We record the binder invoker's uid in thread-local storage before
9918            // going to the content provider to open the file.  Later, in the code
9919            // that handles all permissions checks, we look for this uid and use
9920            // that rather than the Activity Manager's own uid.  The effect is that
9921            // we do the check against the caller's permissions even though it looks
9922            // to the content provider like the Activity Manager itself is making
9923            // the request.
9924            sCallerIdentity.set(new Identity(
9925                    Binder.getCallingPid(), Binder.getCallingUid()));
9926            try {
9927                pfd = cph.provider.openFile(null, uri, "r", null);
9928            } catch (FileNotFoundException e) {
9929                // do nothing; pfd will be returned null
9930            } finally {
9931                // Ensure that whatever happens, we clean up the identity state
9932                sCallerIdentity.remove();
9933            }
9934
9935            // We've got the fd now, so we're done with the provider.
9936            removeContentProviderExternalUnchecked(name, null, userId);
9937        } else {
9938            Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
9939        }
9940        return pfd;
9941    }
9942
9943    // Actually is sleeping or shutting down or whatever else in the future
9944    // is an inactive state.
9945    public boolean isSleepingOrShuttingDown() {
9946        return isSleeping() || mShuttingDown;
9947    }
9948
9949    public boolean isSleeping() {
9950        return mSleeping && !mKeyguardWaitingForDraw;
9951    }
9952
9953    void goingToSleep() {
9954        synchronized(this) {
9955            mWentToSleep = true;
9956            updateEventDispatchingLocked();
9957            goToSleepIfNeededLocked();
9958        }
9959    }
9960
9961    void finishRunningVoiceLocked() {
9962        if (mRunningVoice) {
9963            mRunningVoice = false;
9964            goToSleepIfNeededLocked();
9965        }
9966    }
9967
9968    void goToSleepIfNeededLocked() {
9969        if (mWentToSleep && !mRunningVoice) {
9970            if (!mSleeping) {
9971                mSleeping = true;
9972                mKeyguardWaitingForDraw = false;
9973                mStackSupervisor.goingToSleepLocked();
9974
9975                // Initialize the wake times of all processes.
9976                checkExcessivePowerUsageLocked(false);
9977                mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
9978                Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
9979                mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
9980            }
9981        }
9982    }
9983
9984    void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
9985        if (task != null && task.stack != null && task.stack.isHomeStack()) {
9986            // Never persist the home stack.
9987            return;
9988        }
9989        mTaskPersister.wakeup(task, flush);
9990    }
9991
9992    @Override
9993    public boolean shutdown(int timeout) {
9994        if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
9995                != PackageManager.PERMISSION_GRANTED) {
9996            throw new SecurityException("Requires permission "
9997                    + android.Manifest.permission.SHUTDOWN);
9998        }
9999
10000        boolean timedout = false;
10001
10002        synchronized(this) {
10003            mShuttingDown = true;
10004            updateEventDispatchingLocked();
10005            timedout = mStackSupervisor.shutdownLocked(timeout);
10006        }
10007
10008        mAppOpsService.shutdown();
10009        if (mUsageStatsService != null) {
10010            mUsageStatsService.prepareShutdown();
10011        }
10012        mBatteryStatsService.shutdown();
10013        synchronized (this) {
10014            mProcessStats.shutdownLocked();
10015        }
10016        notifyTaskPersisterLocked(null, true);
10017
10018        return timedout;
10019    }
10020
10021    public final void activitySlept(IBinder token) {
10022        if (localLOGV) Slog.v(TAG, "Activity slept: token=" + token);
10023
10024        final long origId = Binder.clearCallingIdentity();
10025
10026        synchronized (this) {
10027            final ActivityRecord r = ActivityRecord.isInStackLocked(token);
10028            if (r != null) {
10029                mStackSupervisor.activitySleptLocked(r);
10030            }
10031        }
10032
10033        Binder.restoreCallingIdentity(origId);
10034    }
10035
10036    void logLockScreen(String msg) {
10037        if (DEBUG_LOCKSCREEN) Slog.d(TAG, Debug.getCallers(2) + ":" + msg +
10038                " mLockScreenShown=" + mLockScreenShown + " mWentToSleep=" +
10039                mWentToSleep + " mSleeping=" + mSleeping);
10040    }
10041
10042    private void comeOutOfSleepIfNeededLocked() {
10043        if ((!mWentToSleep && !mLockScreenShown) || mRunningVoice) {
10044            if (mSleeping) {
10045                mSleeping = false;
10046                mStackSupervisor.comeOutOfSleepIfNeededLocked();
10047            }
10048        }
10049    }
10050
10051    void wakingUp() {
10052        synchronized(this) {
10053            mWentToSleep = false;
10054            updateEventDispatchingLocked();
10055            comeOutOfSleepIfNeededLocked();
10056        }
10057    }
10058
10059    void startRunningVoiceLocked() {
10060        if (!mRunningVoice) {
10061            mRunningVoice = true;
10062            comeOutOfSleepIfNeededLocked();
10063        }
10064    }
10065
10066    private void updateEventDispatchingLocked() {
10067        mWindowManager.setEventDispatching(mBooted && !mShuttingDown);
10068    }
10069
10070    public void setLockScreenShown(boolean shown) {
10071        if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
10072                != PackageManager.PERMISSION_GRANTED) {
10073            throw new SecurityException("Requires permission "
10074                    + android.Manifest.permission.DEVICE_POWER);
10075        }
10076
10077        synchronized(this) {
10078            long ident = Binder.clearCallingIdentity();
10079            try {
10080                if (DEBUG_LOCKSCREEN) logLockScreen(" shown=" + shown);
10081                mLockScreenShown = shown;
10082                mKeyguardWaitingForDraw = false;
10083                comeOutOfSleepIfNeededLocked();
10084            } finally {
10085                Binder.restoreCallingIdentity(ident);
10086            }
10087        }
10088    }
10089
10090    @Override
10091    public void stopAppSwitches() {
10092        if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
10093                != PackageManager.PERMISSION_GRANTED) {
10094            throw new SecurityException("Requires permission "
10095                    + android.Manifest.permission.STOP_APP_SWITCHES);
10096        }
10097
10098        synchronized(this) {
10099            mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
10100                    + APP_SWITCH_DELAY_TIME;
10101            mDidAppSwitch = false;
10102            mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
10103            Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
10104            mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
10105        }
10106    }
10107
10108    public void resumeAppSwitches() {
10109        if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
10110                != PackageManager.PERMISSION_GRANTED) {
10111            throw new SecurityException("Requires permission "
10112                    + android.Manifest.permission.STOP_APP_SWITCHES);
10113        }
10114
10115        synchronized(this) {
10116            // Note that we don't execute any pending app switches... we will
10117            // let those wait until either the timeout, or the next start
10118            // activity request.
10119            mAppSwitchesAllowedTime = 0;
10120        }
10121    }
10122
10123    boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
10124            int callingPid, int callingUid, String name) {
10125        if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
10126            return true;
10127        }
10128
10129        int perm = checkComponentPermission(
10130                android.Manifest.permission.STOP_APP_SWITCHES, sourcePid,
10131                sourceUid, -1, true);
10132        if (perm == PackageManager.PERMISSION_GRANTED) {
10133            return true;
10134        }
10135
10136        // If the actual IPC caller is different from the logical source, then
10137        // also see if they are allowed to control app switches.
10138        if (callingUid != -1 && callingUid != sourceUid) {
10139            perm = checkComponentPermission(
10140                    android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
10141                    callingUid, -1, true);
10142            if (perm == PackageManager.PERMISSION_GRANTED) {
10143                return true;
10144            }
10145        }
10146
10147        Slog.w(TAG, name + " request from " + sourceUid + " stopped");
10148        return false;
10149    }
10150
10151    public void setDebugApp(String packageName, boolean waitForDebugger,
10152            boolean persistent) {
10153        enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
10154                "setDebugApp()");
10155
10156        long ident = Binder.clearCallingIdentity();
10157        try {
10158            // Note that this is not really thread safe if there are multiple
10159            // callers into it at the same time, but that's not a situation we
10160            // care about.
10161            if (persistent) {
10162                final ContentResolver resolver = mContext.getContentResolver();
10163                Settings.Global.putString(
10164                    resolver, Settings.Global.DEBUG_APP,
10165                    packageName);
10166                Settings.Global.putInt(
10167                    resolver, Settings.Global.WAIT_FOR_DEBUGGER,
10168                    waitForDebugger ? 1 : 0);
10169            }
10170
10171            synchronized (this) {
10172                if (!persistent) {
10173                    mOrigDebugApp = mDebugApp;
10174                    mOrigWaitForDebugger = mWaitForDebugger;
10175                }
10176                mDebugApp = packageName;
10177                mWaitForDebugger = waitForDebugger;
10178                mDebugTransient = !persistent;
10179                if (packageName != null) {
10180                    forceStopPackageLocked(packageName, -1, false, false, true, true,
10181                            false, UserHandle.USER_ALL, "set debug app");
10182                }
10183            }
10184        } finally {
10185            Binder.restoreCallingIdentity(ident);
10186        }
10187    }
10188
10189    void setOpenGlTraceApp(ApplicationInfo app, String processName) {
10190        synchronized (this) {
10191            boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
10192            if (!isDebuggable) {
10193                if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
10194                    throw new SecurityException("Process not debuggable: " + app.packageName);
10195                }
10196            }
10197
10198            mOpenGlTraceApp = processName;
10199        }
10200    }
10201
10202    void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) {
10203        synchronized (this) {
10204            boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
10205            if (!isDebuggable) {
10206                if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
10207                    throw new SecurityException("Process not debuggable: " + app.packageName);
10208                }
10209            }
10210            mProfileApp = processName;
10211            mProfileFile = profilerInfo.profileFile;
10212            if (mProfileFd != null) {
10213                try {
10214                    mProfileFd.close();
10215                } catch (IOException e) {
10216                }
10217                mProfileFd = null;
10218            }
10219            mProfileFd = profilerInfo.profileFd;
10220            mSamplingInterval = profilerInfo.samplingInterval;
10221            mAutoStopProfiler = profilerInfo.autoStopProfiler;
10222            mProfileType = 0;
10223        }
10224    }
10225
10226    @Override
10227    public void setAlwaysFinish(boolean enabled) {
10228        enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
10229                "setAlwaysFinish()");
10230
10231        Settings.Global.putInt(
10232                mContext.getContentResolver(),
10233                Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
10234
10235        synchronized (this) {
10236            mAlwaysFinishActivities = enabled;
10237        }
10238    }
10239
10240    @Override
10241    public void setActivityController(IActivityController controller) {
10242        enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
10243                "setActivityController()");
10244        synchronized (this) {
10245            mController = controller;
10246            Watchdog.getInstance().setActivityController(controller);
10247        }
10248    }
10249
10250    @Override
10251    public void setUserIsMonkey(boolean userIsMonkey) {
10252        synchronized (this) {
10253            synchronized (mPidsSelfLocked) {
10254                final int callingPid = Binder.getCallingPid();
10255                ProcessRecord precessRecord = mPidsSelfLocked.get(callingPid);
10256                if (precessRecord == null) {
10257                    throw new SecurityException("Unknown process: " + callingPid);
10258                }
10259                if (precessRecord.instrumentationUiAutomationConnection  == null) {
10260                    throw new SecurityException("Only an instrumentation process "
10261                            + "with a UiAutomation can call setUserIsMonkey");
10262                }
10263            }
10264            mUserIsMonkey = userIsMonkey;
10265        }
10266    }
10267
10268    @Override
10269    public boolean isUserAMonkey() {
10270        synchronized (this) {
10271            // If there is a controller also implies the user is a monkey.
10272            return (mUserIsMonkey || mController != null);
10273        }
10274    }
10275
10276    public void requestBugReport() {
10277        enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
10278        SystemProperties.set("ctl.start", "bugreport");
10279    }
10280
10281    public static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
10282        return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT;
10283    }
10284
10285    public static long getInputDispatchingTimeoutLocked(ProcessRecord r) {
10286        if (r != null && (r.instrumentationClass != null || r.usingWrapper)) {
10287            return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
10288        }
10289        return KEY_DISPATCHING_TIMEOUT;
10290    }
10291
10292    @Override
10293    public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
10294        if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
10295                != PackageManager.PERMISSION_GRANTED) {
10296            throw new SecurityException("Requires permission "
10297                    + android.Manifest.permission.FILTER_EVENTS);
10298        }
10299        ProcessRecord proc;
10300        long timeout;
10301        synchronized (this) {
10302            synchronized (mPidsSelfLocked) {
10303                proc = mPidsSelfLocked.get(pid);
10304            }
10305            timeout = getInputDispatchingTimeoutLocked(proc);
10306        }
10307
10308        if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) {
10309            return -1;
10310        }
10311
10312        return timeout;
10313    }
10314
10315    /**
10316     * Handle input dispatching timeouts.
10317     * Returns whether input dispatching should be aborted or not.
10318     */
10319    public boolean inputDispatchingTimedOut(final ProcessRecord proc,
10320            final ActivityRecord activity, final ActivityRecord parent,
10321            final boolean aboveSystem, String reason) {
10322        if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
10323                != PackageManager.PERMISSION_GRANTED) {
10324            throw new SecurityException("Requires permission "
10325                    + android.Manifest.permission.FILTER_EVENTS);
10326        }
10327
10328        final String annotation;
10329        if (reason == null) {
10330            annotation = "Input dispatching timed out";
10331        } else {
10332            annotation = "Input dispatching timed out (" + reason + ")";
10333        }
10334
10335        if (proc != null) {
10336            synchronized (this) {
10337                if (proc.debugging) {
10338                    return false;
10339                }
10340
10341                if (mDidDexOpt) {
10342                    // Give more time since we were dexopting.
10343                    mDidDexOpt = false;
10344                    return false;
10345                }
10346
10347                if (proc.instrumentationClass != null) {
10348                    Bundle info = new Bundle();
10349                    info.putString("shortMsg", "keyDispatchingTimedOut");
10350                    info.putString("longMsg", annotation);
10351                    finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
10352                    return true;
10353                }
10354            }
10355            mHandler.post(new Runnable() {
10356                @Override
10357                public void run() {
10358                    appNotResponding(proc, activity, parent, aboveSystem, annotation);
10359                }
10360            });
10361        }
10362
10363        return true;
10364    }
10365
10366    public Bundle getAssistContextExtras(int requestType) {
10367        enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
10368                "getAssistContextExtras()");
10369        PendingAssistExtras pae;
10370        Bundle extras = new Bundle();
10371        synchronized (this) {
10372            ActivityRecord activity = getFocusedStack().mResumedActivity;
10373            if (activity == null) {
10374                Slog.w(TAG, "getAssistContextExtras failed: no resumed activity");
10375                return null;
10376            }
10377            extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
10378            if (activity.app == null || activity.app.thread == null) {
10379                Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
10380                return extras;
10381            }
10382            if (activity.app.pid == Binder.getCallingPid()) {
10383                Slog.w(TAG, "getAssistContextExtras failed: request process same as " + activity);
10384                return extras;
10385            }
10386            pae = new PendingAssistExtras(activity);
10387            try {
10388                activity.app.thread.requestAssistContextExtras(activity.appToken, pae,
10389                        requestType);
10390                mPendingAssistExtras.add(pae);
10391                mHandler.postDelayed(pae, PENDING_ASSIST_EXTRAS_TIMEOUT);
10392            } catch (RemoteException e) {
10393                Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
10394                return extras;
10395            }
10396        }
10397        synchronized (pae) {
10398            while (!pae.haveResult) {
10399                try {
10400                    pae.wait();
10401                } catch (InterruptedException e) {
10402                }
10403            }
10404            if (pae.result != null) {
10405                extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
10406            }
10407        }
10408        synchronized (this) {
10409            mPendingAssistExtras.remove(pae);
10410            mHandler.removeCallbacks(pae);
10411        }
10412        return extras;
10413    }
10414
10415    public void reportAssistContextExtras(IBinder token, Bundle extras) {
10416        PendingAssistExtras pae = (PendingAssistExtras)token;
10417        synchronized (pae) {
10418            pae.result = extras;
10419            pae.haveResult = true;
10420            pae.notifyAll();
10421        }
10422    }
10423
10424    public void registerProcessObserver(IProcessObserver observer) {
10425        enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
10426                "registerProcessObserver()");
10427        synchronized (this) {
10428            mProcessObservers.register(observer);
10429        }
10430    }
10431
10432    @Override
10433    public void unregisterProcessObserver(IProcessObserver observer) {
10434        synchronized (this) {
10435            mProcessObservers.unregister(observer);
10436        }
10437    }
10438
10439    @Override
10440    public boolean convertFromTranslucent(IBinder token) {
10441        final long origId = Binder.clearCallingIdentity();
10442        try {
10443            synchronized (this) {
10444                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
10445                if (r == null) {
10446                    return false;
10447                }
10448                final boolean translucentChanged = r.changeWindowTranslucency(true);
10449                if (translucentChanged) {
10450                    r.task.stack.releaseBackgroundResources();
10451                    mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
10452                }
10453                mWindowManager.setAppFullscreen(token, true);
10454                return translucentChanged;
10455            }
10456        } finally {
10457            Binder.restoreCallingIdentity(origId);
10458        }
10459    }
10460
10461    @Override
10462    public boolean convertToTranslucent(IBinder token, ActivityOptions options) {
10463        final long origId = Binder.clearCallingIdentity();
10464        try {
10465            synchronized (this) {
10466                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
10467                if (r == null) {
10468                    return false;
10469                }
10470                int index = r.task.mActivities.lastIndexOf(r);
10471                if (index > 0) {
10472                    ActivityRecord under = r.task.mActivities.get(index - 1);
10473                    under.returningOptions = options;
10474                }
10475                final boolean translucentChanged = r.changeWindowTranslucency(false);
10476                if (translucentChanged) {
10477                    r.task.stack.convertToTranslucent(r);
10478                }
10479                mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
10480                mWindowManager.setAppFullscreen(token, false);
10481                return translucentChanged;
10482            }
10483        } finally {
10484            Binder.restoreCallingIdentity(origId);
10485        }
10486    }
10487
10488    @Override
10489    public boolean requestVisibleBehind(IBinder token, boolean visible) {
10490        final long origId = Binder.clearCallingIdentity();
10491        try {
10492            synchronized (this) {
10493                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
10494                if (r != null) {
10495                    return mStackSupervisor.requestVisibleBehindLocked(r, visible);
10496                }
10497            }
10498            return false;
10499        } finally {
10500            Binder.restoreCallingIdentity(origId);
10501        }
10502    }
10503
10504    @Override
10505    public boolean isBackgroundVisibleBehind(IBinder token) {
10506        final long origId = Binder.clearCallingIdentity();
10507        try {
10508            synchronized (this) {
10509                final ActivityStack stack = ActivityRecord.getStackLocked(token);
10510                final boolean visible = stack == null ? false : stack.hasVisibleBehindActivity();
10511                if (ActivityStackSupervisor.DEBUG_VISIBLE_BEHIND) Slog.d(TAG,
10512                        "isBackgroundVisibleBehind: stack=" + stack + " visible=" + visible);
10513                return visible;
10514            }
10515        } finally {
10516            Binder.restoreCallingIdentity(origId);
10517        }
10518    }
10519
10520    @Override
10521    public ActivityOptions getActivityOptions(IBinder token) {
10522        final long origId = Binder.clearCallingIdentity();
10523        try {
10524            synchronized (this) {
10525                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
10526                if (r != null) {
10527                    final ActivityOptions activityOptions = r.pendingOptions;
10528                    r.pendingOptions = null;
10529                    return activityOptions;
10530                }
10531                return null;
10532            }
10533        } finally {
10534            Binder.restoreCallingIdentity(origId);
10535        }
10536    }
10537
10538    @Override
10539    public void setImmersive(IBinder token, boolean immersive) {
10540        synchronized(this) {
10541            final ActivityRecord r = ActivityRecord.isInStackLocked(token);
10542            if (r == null) {
10543                throw new IllegalArgumentException();
10544            }
10545            r.immersive = immersive;
10546
10547            // update associated state if we're frontmost
10548            if (r == mFocusedActivity) {
10549                if (DEBUG_IMMERSIVE) {
10550                    Slog.d(TAG, "Frontmost changed immersion: "+ r);
10551                }
10552                applyUpdateLockStateLocked(r);
10553            }
10554        }
10555    }
10556
10557    @Override
10558    public boolean isImmersive(IBinder token) {
10559        synchronized (this) {
10560            ActivityRecord r = ActivityRecord.isInStackLocked(token);
10561            if (r == null) {
10562                throw new IllegalArgumentException();
10563            }
10564            return r.immersive;
10565        }
10566    }
10567
10568    public boolean isTopActivityImmersive() {
10569        enforceNotIsolatedCaller("startActivity");
10570        synchronized (this) {
10571            ActivityRecord r = getFocusedStack().topRunningActivityLocked(null);
10572            return (r != null) ? r.immersive : false;
10573        }
10574    }
10575
10576    @Override
10577    public boolean isTopOfTask(IBinder token) {
10578        synchronized (this) {
10579            ActivityRecord r = ActivityRecord.isInStackLocked(token);
10580            if (r == null) {
10581                throw new IllegalArgumentException();
10582            }
10583            return r.task.getTopActivity() == r;
10584        }
10585    }
10586
10587    public final void enterSafeMode() {
10588        synchronized(this) {
10589            // It only makes sense to do this before the system is ready
10590            // and started launching other packages.
10591            if (!mSystemReady) {
10592                try {
10593                    AppGlobals.getPackageManager().enterSafeMode();
10594                } catch (RemoteException e) {
10595                }
10596            }
10597
10598            mSafeMode = true;
10599        }
10600    }
10601
10602    public final void showSafeModeOverlay() {
10603        View v = LayoutInflater.from(mContext).inflate(
10604                com.android.internal.R.layout.safe_mode, null);
10605        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
10606        lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
10607        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
10608        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
10609        lp.gravity = Gravity.BOTTOM | Gravity.START;
10610        lp.format = v.getBackground().getOpacity();
10611        lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
10612                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
10613        lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
10614        ((WindowManager)mContext.getSystemService(
10615                Context.WINDOW_SERVICE)).addView(v, lp);
10616    }
10617
10618    public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg) {
10619        if (!(sender instanceof PendingIntentRecord)) {
10620            return;
10621        }
10622        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10623        synchronized (stats) {
10624            if (mBatteryStatsService.isOnBattery()) {
10625                mBatteryStatsService.enforceCallingPermission();
10626                PendingIntentRecord rec = (PendingIntentRecord)sender;
10627                int MY_UID = Binder.getCallingUid();
10628                int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
10629                BatteryStatsImpl.Uid.Pkg pkg =
10630                    stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid,
10631                            sourcePkg != null ? sourcePkg : rec.key.packageName);
10632                pkg.incWakeupsLocked();
10633            }
10634        }
10635    }
10636
10637    public boolean killPids(int[] pids, String pReason, boolean secure) {
10638        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
10639            throw new SecurityException("killPids only available to the system");
10640        }
10641        String reason = (pReason == null) ? "Unknown" : pReason;
10642        // XXX Note: don't acquire main activity lock here, because the window
10643        // manager calls in with its locks held.
10644
10645        boolean killed = false;
10646        synchronized (mPidsSelfLocked) {
10647            int[] types = new int[pids.length];
10648            int worstType = 0;
10649            for (int i=0; i<pids.length; i++) {
10650                ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
10651                if (proc != null) {
10652                    int type = proc.setAdj;
10653                    types[i] = type;
10654                    if (type > worstType) {
10655                        worstType = type;
10656                    }
10657                }
10658            }
10659
10660            // If the worst oom_adj is somewhere in the cached proc LRU range,
10661            // then constrain it so we will kill all cached procs.
10662            if (worstType < ProcessList.CACHED_APP_MAX_ADJ
10663                    && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
10664                worstType = ProcessList.CACHED_APP_MIN_ADJ;
10665            }
10666
10667            // If this is not a secure call, don't let it kill processes that
10668            // are important.
10669            if (!secure && worstType < ProcessList.SERVICE_ADJ) {
10670                worstType = ProcessList.SERVICE_ADJ;
10671            }
10672
10673            Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
10674            for (int i=0; i<pids.length; i++) {
10675                ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
10676                if (proc == null) {
10677                    continue;
10678                }
10679                int adj = proc.setAdj;
10680                if (adj >= worstType && !proc.killedByAm) {
10681                    proc.kill(reason, true);
10682                    killed = true;
10683                }
10684            }
10685        }
10686        return killed;
10687    }
10688
10689    @Override
10690    public void killUid(int uid, String reason) {
10691        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
10692            throw new SecurityException("killUid only available to the system");
10693        }
10694        synchronized (this) {
10695            killPackageProcessesLocked(null, UserHandle.getAppId(uid), UserHandle.getUserId(uid),
10696                    ProcessList.FOREGROUND_APP_ADJ-1, false, true, true, false,
10697                    reason != null ? reason : "kill uid");
10698        }
10699    }
10700
10701    @Override
10702    public boolean killProcessesBelowForeground(String reason) {
10703        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
10704            throw new SecurityException("killProcessesBelowForeground() only available to system");
10705        }
10706
10707        return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
10708    }
10709
10710    private boolean killProcessesBelowAdj(int belowAdj, String reason) {
10711        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
10712            throw new SecurityException("killProcessesBelowAdj() only available to system");
10713        }
10714
10715        boolean killed = false;
10716        synchronized (mPidsSelfLocked) {
10717            final int size = mPidsSelfLocked.size();
10718            for (int i = 0; i < size; i++) {
10719                final int pid = mPidsSelfLocked.keyAt(i);
10720                final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
10721                if (proc == null) continue;
10722
10723                final int adj = proc.setAdj;
10724                if (adj > belowAdj && !proc.killedByAm) {
10725                    proc.kill(reason, true);
10726                    killed = true;
10727                }
10728            }
10729        }
10730        return killed;
10731    }
10732
10733    @Override
10734    public void hang(final IBinder who, boolean allowRestart) {
10735        if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
10736                != PackageManager.PERMISSION_GRANTED) {
10737            throw new SecurityException("Requires permission "
10738                    + android.Manifest.permission.SET_ACTIVITY_WATCHER);
10739        }
10740
10741        final IBinder.DeathRecipient death = new DeathRecipient() {
10742            @Override
10743            public void binderDied() {
10744                synchronized (this) {
10745                    notifyAll();
10746                }
10747            }
10748        };
10749
10750        try {
10751            who.linkToDeath(death, 0);
10752        } catch (RemoteException e) {
10753            Slog.w(TAG, "hang: given caller IBinder is already dead.");
10754            return;
10755        }
10756
10757        synchronized (this) {
10758            Watchdog.getInstance().setAllowRestart(allowRestart);
10759            Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
10760            synchronized (death) {
10761                while (who.isBinderAlive()) {
10762                    try {
10763                        death.wait();
10764                    } catch (InterruptedException e) {
10765                    }
10766                }
10767            }
10768            Watchdog.getInstance().setAllowRestart(true);
10769        }
10770    }
10771
10772    @Override
10773    public void restart() {
10774        if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
10775                != PackageManager.PERMISSION_GRANTED) {
10776            throw new SecurityException("Requires permission "
10777                    + android.Manifest.permission.SET_ACTIVITY_WATCHER);
10778        }
10779
10780        Log.i(TAG, "Sending shutdown broadcast...");
10781
10782        BroadcastReceiver br = new BroadcastReceiver() {
10783            @Override public void onReceive(Context context, Intent intent) {
10784                // Now the broadcast is done, finish up the low-level shutdown.
10785                Log.i(TAG, "Shutting down activity manager...");
10786                shutdown(10000);
10787                Log.i(TAG, "Shutdown complete, restarting!");
10788                Process.killProcess(Process.myPid());
10789                System.exit(10);
10790            }
10791        };
10792
10793        // First send the high-level shut down broadcast.
10794        Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
10795        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10796        intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
10797        /* For now we are not doing a clean shutdown, because things seem to get unhappy.
10798        mContext.sendOrderedBroadcastAsUser(intent,
10799                UserHandle.ALL, null, br, mHandler, 0, null, null);
10800        */
10801        br.onReceive(mContext, intent);
10802    }
10803
10804    private long getLowRamTimeSinceIdle(long now) {
10805        return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0);
10806    }
10807
10808    @Override
10809    public void performIdleMaintenance() {
10810        if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
10811                != PackageManager.PERMISSION_GRANTED) {
10812            throw new SecurityException("Requires permission "
10813                    + android.Manifest.permission.SET_ACTIVITY_WATCHER);
10814        }
10815
10816        synchronized (this) {
10817            final long now = SystemClock.uptimeMillis();
10818            final long timeSinceLastIdle = now - mLastIdleTime;
10819            final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now);
10820            mLastIdleTime = now;
10821            mLowRamTimeSinceLastIdle = 0;
10822            if (mLowRamStartTime != 0) {
10823                mLowRamStartTime = now;
10824            }
10825
10826            StringBuilder sb = new StringBuilder(128);
10827            sb.append("Idle maintenance over ");
10828            TimeUtils.formatDuration(timeSinceLastIdle, sb);
10829            sb.append(" low RAM for ");
10830            TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
10831            Slog.i(TAG, sb.toString());
10832
10833            // If at least 1/3 of our time since the last idle period has been spent
10834            // with RAM low, then we want to kill processes.
10835            boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
10836
10837            for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
10838                ProcessRecord proc = mLruProcesses.get(i);
10839                if (proc.notCachedSinceIdle) {
10840                    if (proc.setProcState > ActivityManager.PROCESS_STATE_TOP
10841                            && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
10842                        if (doKilling && proc.initialIdlePss != 0
10843                                && proc.lastPss > ((proc.initialIdlePss*3)/2)) {
10844                            proc.kill("idle maint (pss " + proc.lastPss
10845                                    + " from " + proc.initialIdlePss + ")", true);
10846                        }
10847                    }
10848                } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME) {
10849                    proc.notCachedSinceIdle = true;
10850                    proc.initialIdlePss = 0;
10851                    proc.nextPssTime = ProcessList.computeNextPssTime(proc.curProcState, true,
10852                            isSleeping(), now);
10853                }
10854            }
10855
10856            mHandler.removeMessages(REQUEST_ALL_PSS_MSG);
10857            mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000);
10858        }
10859    }
10860
10861    private void retrieveSettings() {
10862        final ContentResolver resolver = mContext.getContentResolver();
10863        String debugApp = Settings.Global.getString(
10864            resolver, Settings.Global.DEBUG_APP);
10865        boolean waitForDebugger = Settings.Global.getInt(
10866            resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
10867        boolean alwaysFinishActivities = Settings.Global.getInt(
10868            resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
10869        boolean forceRtl = Settings.Global.getInt(
10870                resolver, Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0;
10871        // Transfer any global setting for forcing RTL layout, into a System Property
10872        SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
10873
10874        Configuration configuration = new Configuration();
10875        Settings.System.getConfiguration(resolver, configuration);
10876        if (forceRtl) {
10877            // This will take care of setting the correct layout direction flags
10878            configuration.setLayoutDirection(configuration.locale);
10879        }
10880
10881        synchronized (this) {
10882            mDebugApp = mOrigDebugApp = debugApp;
10883            mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
10884            mAlwaysFinishActivities = alwaysFinishActivities;
10885            // This happens before any activities are started, so we can
10886            // change mConfiguration in-place.
10887            updateConfigurationLocked(configuration, null, false, true);
10888            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
10889        }
10890    }
10891
10892    /** Loads resources after the current configuration has been set. */
10893    private void loadResourcesOnSystemReady() {
10894        final Resources res = mContext.getResources();
10895        mHasRecents = res.getBoolean(com.android.internal.R.bool.config_hasRecents);
10896        mThumbnailWidth = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
10897        mThumbnailHeight = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
10898    }
10899
10900    public boolean testIsSystemReady() {
10901        // no need to synchronize(this) just to read & return the value
10902        return mSystemReady;
10903    }
10904
10905    private static File getCalledPreBootReceiversFile() {
10906        File dataDir = Environment.getDataDirectory();
10907        File systemDir = new File(dataDir, "system");
10908        File fname = new File(systemDir, CALLED_PRE_BOOTS_FILENAME);
10909        return fname;
10910    }
10911
10912    private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
10913        ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
10914        File file = getCalledPreBootReceiversFile();
10915        FileInputStream fis = null;
10916        try {
10917            fis = new FileInputStream(file);
10918            DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
10919            int fvers = dis.readInt();
10920            if (fvers == LAST_PREBOOT_DELIVERED_FILE_VERSION) {
10921                String vers = dis.readUTF();
10922                String codename = dis.readUTF();
10923                String build = dis.readUTF();
10924                if (android.os.Build.VERSION.RELEASE.equals(vers)
10925                        && android.os.Build.VERSION.CODENAME.equals(codename)
10926                        && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
10927                    int num = dis.readInt();
10928                    while (num > 0) {
10929                        num--;
10930                        String pkg = dis.readUTF();
10931                        String cls = dis.readUTF();
10932                        lastDoneReceivers.add(new ComponentName(pkg, cls));
10933                    }
10934                }
10935            }
10936        } catch (FileNotFoundException e) {
10937        } catch (IOException e) {
10938            Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
10939        } finally {
10940            if (fis != null) {
10941                try {
10942                    fis.close();
10943                } catch (IOException e) {
10944                }
10945            }
10946        }
10947        return lastDoneReceivers;
10948    }
10949
10950    private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
10951        File file = getCalledPreBootReceiversFile();
10952        FileOutputStream fos = null;
10953        DataOutputStream dos = null;
10954        try {
10955            fos = new FileOutputStream(file);
10956            dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
10957            dos.writeInt(LAST_PREBOOT_DELIVERED_FILE_VERSION);
10958            dos.writeUTF(android.os.Build.VERSION.RELEASE);
10959            dos.writeUTF(android.os.Build.VERSION.CODENAME);
10960            dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
10961            dos.writeInt(list.size());
10962            for (int i=0; i<list.size(); i++) {
10963                dos.writeUTF(list.get(i).getPackageName());
10964                dos.writeUTF(list.get(i).getClassName());
10965            }
10966        } catch (IOException e) {
10967            Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
10968            file.delete();
10969        } finally {
10970            FileUtils.sync(fos);
10971            if (dos != null) {
10972                try {
10973                    dos.close();
10974                } catch (IOException e) {
10975                    // TODO Auto-generated catch block
10976                    e.printStackTrace();
10977                }
10978            }
10979        }
10980    }
10981
10982    private boolean deliverPreBootCompleted(final Runnable onFinishCallback,
10983            ArrayList<ComponentName> doneReceivers, int userId) {
10984        boolean waitingUpdate = false;
10985        Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
10986        List<ResolveInfo> ris = null;
10987        try {
10988            ris = AppGlobals.getPackageManager().queryIntentReceivers(
10989                    intent, null, 0, userId);
10990        } catch (RemoteException e) {
10991        }
10992        if (ris != null) {
10993            for (int i=ris.size()-1; i>=0; i--) {
10994                if ((ris.get(i).activityInfo.applicationInfo.flags
10995                        &ApplicationInfo.FLAG_SYSTEM) == 0) {
10996                    ris.remove(i);
10997                }
10998            }
10999            intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
11000
11001            // For User 0, load the version number. When delivering to a new user, deliver
11002            // to all receivers.
11003            if (userId == UserHandle.USER_OWNER) {
11004                ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
11005                for (int i=0; i<ris.size(); i++) {
11006                    ActivityInfo ai = ris.get(i).activityInfo;
11007                    ComponentName comp = new ComponentName(ai.packageName, ai.name);
11008                    if (lastDoneReceivers.contains(comp)) {
11009                        // We already did the pre boot receiver for this app with the current
11010                        // platform version, so don't do it again...
11011                        ris.remove(i);
11012                        i--;
11013                        // ...however, do keep it as one that has been done, so we don't
11014                        // forget about it when rewriting the file of last done receivers.
11015                        doneReceivers.add(comp);
11016                    }
11017                }
11018            }
11019
11020            // If primary user, send broadcast to all available users, else just to userId
11021            final int[] users = userId == UserHandle.USER_OWNER ? getUsersLocked()
11022                    : new int[] { userId };
11023            for (int i = 0; i < ris.size(); i++) {
11024                ActivityInfo ai = ris.get(i).activityInfo;
11025                ComponentName comp = new ComponentName(ai.packageName, ai.name);
11026                doneReceivers.add(comp);
11027                intent.setComponent(comp);
11028                for (int j=0; j<users.length; j++) {
11029                    IIntentReceiver finisher = null;
11030                    // On last receiver and user, set up a completion callback
11031                    if (i == ris.size() - 1 && j == users.length - 1 && onFinishCallback != null) {
11032                        finisher = new IIntentReceiver.Stub() {
11033                            public void performReceive(Intent intent, int resultCode,
11034                                    String data, Bundle extras, boolean ordered,
11035                                    boolean sticky, int sendingUser) {
11036                                // The raw IIntentReceiver interface is called
11037                                // with the AM lock held, so redispatch to
11038                                // execute our code without the lock.
11039                                mHandler.post(onFinishCallback);
11040                            }
11041                        };
11042                    }
11043                    Slog.i(TAG, "Sending system update to " + intent.getComponent()
11044                            + " for user " + users[j]);
11045                    broadcastIntentLocked(null, null, intent, null, finisher,
11046                            0, null, null, null, AppOpsManager.OP_NONE,
11047                            true, false, MY_PID, Process.SYSTEM_UID,
11048                            users[j]);
11049                    if (finisher != null) {
11050                        waitingUpdate = true;
11051                    }
11052                }
11053            }
11054        }
11055
11056        return waitingUpdate;
11057    }
11058
11059    public void systemReady(final Runnable goingCallback) {
11060        synchronized(this) {
11061            if (mSystemReady) {
11062                // If we're done calling all the receivers, run the next "boot phase" passed in
11063                // by the SystemServer
11064                if (goingCallback != null) {
11065                    goingCallback.run();
11066                }
11067                return;
11068            }
11069
11070            // Make sure we have the current profile info, since it is needed for
11071            // security checks.
11072            updateCurrentProfileIdsLocked();
11073
11074            if (mRecentTasks == null) {
11075                mRecentTasks = mTaskPersister.restoreTasksLocked();
11076                if (!mRecentTasks.isEmpty()) {
11077                    mStackSupervisor.createStackForRestoredTaskHistory(mRecentTasks);
11078                }
11079                cleanupRecentTasksLocked(UserHandle.USER_ALL);
11080                mTaskPersister.startPersisting();
11081            }
11082
11083            // Check to see if there are any update receivers to run.
11084            if (!mDidUpdate) {
11085                if (mWaitingUpdate) {
11086                    return;
11087                }
11088                final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
11089                mWaitingUpdate = deliverPreBootCompleted(new Runnable() {
11090                    public void run() {
11091                        synchronized (ActivityManagerService.this) {
11092                            mDidUpdate = true;
11093                        }
11094                        writeLastDonePreBootReceivers(doneReceivers);
11095                        showBootMessage(mContext.getText(
11096                                R.string.android_upgrading_complete),
11097                                false);
11098                        systemReady(goingCallback);
11099                    }
11100                }, doneReceivers, UserHandle.USER_OWNER);
11101
11102                if (mWaitingUpdate) {
11103                    return;
11104                }
11105                mDidUpdate = true;
11106            }
11107
11108            mAppOpsService.systemReady();
11109            mSystemReady = true;
11110        }
11111
11112        ArrayList<ProcessRecord> procsToKill = null;
11113        synchronized(mPidsSelfLocked) {
11114            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
11115                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
11116                if (!isAllowedWhileBooting(proc.info)){
11117                    if (procsToKill == null) {
11118                        procsToKill = new ArrayList<ProcessRecord>();
11119                    }
11120                    procsToKill.add(proc);
11121                }
11122            }
11123        }
11124
11125        synchronized(this) {
11126            if (procsToKill != null) {
11127                for (int i=procsToKill.size()-1; i>=0; i--) {
11128                    ProcessRecord proc = procsToKill.get(i);
11129                    Slog.i(TAG, "Removing system update proc: " + proc);
11130                    removeProcessLocked(proc, true, false, "system update done");
11131                }
11132            }
11133
11134            // Now that we have cleaned up any update processes, we
11135            // are ready to start launching real processes and know that
11136            // we won't trample on them any more.
11137            mProcessesReady = true;
11138        }
11139
11140        Slog.i(TAG, "System now ready");
11141        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
11142            SystemClock.uptimeMillis());
11143
11144        synchronized(this) {
11145            // Make sure we have no pre-ready processes sitting around.
11146
11147            if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
11148                ResolveInfo ri = mContext.getPackageManager()
11149                        .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
11150                                STOCK_PM_FLAGS);
11151                CharSequence errorMsg = null;
11152                if (ri != null) {
11153                    ActivityInfo ai = ri.activityInfo;
11154                    ApplicationInfo app = ai.applicationInfo;
11155                    if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11156                        mTopAction = Intent.ACTION_FACTORY_TEST;
11157                        mTopData = null;
11158                        mTopComponent = new ComponentName(app.packageName,
11159                                ai.name);
11160                    } else {
11161                        errorMsg = mContext.getResources().getText(
11162                                com.android.internal.R.string.factorytest_not_system);
11163                    }
11164                } else {
11165                    errorMsg = mContext.getResources().getText(
11166                            com.android.internal.R.string.factorytest_no_action);
11167                }
11168                if (errorMsg != null) {
11169                    mTopAction = null;
11170                    mTopData = null;
11171                    mTopComponent = null;
11172                    Message msg = Message.obtain();
11173                    msg.what = SHOW_FACTORY_ERROR_MSG;
11174                    msg.getData().putCharSequence("msg", errorMsg);
11175                    mHandler.sendMessage(msg);
11176                }
11177            }
11178        }
11179
11180        retrieveSettings();
11181        loadResourcesOnSystemReady();
11182
11183        synchronized (this) {
11184            readGrantedUriPermissionsLocked();
11185        }
11186
11187        if (goingCallback != null) goingCallback.run();
11188
11189        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
11190                Integer.toString(mCurrentUserId), mCurrentUserId);
11191        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
11192                Integer.toString(mCurrentUserId), mCurrentUserId);
11193        mSystemServiceManager.startUser(mCurrentUserId);
11194
11195        synchronized (this) {
11196            if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
11197                try {
11198                    List apps = AppGlobals.getPackageManager().
11199                        getPersistentApplications(STOCK_PM_FLAGS);
11200                    if (apps != null) {
11201                        int N = apps.size();
11202                        int i;
11203                        for (i=0; i<N; i++) {
11204                            ApplicationInfo info
11205                                = (ApplicationInfo)apps.get(i);
11206                            if (info != null &&
11207                                    !info.packageName.equals("android")) {
11208                                addAppLocked(info, false, null /* ABI override */);
11209                            }
11210                        }
11211                    }
11212                } catch (RemoteException ex) {
11213                    // pm is in same process, this will never happen.
11214                }
11215            }
11216
11217            // Start up initial activity.
11218            mBooting = true;
11219
11220            try {
11221                if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
11222                    Message msg = Message.obtain();
11223                    msg.what = SHOW_UID_ERROR_MSG;
11224                    mHandler.sendMessage(msg);
11225                }
11226            } catch (RemoteException e) {
11227            }
11228
11229            long ident = Binder.clearCallingIdentity();
11230            try {
11231                Intent intent = new Intent(Intent.ACTION_USER_STARTED);
11232                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11233                        | Intent.FLAG_RECEIVER_FOREGROUND);
11234                intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
11235                broadcastIntentLocked(null, null, intent,
11236                        null, null, 0, null, null, null, AppOpsManager.OP_NONE,
11237                        false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
11238                intent = new Intent(Intent.ACTION_USER_STARTING);
11239                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11240                intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
11241                broadcastIntentLocked(null, null, intent,
11242                        null, new IIntentReceiver.Stub() {
11243                            @Override
11244                            public void performReceive(Intent intent, int resultCode, String data,
11245                                    Bundle extras, boolean ordered, boolean sticky, int sendingUser)
11246                                    throws RemoteException {
11247                            }
11248                        }, 0, null, null,
11249                        INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
11250                        true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
11251            } catch (Throwable t) {
11252                Slog.wtf(TAG, "Failed sending first user broadcasts", t);
11253            } finally {
11254                Binder.restoreCallingIdentity(ident);
11255            }
11256            mStackSupervisor.resumeTopActivitiesLocked();
11257            sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
11258        }
11259    }
11260
11261    private boolean makeAppCrashingLocked(ProcessRecord app,
11262            String shortMsg, String longMsg, String stackTrace) {
11263        app.crashing = true;
11264        app.crashingReport = generateProcessError(app,
11265                ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
11266        startAppProblemLocked(app);
11267        app.stopFreezingAllLocked();
11268        return handleAppCrashLocked(app, shortMsg, longMsg, stackTrace);
11269    }
11270
11271    private void makeAppNotRespondingLocked(ProcessRecord app,
11272            String activity, String shortMsg, String longMsg) {
11273        app.notResponding = true;
11274        app.notRespondingReport = generateProcessError(app,
11275                ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
11276                activity, shortMsg, longMsg, null);
11277        startAppProblemLocked(app);
11278        app.stopFreezingAllLocked();
11279    }
11280
11281    /**
11282     * Generate a process error record, suitable for attachment to a ProcessRecord.
11283     *
11284     * @param app The ProcessRecord in which the error occurred.
11285     * @param condition Crashing, Application Not Responding, etc.  Values are defined in
11286     *                      ActivityManager.AppErrorStateInfo
11287     * @param activity The activity associated with the crash, if known.
11288     * @param shortMsg Short message describing the crash.
11289     * @param longMsg Long message describing the crash.
11290     * @param stackTrace Full crash stack trace, may be null.
11291     *
11292     * @return Returns a fully-formed AppErrorStateInfo record.
11293     */
11294    private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
11295            int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
11296        ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
11297
11298        report.condition = condition;
11299        report.processName = app.processName;
11300        report.pid = app.pid;
11301        report.uid = app.info.uid;
11302        report.tag = activity;
11303        report.shortMsg = shortMsg;
11304        report.longMsg = longMsg;
11305        report.stackTrace = stackTrace;
11306
11307        return report;
11308    }
11309
11310    void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
11311        synchronized (this) {
11312            app.crashing = false;
11313            app.crashingReport = null;
11314            app.notResponding = false;
11315            app.notRespondingReport = null;
11316            if (app.anrDialog == fromDialog) {
11317                app.anrDialog = null;
11318            }
11319            if (app.waitDialog == fromDialog) {
11320                app.waitDialog = null;
11321            }
11322            if (app.pid > 0 && app.pid != MY_PID) {
11323                handleAppCrashLocked(app, null, null, null);
11324                app.kill("user request after error", true);
11325            }
11326        }
11327    }
11328
11329    private boolean handleAppCrashLocked(ProcessRecord app, String shortMsg, String longMsg,
11330            String stackTrace) {
11331        long now = SystemClock.uptimeMillis();
11332
11333        Long crashTime;
11334        if (!app.isolated) {
11335            crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
11336        } else {
11337            crashTime = null;
11338        }
11339        if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
11340            // This process loses!
11341            Slog.w(TAG, "Process " + app.info.processName
11342                    + " has crashed too many times: killing!");
11343            EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
11344                    app.userId, app.info.processName, app.uid);
11345            mStackSupervisor.handleAppCrashLocked(app);
11346            if (!app.persistent) {
11347                // We don't want to start this process again until the user
11348                // explicitly does so...  but for persistent process, we really
11349                // need to keep it running.  If a persistent process is actually
11350                // repeatedly crashing, then badness for everyone.
11351                EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
11352                        app.info.processName);
11353                if (!app.isolated) {
11354                    // XXX We don't have a way to mark isolated processes
11355                    // as bad, since they don't have a peristent identity.
11356                    mBadProcesses.put(app.info.processName, app.uid,
11357                            new BadProcessInfo(now, shortMsg, longMsg, stackTrace));
11358                    mProcessCrashTimes.remove(app.info.processName, app.uid);
11359                }
11360                app.bad = true;
11361                app.removed = true;
11362                // Don't let services in this process be restarted and potentially
11363                // annoy the user repeatedly.  Unless it is persistent, since those
11364                // processes run critical code.
11365                removeProcessLocked(app, false, false, "crash");
11366                mStackSupervisor.resumeTopActivitiesLocked();
11367                return false;
11368            }
11369            mStackSupervisor.resumeTopActivitiesLocked();
11370        } else {
11371            mStackSupervisor.finishTopRunningActivityLocked(app);
11372        }
11373
11374        // Bump up the crash count of any services currently running in the proc.
11375        for (int i=app.services.size()-1; i>=0; i--) {
11376            // Any services running in the application need to be placed
11377            // back in the pending list.
11378            ServiceRecord sr = app.services.valueAt(i);
11379            sr.crashCount++;
11380        }
11381
11382        // If the crashing process is what we consider to be the "home process" and it has been
11383        // replaced by a third-party app, clear the package preferred activities from packages
11384        // with a home activity running in the process to prevent a repeatedly crashing app
11385        // from blocking the user to manually clear the list.
11386        final ArrayList<ActivityRecord> activities = app.activities;
11387        if (app == mHomeProcess && activities.size() > 0
11388                    && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
11389            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
11390                final ActivityRecord r = activities.get(activityNdx);
11391                if (r.isHomeActivity()) {
11392                    Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
11393                    try {
11394                        ActivityThread.getPackageManager()
11395                                .clearPackagePreferredActivities(r.packageName);
11396                    } catch (RemoteException c) {
11397                        // pm is in same process, this will never happen.
11398                    }
11399                }
11400            }
11401        }
11402
11403        if (!app.isolated) {
11404            // XXX Can't keep track of crash times for isolated processes,
11405            // because they don't have a perisistent identity.
11406            mProcessCrashTimes.put(app.info.processName, app.uid, now);
11407        }
11408
11409        if (app.crashHandler != null) mHandler.post(app.crashHandler);
11410        return true;
11411    }
11412
11413    void startAppProblemLocked(ProcessRecord app) {
11414        // If this app is not running under the current user, then we
11415        // can't give it a report button because that would require
11416        // launching the report UI under a different user.
11417        app.errorReportReceiver = null;
11418
11419        for (int userId : mCurrentProfileIds) {
11420            if (app.userId == userId) {
11421                app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
11422                        mContext, app.info.packageName, app.info.flags);
11423            }
11424        }
11425        skipCurrentReceiverLocked(app);
11426    }
11427
11428    void skipCurrentReceiverLocked(ProcessRecord app) {
11429        for (BroadcastQueue queue : mBroadcastQueues) {
11430            queue.skipCurrentReceiverLocked(app);
11431        }
11432    }
11433
11434    /**
11435     * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
11436     * The application process will exit immediately after this call returns.
11437     * @param app object of the crashing app, null for the system server
11438     * @param crashInfo describing the exception
11439     */
11440    public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
11441        ProcessRecord r = findAppProcess(app, "Crash");
11442        final String processName = app == null ? "system_server"
11443                : (r == null ? "unknown" : r.processName);
11444
11445        handleApplicationCrashInner("crash", r, processName, crashInfo);
11446    }
11447
11448    /* Native crash reporting uses this inner version because it needs to be somewhat
11449     * decoupled from the AM-managed cleanup lifecycle
11450     */
11451    void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
11452            ApplicationErrorReport.CrashInfo crashInfo) {
11453        EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
11454                UserHandle.getUserId(Binder.getCallingUid()), processName,
11455                r == null ? -1 : r.info.flags,
11456                crashInfo.exceptionClassName,
11457                crashInfo.exceptionMessage,
11458                crashInfo.throwFileName,
11459                crashInfo.throwLineNumber);
11460
11461        addErrorToDropBox(eventType, r, processName, null, null, null, null, null, crashInfo);
11462
11463        crashApplication(r, crashInfo);
11464    }
11465
11466    public void handleApplicationStrictModeViolation(
11467            IBinder app,
11468            int violationMask,
11469            StrictMode.ViolationInfo info) {
11470        ProcessRecord r = findAppProcess(app, "StrictMode");
11471        if (r == null) {
11472            return;
11473        }
11474
11475        if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
11476            Integer stackFingerprint = info.hashCode();
11477            boolean logIt = true;
11478            synchronized (mAlreadyLoggedViolatedStacks) {
11479                if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
11480                    logIt = false;
11481                    // TODO: sub-sample into EventLog for these, with
11482                    // the info.durationMillis?  Then we'd get
11483                    // the relative pain numbers, without logging all
11484                    // the stack traces repeatedly.  We'd want to do
11485                    // likewise in the client code, which also does
11486                    // dup suppression, before the Binder call.
11487                } else {
11488                    if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
11489                        mAlreadyLoggedViolatedStacks.clear();
11490                    }
11491                    mAlreadyLoggedViolatedStacks.add(stackFingerprint);
11492                }
11493            }
11494            if (logIt) {
11495                logStrictModeViolationToDropBox(r, info);
11496            }
11497        }
11498
11499        if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
11500            AppErrorResult result = new AppErrorResult();
11501            synchronized (this) {
11502                final long origId = Binder.clearCallingIdentity();
11503
11504                Message msg = Message.obtain();
11505                msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
11506                HashMap<String, Object> data = new HashMap<String, Object>();
11507                data.put("result", result);
11508                data.put("app", r);
11509                data.put("violationMask", violationMask);
11510                data.put("info", info);
11511                msg.obj = data;
11512                mHandler.sendMessage(msg);
11513
11514                Binder.restoreCallingIdentity(origId);
11515            }
11516            int res = result.get();
11517            Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
11518        }
11519    }
11520
11521    // Depending on the policy in effect, there could be a bunch of
11522    // these in quick succession so we try to batch these together to
11523    // minimize disk writes, number of dropbox entries, and maximize
11524    // compression, by having more fewer, larger records.
11525    private void logStrictModeViolationToDropBox(
11526            ProcessRecord process,
11527            StrictMode.ViolationInfo info) {
11528        if (info == null) {
11529            return;
11530        }
11531        final boolean isSystemApp = process == null ||
11532                (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
11533                                       ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
11534        final String processName = process == null ? "unknown" : process.processName;
11535        final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
11536        final DropBoxManager dbox = (DropBoxManager)
11537                mContext.getSystemService(Context.DROPBOX_SERVICE);
11538
11539        // Exit early if the dropbox isn't configured to accept this report type.
11540        if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
11541
11542        boolean bufferWasEmpty;
11543        boolean needsFlush;
11544        final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
11545        synchronized (sb) {
11546            bufferWasEmpty = sb.length() == 0;
11547            appendDropBoxProcessHeaders(process, processName, sb);
11548            sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
11549            sb.append("System-App: ").append(isSystemApp).append("\n");
11550            sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
11551            if (info.violationNumThisLoop != 0) {
11552                sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
11553            }
11554            if (info.numAnimationsRunning != 0) {
11555                sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
11556            }
11557            if (info.broadcastIntentAction != null) {
11558                sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
11559            }
11560            if (info.durationMillis != -1) {
11561                sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
11562            }
11563            if (info.numInstances != -1) {
11564                sb.append("Instance-Count: ").append(info.numInstances).append("\n");
11565            }
11566            if (info.tags != null) {
11567                for (String tag : info.tags) {
11568                    sb.append("Span-Tag: ").append(tag).append("\n");
11569                }
11570            }
11571            sb.append("\n");
11572            if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
11573                sb.append(info.crashInfo.stackTrace);
11574            }
11575            sb.append("\n");
11576
11577            // Only buffer up to ~64k.  Various logging bits truncate
11578            // things at 128k.
11579            needsFlush = (sb.length() > 64 * 1024);
11580        }
11581
11582        // Flush immediately if the buffer's grown too large, or this
11583        // is a non-system app.  Non-system apps are isolated with a
11584        // different tag & policy and not batched.
11585        //
11586        // Batching is useful during internal testing with
11587        // StrictMode settings turned up high.  Without batching,
11588        // thousands of separate files could be created on boot.
11589        if (!isSystemApp || needsFlush) {
11590            new Thread("Error dump: " + dropboxTag) {
11591                @Override
11592                public void run() {
11593                    String report;
11594                    synchronized (sb) {
11595                        report = sb.toString();
11596                        sb.delete(0, sb.length());
11597                        sb.trimToSize();
11598                    }
11599                    if (report.length() != 0) {
11600                        dbox.addText(dropboxTag, report);
11601                    }
11602                }
11603            }.start();
11604            return;
11605        }
11606
11607        // System app batching:
11608        if (!bufferWasEmpty) {
11609            // An existing dropbox-writing thread is outstanding, so
11610            // we don't need to start it up.  The existing thread will
11611            // catch the buffer appends we just did.
11612            return;
11613        }
11614
11615        // Worker thread to both batch writes and to avoid blocking the caller on I/O.
11616        // (After this point, we shouldn't access AMS internal data structures.)
11617        new Thread("Error dump: " + dropboxTag) {
11618            @Override
11619            public void run() {
11620                // 5 second sleep to let stacks arrive and be batched together
11621                try {
11622                    Thread.sleep(5000);  // 5 seconds
11623                } catch (InterruptedException e) {}
11624
11625                String errorReport;
11626                synchronized (mStrictModeBuffer) {
11627                    errorReport = mStrictModeBuffer.toString();
11628                    if (errorReport.length() == 0) {
11629                        return;
11630                    }
11631                    mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
11632                    mStrictModeBuffer.trimToSize();
11633                }
11634                dbox.addText(dropboxTag, errorReport);
11635            }
11636        }.start();
11637    }
11638
11639    /**
11640     * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
11641     * @param app object of the crashing app, null for the system server
11642     * @param tag reported by the caller
11643     * @param system whether this wtf is coming from the system
11644     * @param crashInfo describing the context of the error
11645     * @return true if the process should exit immediately (WTF is fatal)
11646     */
11647    public boolean handleApplicationWtf(IBinder app, final String tag, boolean system,
11648            final ApplicationErrorReport.CrashInfo crashInfo) {
11649        final ProcessRecord r = findAppProcess(app, "WTF");
11650        final String processName = app == null ? "system_server"
11651                : (r == null ? "unknown" : r.processName);
11652
11653        EventLog.writeEvent(EventLogTags.AM_WTF,
11654                UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
11655                processName,
11656                r == null ? -1 : r.info.flags,
11657                tag, crashInfo.exceptionMessage);
11658
11659        if (system) {
11660            // If this is coming from the system, we could very well have low-level
11661            // system locks held, so we want to do this all asynchronously.  And we
11662            // never want this to become fatal, so there is that too.
11663            mHandler.post(new Runnable() {
11664                @Override public void run() {
11665                    addErrorToDropBox("wtf", r, processName, null, null, tag, null, null,
11666                            crashInfo);
11667                }
11668            });
11669            return false;
11670        }
11671
11672        addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
11673
11674        if (r != null && r.pid != Process.myPid() &&
11675                Settings.Global.getInt(mContext.getContentResolver(),
11676                        Settings.Global.WTF_IS_FATAL, 0) != 0) {
11677            crashApplication(r, crashInfo);
11678            return true;
11679        } else {
11680            return false;
11681        }
11682    }
11683
11684    /**
11685     * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
11686     * @return the corresponding {@link ProcessRecord} object, or null if none could be found
11687     */
11688    private ProcessRecord findAppProcess(IBinder app, String reason) {
11689        if (app == null) {
11690            return null;
11691        }
11692
11693        synchronized (this) {
11694            final int NP = mProcessNames.getMap().size();
11695            for (int ip=0; ip<NP; ip++) {
11696                SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
11697                final int NA = apps.size();
11698                for (int ia=0; ia<NA; ia++) {
11699                    ProcessRecord p = apps.valueAt(ia);
11700                    if (p.thread != null && p.thread.asBinder() == app) {
11701                        return p;
11702                    }
11703                }
11704            }
11705
11706            Slog.w(TAG, "Can't find mystery application for " + reason
11707                    + " from pid=" + Binder.getCallingPid()
11708                    + " uid=" + Binder.getCallingUid() + ": " + app);
11709            return null;
11710        }
11711    }
11712
11713    /**
11714     * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
11715     * to append various headers to the dropbox log text.
11716     */
11717    private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
11718            StringBuilder sb) {
11719        // Watchdog thread ends up invoking this function (with
11720        // a null ProcessRecord) to add the stack file to dropbox.
11721        // Do not acquire a lock on this (am) in such cases, as it
11722        // could cause a potential deadlock, if and when watchdog
11723        // is invoked due to unavailability of lock on am and it
11724        // would prevent watchdog from killing system_server.
11725        if (process == null) {
11726            sb.append("Process: ").append(processName).append("\n");
11727            return;
11728        }
11729        // Note: ProcessRecord 'process' is guarded by the service
11730        // instance.  (notably process.pkgList, which could otherwise change
11731        // concurrently during execution of this method)
11732        synchronized (this) {
11733            sb.append("Process: ").append(processName).append("\n");
11734            int flags = process.info.flags;
11735            IPackageManager pm = AppGlobals.getPackageManager();
11736            sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
11737            for (int ip=0; ip<process.pkgList.size(); ip++) {
11738                String pkg = process.pkgList.keyAt(ip);
11739                sb.append("Package: ").append(pkg);
11740                try {
11741                    PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
11742                    if (pi != null) {
11743                        sb.append(" v").append(pi.versionCode);
11744                        if (pi.versionName != null) {
11745                            sb.append(" (").append(pi.versionName).append(")");
11746                        }
11747                    }
11748                } catch (RemoteException e) {
11749                    Slog.e(TAG, "Error getting package info: " + pkg, e);
11750                }
11751                sb.append("\n");
11752            }
11753        }
11754    }
11755
11756    private static String processClass(ProcessRecord process) {
11757        if (process == null || process.pid == MY_PID) {
11758            return "system_server";
11759        } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11760            return "system_app";
11761        } else {
11762            return "data_app";
11763        }
11764    }
11765
11766    /**
11767     * Write a description of an error (crash, WTF, ANR) to the drop box.
11768     * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
11769     * @param process which caused the error, null means the system server
11770     * @param activity which triggered the error, null if unknown
11771     * @param parent activity related to the error, null if unknown
11772     * @param subject line related to the error, null if absent
11773     * @param report in long form describing the error, null if absent
11774     * @param logFile to include in the report, null if none
11775     * @param crashInfo giving an application stack trace, null if absent
11776     */
11777    public void addErrorToDropBox(String eventType,
11778            ProcessRecord process, String processName, ActivityRecord activity,
11779            ActivityRecord parent, String subject,
11780            final String report, final File logFile,
11781            final ApplicationErrorReport.CrashInfo crashInfo) {
11782        // NOTE -- this must never acquire the ActivityManagerService lock,
11783        // otherwise the watchdog may be prevented from resetting the system.
11784
11785        final String dropboxTag = processClass(process) + "_" + eventType;
11786        final DropBoxManager dbox = (DropBoxManager)
11787                mContext.getSystemService(Context.DROPBOX_SERVICE);
11788
11789        // Exit early if the dropbox isn't configured to accept this report type.
11790        if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
11791
11792        final StringBuilder sb = new StringBuilder(1024);
11793        appendDropBoxProcessHeaders(process, processName, sb);
11794        if (activity != null) {
11795            sb.append("Activity: ").append(activity.shortComponentName).append("\n");
11796        }
11797        if (parent != null && parent.app != null && parent.app.pid != process.pid) {
11798            sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
11799        }
11800        if (parent != null && parent != activity) {
11801            sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
11802        }
11803        if (subject != null) {
11804            sb.append("Subject: ").append(subject).append("\n");
11805        }
11806        sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
11807        if (Debug.isDebuggerConnected()) {
11808            sb.append("Debugger: Connected\n");
11809        }
11810        sb.append("\n");
11811
11812        // Do the rest in a worker thread to avoid blocking the caller on I/O
11813        // (After this point, we shouldn't access AMS internal data structures.)
11814        Thread worker = new Thread("Error dump: " + dropboxTag) {
11815            @Override
11816            public void run() {
11817                if (report != null) {
11818                    sb.append(report);
11819                }
11820                if (logFile != null) {
11821                    try {
11822                        sb.append(FileUtils.readTextFile(logFile, DROPBOX_MAX_SIZE,
11823                                    "\n\n[[TRUNCATED]]"));
11824                    } catch (IOException e) {
11825                        Slog.e(TAG, "Error reading " + logFile, e);
11826                    }
11827                }
11828                if (crashInfo != null && crashInfo.stackTrace != null) {
11829                    sb.append(crashInfo.stackTrace);
11830                }
11831
11832                String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
11833                int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
11834                if (lines > 0) {
11835                    sb.append("\n");
11836
11837                    // Merge several logcat streams, and take the last N lines
11838                    InputStreamReader input = null;
11839                    try {
11840                        java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
11841                                "-v", "time", "-b", "events", "-b", "system", "-b", "main",
11842                                "-b", "crash",
11843                                "-t", String.valueOf(lines)).redirectErrorStream(true).start();
11844
11845                        try { logcat.getOutputStream().close(); } catch (IOException e) {}
11846                        try { logcat.getErrorStream().close(); } catch (IOException e) {}
11847                        input = new InputStreamReader(logcat.getInputStream());
11848
11849                        int num;
11850                        char[] buf = new char[8192];
11851                        while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
11852                    } catch (IOException e) {
11853                        Slog.e(TAG, "Error running logcat", e);
11854                    } finally {
11855                        if (input != null) try { input.close(); } catch (IOException e) {}
11856                    }
11857                }
11858
11859                dbox.addText(dropboxTag, sb.toString());
11860            }
11861        };
11862
11863        if (process == null) {
11864            // If process is null, we are being called from some internal code
11865            // and may be about to die -- run this synchronously.
11866            worker.run();
11867        } else {
11868            worker.start();
11869        }
11870    }
11871
11872    /**
11873     * Bring up the "unexpected error" dialog box for a crashing app.
11874     * Deal with edge cases (intercepts from instrumented applications,
11875     * ActivityController, error intent receivers, that sort of thing).
11876     * @param r the application crashing
11877     * @param crashInfo describing the failure
11878     */
11879    private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
11880        long timeMillis = System.currentTimeMillis();
11881        String shortMsg = crashInfo.exceptionClassName;
11882        String longMsg = crashInfo.exceptionMessage;
11883        String stackTrace = crashInfo.stackTrace;
11884        if (shortMsg != null && longMsg != null) {
11885            longMsg = shortMsg + ": " + longMsg;
11886        } else if (shortMsg != null) {
11887            longMsg = shortMsg;
11888        }
11889
11890        AppErrorResult result = new AppErrorResult();
11891        synchronized (this) {
11892            if (mController != null) {
11893                try {
11894                    String name = r != null ? r.processName : null;
11895                    int pid = r != null ? r.pid : Binder.getCallingPid();
11896                    int uid = r != null ? r.info.uid : Binder.getCallingUid();
11897                    if (!mController.appCrashed(name, pid,
11898                            shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
11899                        if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
11900                                && "Native crash".equals(crashInfo.exceptionClassName)) {
11901                            Slog.w(TAG, "Skip killing native crashed app " + name
11902                                    + "(" + pid + ") during testing");
11903                        } else {
11904                            Slog.w(TAG, "Force-killing crashed app " + name
11905                                    + " at watcher's request");
11906                            if (r != null) {
11907                                r.kill("crash", true);
11908                            } else {
11909                                // Huh.
11910                                Process.killProcess(pid);
11911                                Process.killProcessGroup(uid, pid);
11912                            }
11913                        }
11914                        return;
11915                    }
11916                } catch (RemoteException e) {
11917                    mController = null;
11918                    Watchdog.getInstance().setActivityController(null);
11919                }
11920            }
11921
11922            final long origId = Binder.clearCallingIdentity();
11923
11924            // If this process is running instrumentation, finish it.
11925            if (r != null && r.instrumentationClass != null) {
11926                Slog.w(TAG, "Error in app " + r.processName
11927                      + " running instrumentation " + r.instrumentationClass + ":");
11928                if (shortMsg != null) Slog.w(TAG, "  " + shortMsg);
11929                if (longMsg != null) Slog.w(TAG, "  " + longMsg);
11930                Bundle info = new Bundle();
11931                info.putString("shortMsg", shortMsg);
11932                info.putString("longMsg", longMsg);
11933                finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
11934                Binder.restoreCallingIdentity(origId);
11935                return;
11936            }
11937
11938            // If we can't identify the process or it's already exceeded its crash quota,
11939            // quit right away without showing a crash dialog.
11940            if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
11941                Binder.restoreCallingIdentity(origId);
11942                return;
11943            }
11944
11945            Message msg = Message.obtain();
11946            msg.what = SHOW_ERROR_MSG;
11947            HashMap data = new HashMap();
11948            data.put("result", result);
11949            data.put("app", r);
11950            msg.obj = data;
11951            mHandler.sendMessage(msg);
11952
11953            Binder.restoreCallingIdentity(origId);
11954        }
11955
11956        int res = result.get();
11957
11958        Intent appErrorIntent = null;
11959        synchronized (this) {
11960            if (r != null && !r.isolated) {
11961                // XXX Can't keep track of crash time for isolated processes,
11962                // since they don't have a persistent identity.
11963                mProcessCrashTimes.put(r.info.processName, r.uid,
11964                        SystemClock.uptimeMillis());
11965            }
11966            if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
11967                appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
11968            }
11969        }
11970
11971        if (appErrorIntent != null) {
11972            try {
11973                mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
11974            } catch (ActivityNotFoundException e) {
11975                Slog.w(TAG, "bug report receiver dissappeared", e);
11976            }
11977        }
11978    }
11979
11980    Intent createAppErrorIntentLocked(ProcessRecord r,
11981            long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
11982        ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
11983        if (report == null) {
11984            return null;
11985        }
11986        Intent result = new Intent(Intent.ACTION_APP_ERROR);
11987        result.setComponent(r.errorReportReceiver);
11988        result.putExtra(Intent.EXTRA_BUG_REPORT, report);
11989        result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
11990        return result;
11991    }
11992
11993    private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
11994            long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
11995        if (r.errorReportReceiver == null) {
11996            return null;
11997        }
11998
11999        if (!r.crashing && !r.notResponding && !r.forceCrashReport) {
12000            return null;
12001        }
12002
12003        ApplicationErrorReport report = new ApplicationErrorReport();
12004        report.packageName = r.info.packageName;
12005        report.installerPackageName = r.errorReportReceiver.getPackageName();
12006        report.processName = r.processName;
12007        report.time = timeMillis;
12008        report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12009
12010        if (r.crashing || r.forceCrashReport) {
12011            report.type = ApplicationErrorReport.TYPE_CRASH;
12012            report.crashInfo = crashInfo;
12013        } else if (r.notResponding) {
12014            report.type = ApplicationErrorReport.TYPE_ANR;
12015            report.anrInfo = new ApplicationErrorReport.AnrInfo();
12016
12017            report.anrInfo.activity = r.notRespondingReport.tag;
12018            report.anrInfo.cause = r.notRespondingReport.shortMsg;
12019            report.anrInfo.info = r.notRespondingReport.longMsg;
12020        }
12021
12022        return report;
12023    }
12024
12025    public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
12026        enforceNotIsolatedCaller("getProcessesInErrorState");
12027        // assume our apps are happy - lazy create the list
12028        List<ActivityManager.ProcessErrorStateInfo> errList = null;
12029
12030        final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
12031                Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
12032        int userId = UserHandle.getUserId(Binder.getCallingUid());
12033
12034        synchronized (this) {
12035
12036            // iterate across all processes
12037            for (int i=mLruProcesses.size()-1; i>=0; i--) {
12038                ProcessRecord app = mLruProcesses.get(i);
12039                if (!allUsers && app.userId != userId) {
12040                    continue;
12041                }
12042                if ((app.thread != null) && (app.crashing || app.notResponding)) {
12043                    // This one's in trouble, so we'll generate a report for it
12044                    // crashes are higher priority (in case there's a crash *and* an anr)
12045                    ActivityManager.ProcessErrorStateInfo report = null;
12046                    if (app.crashing) {
12047                        report = app.crashingReport;
12048                    } else if (app.notResponding) {
12049                        report = app.notRespondingReport;
12050                    }
12051
12052                    if (report != null) {
12053                        if (errList == null) {
12054                            errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
12055                        }
12056                        errList.add(report);
12057                    } else {
12058                        Slog.w(TAG, "Missing app error report, app = " + app.processName +
12059                                " crashing = " + app.crashing +
12060                                " notResponding = " + app.notResponding);
12061                    }
12062                }
12063            }
12064        }
12065
12066        return errList;
12067    }
12068
12069    static int procStateToImportance(int procState, int memAdj,
12070            ActivityManager.RunningAppProcessInfo currApp) {
12071        int imp = ActivityManager.RunningAppProcessInfo.procStateToImportance(procState);
12072        if (imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
12073            currApp.lru = memAdj;
12074        } else {
12075            currApp.lru = 0;
12076        }
12077        return imp;
12078    }
12079
12080    private void fillInProcMemInfo(ProcessRecord app,
12081            ActivityManager.RunningAppProcessInfo outInfo) {
12082        outInfo.pid = app.pid;
12083        outInfo.uid = app.info.uid;
12084        if (mHeavyWeightProcess == app) {
12085            outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
12086        }
12087        if (app.persistent) {
12088            outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
12089        }
12090        if (app.activities.size() > 0) {
12091            outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
12092        }
12093        outInfo.lastTrimLevel = app.trimMemoryLevel;
12094        int adj = app.curAdj;
12095        int procState = app.curProcState;
12096        outInfo.importance = procStateToImportance(procState, adj, outInfo);
12097        outInfo.importanceReasonCode = app.adjTypeCode;
12098        outInfo.processState = app.curProcState;
12099    }
12100
12101    public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
12102        enforceNotIsolatedCaller("getRunningAppProcesses");
12103        // Lazy instantiation of list
12104        List<ActivityManager.RunningAppProcessInfo> runList = null;
12105        final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
12106                Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
12107        int userId = UserHandle.getUserId(Binder.getCallingUid());
12108        synchronized (this) {
12109            // Iterate across all processes
12110            for (int i=mLruProcesses.size()-1; i>=0; i--) {
12111                ProcessRecord app = mLruProcesses.get(i);
12112                if (!allUsers && app.userId != userId) {
12113                    continue;
12114                }
12115                if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
12116                    // Generate process state info for running application
12117                    ActivityManager.RunningAppProcessInfo currApp =
12118                        new ActivityManager.RunningAppProcessInfo(app.processName,
12119                                app.pid, app.getPackageList());
12120                    fillInProcMemInfo(app, currApp);
12121                    if (app.adjSource instanceof ProcessRecord) {
12122                        currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
12123                        currApp.importanceReasonImportance =
12124                                ActivityManager.RunningAppProcessInfo.procStateToImportance(
12125                                        app.adjSourceProcState);
12126                    } else if (app.adjSource instanceof ActivityRecord) {
12127                        ActivityRecord r = (ActivityRecord)app.adjSource;
12128                        if (r.app != null) currApp.importanceReasonPid = r.app.pid;
12129                    }
12130                    if (app.adjTarget instanceof ComponentName) {
12131                        currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
12132                    }
12133                    //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
12134                    //        + " lru=" + currApp.lru);
12135                    if (runList == null) {
12136                        runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
12137                    }
12138                    runList.add(currApp);
12139                }
12140            }
12141        }
12142        return runList;
12143    }
12144
12145    public List<ApplicationInfo> getRunningExternalApplications() {
12146        enforceNotIsolatedCaller("getRunningExternalApplications");
12147        List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
12148        List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
12149        if (runningApps != null && runningApps.size() > 0) {
12150            Set<String> extList = new HashSet<String>();
12151            for (ActivityManager.RunningAppProcessInfo app : runningApps) {
12152                if (app.pkgList != null) {
12153                    for (String pkg : app.pkgList) {
12154                        extList.add(pkg);
12155                    }
12156                }
12157            }
12158            IPackageManager pm = AppGlobals.getPackageManager();
12159            for (String pkg : extList) {
12160                try {
12161                    ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
12162                    if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
12163                        retList.add(info);
12164                    }
12165                } catch (RemoteException e) {
12166                }
12167            }
12168        }
12169        return retList;
12170    }
12171
12172    @Override
12173    public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
12174        enforceNotIsolatedCaller("getMyMemoryState");
12175        synchronized (this) {
12176            ProcessRecord proc;
12177            synchronized (mPidsSelfLocked) {
12178                proc = mPidsSelfLocked.get(Binder.getCallingPid());
12179            }
12180            fillInProcMemInfo(proc, outInfo);
12181        }
12182    }
12183
12184    @Override
12185    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12186        if (checkCallingPermission(android.Manifest.permission.DUMP)
12187                != PackageManager.PERMISSION_GRANTED) {
12188            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12189                    + Binder.getCallingPid()
12190                    + ", uid=" + Binder.getCallingUid()
12191                    + " without permission "
12192                    + android.Manifest.permission.DUMP);
12193            return;
12194        }
12195
12196        boolean dumpAll = false;
12197        boolean dumpClient = false;
12198        String dumpPackage = null;
12199
12200        int opti = 0;
12201        while (opti < args.length) {
12202            String opt = args[opti];
12203            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12204                break;
12205            }
12206            opti++;
12207            if ("-a".equals(opt)) {
12208                dumpAll = true;
12209            } else if ("-c".equals(opt)) {
12210                dumpClient = true;
12211            } else if ("-h".equals(opt)) {
12212                pw.println("Activity manager dump options:");
12213                pw.println("  [-a] [-c] [-h] [cmd] ...");
12214                pw.println("  cmd may be one of:");
12215                pw.println("    a[ctivities]: activity stack state");
12216                pw.println("    r[recents]: recent activities state");
12217                pw.println("    b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
12218                pw.println("    i[ntents] [PACKAGE_NAME]: pending intent state");
12219                pw.println("    p[rocesses] [PACKAGE_NAME]: process state");
12220                pw.println("    o[om]: out of memory management");
12221                pw.println("    prov[iders] [COMP_SPEC ...]: content provider state");
12222                pw.println("    provider [COMP_SPEC]: provider client-side state");
12223                pw.println("    s[ervices] [COMP_SPEC ...]: service state");
12224                pw.println("    service [COMP_SPEC]: service client-side state");
12225                pw.println("    package [PACKAGE_NAME]: all state related to given package");
12226                pw.println("    all: dump all activities");
12227                pw.println("    top: dump the top activity");
12228                pw.println("  cmd may also be a COMP_SPEC to dump activities.");
12229                pw.println("  COMP_SPEC may be a component name (com.foo/.myApp),");
12230                pw.println("    a partial substring in a component name, a");
12231                pw.println("    hex object identifier.");
12232                pw.println("  -a: include all available server state.");
12233                pw.println("  -c: include client state.");
12234                return;
12235            } else {
12236                pw.println("Unknown argument: " + opt + "; use -h for help");
12237            }
12238        }
12239
12240        long origId = Binder.clearCallingIdentity();
12241        boolean more = false;
12242        // Is the caller requesting to dump a particular piece of data?
12243        if (opti < args.length) {
12244            String cmd = args[opti];
12245            opti++;
12246            if ("activities".equals(cmd) || "a".equals(cmd)) {
12247                synchronized (this) {
12248                    dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
12249                }
12250            } else if ("recents".equals(cmd) || "r".equals(cmd)) {
12251                synchronized (this) {
12252                    dumpRecentsLocked(fd, pw, args, opti, true, null);
12253                }
12254            } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
12255                String[] newArgs;
12256                String name;
12257                if (opti >= args.length) {
12258                    name = null;
12259                    newArgs = EMPTY_STRING_ARRAY;
12260                } else {
12261                    name = args[opti];
12262                    opti++;
12263                    newArgs = new String[args.length - opti];
12264                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
12265                            args.length - opti);
12266                }
12267                synchronized (this) {
12268                    dumpBroadcastsLocked(fd, pw, args, opti, true, name);
12269                }
12270            } else if ("intents".equals(cmd) || "i".equals(cmd)) {
12271                String[] newArgs;
12272                String name;
12273                if (opti >= args.length) {
12274                    name = null;
12275                    newArgs = EMPTY_STRING_ARRAY;
12276                } else {
12277                    name = args[opti];
12278                    opti++;
12279                    newArgs = new String[args.length - opti];
12280                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
12281                            args.length - opti);
12282                }
12283                synchronized (this) {
12284                    dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
12285                }
12286            } else if ("processes".equals(cmd) || "p".equals(cmd)) {
12287                String[] newArgs;
12288                String name;
12289                if (opti >= args.length) {
12290                    name = null;
12291                    newArgs = EMPTY_STRING_ARRAY;
12292                } else {
12293                    name = args[opti];
12294                    opti++;
12295                    newArgs = new String[args.length - opti];
12296                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
12297                            args.length - opti);
12298                }
12299                synchronized (this) {
12300                    dumpProcessesLocked(fd, pw, args, opti, true, name);
12301                }
12302            } else if ("oom".equals(cmd) || "o".equals(cmd)) {
12303                synchronized (this) {
12304                    dumpOomLocked(fd, pw, args, opti, true);
12305                }
12306            } else if ("provider".equals(cmd)) {
12307                String[] newArgs;
12308                String name;
12309                if (opti >= args.length) {
12310                    name = null;
12311                    newArgs = EMPTY_STRING_ARRAY;
12312                } else {
12313                    name = args[opti];
12314                    opti++;
12315                    newArgs = new String[args.length - opti];
12316                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
12317                }
12318                if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
12319                    pw.println("No providers match: " + name);
12320                    pw.println("Use -h for help.");
12321                }
12322            } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
12323                synchronized (this) {
12324                    dumpProvidersLocked(fd, pw, args, opti, true, null);
12325                }
12326            } else if ("service".equals(cmd)) {
12327                String[] newArgs;
12328                String name;
12329                if (opti >= args.length) {
12330                    name = null;
12331                    newArgs = EMPTY_STRING_ARRAY;
12332                } else {
12333                    name = args[opti];
12334                    opti++;
12335                    newArgs = new String[args.length - opti];
12336                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
12337                            args.length - opti);
12338                }
12339                if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
12340                    pw.println("No services match: " + name);
12341                    pw.println("Use -h for help.");
12342                }
12343            } else if ("package".equals(cmd)) {
12344                String[] newArgs;
12345                if (opti >= args.length) {
12346                    pw.println("package: no package name specified");
12347                    pw.println("Use -h for help.");
12348                } else {
12349                    dumpPackage = args[opti];
12350                    opti++;
12351                    newArgs = new String[args.length - opti];
12352                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
12353                            args.length - opti);
12354                    args = newArgs;
12355                    opti = 0;
12356                    more = true;
12357                }
12358            } else if ("services".equals(cmd) || "s".equals(cmd)) {
12359                synchronized (this) {
12360                    mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
12361                }
12362            } else {
12363                // Dumping a single activity?
12364                if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
12365                    pw.println("Bad activity command, or no activities match: " + cmd);
12366                    pw.println("Use -h for help.");
12367                }
12368            }
12369            if (!more) {
12370                Binder.restoreCallingIdentity(origId);
12371                return;
12372            }
12373        }
12374
12375        // No piece of data specified, dump everything.
12376        synchronized (this) {
12377            dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
12378            pw.println();
12379            if (dumpAll) {
12380                pw.println("-------------------------------------------------------------------------------");
12381            }
12382            dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
12383            pw.println();
12384            if (dumpAll) {
12385                pw.println("-------------------------------------------------------------------------------");
12386            }
12387            dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
12388            pw.println();
12389            if (dumpAll) {
12390                pw.println("-------------------------------------------------------------------------------");
12391            }
12392            mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
12393            pw.println();
12394            if (dumpAll) {
12395                pw.println("-------------------------------------------------------------------------------");
12396            }
12397            dumpRecentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
12398            pw.println();
12399            if (dumpAll) {
12400                pw.println("-------------------------------------------------------------------------------");
12401            }
12402            dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
12403            pw.println();
12404            if (dumpAll) {
12405                pw.println("-------------------------------------------------------------------------------");
12406            }
12407            dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
12408        }
12409        Binder.restoreCallingIdentity(origId);
12410    }
12411
12412    void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12413            int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
12414        pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
12415
12416        boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
12417                dumpPackage);
12418        boolean needSep = printedAnything;
12419
12420        boolean printed = ActivityStackSupervisor.printThisActivity(pw, mFocusedActivity,
12421                dumpPackage, needSep, "  mFocusedActivity: ");
12422        if (printed) {
12423            printedAnything = true;
12424            needSep = false;
12425        }
12426
12427        if (dumpPackage == null) {
12428            if (needSep) {
12429                pw.println();
12430            }
12431            needSep = true;
12432            printedAnything = true;
12433            mStackSupervisor.dump(pw, "  ");
12434        }
12435
12436        if (!printedAnything) {
12437            pw.println("  (nothing)");
12438        }
12439    }
12440
12441    void dumpRecentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12442            int opti, boolean dumpAll, String dumpPackage) {
12443        pw.println("ACTIVITY MANAGER RECENT ACTIVITIES (dumpsys activity recents)");
12444
12445        boolean printedAnything = false;
12446
12447        if (mRecentTasks.size() > 0) {
12448            boolean printedHeader = false;
12449
12450            final int N = mRecentTasks.size();
12451            for (int i=0; i<N; i++) {
12452                TaskRecord tr = mRecentTasks.get(i);
12453                if (dumpPackage != null) {
12454                    if (tr.realActivity == null ||
12455                            !dumpPackage.equals(tr.realActivity)) {
12456                        continue;
12457                    }
12458                }
12459                if (!printedHeader) {
12460                    pw.println("  Recent tasks:");
12461                    printedHeader = true;
12462                    printedAnything = true;
12463                }
12464                pw.print("  * Recent #"); pw.print(i); pw.print(": ");
12465                        pw.println(tr);
12466                if (dumpAll) {
12467                    mRecentTasks.get(i).dump(pw, "    ");
12468                }
12469            }
12470        }
12471
12472        if (!printedAnything) {
12473            pw.println("  (nothing)");
12474        }
12475    }
12476
12477    void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12478            int opti, boolean dumpAll, String dumpPackage) {
12479        boolean needSep = false;
12480        boolean printedAnything = false;
12481        int numPers = 0;
12482
12483        pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
12484
12485        if (dumpAll) {
12486            final int NP = mProcessNames.getMap().size();
12487            for (int ip=0; ip<NP; ip++) {
12488                SparseArray<ProcessRecord> procs = mProcessNames.getMap().valueAt(ip);
12489                final int NA = procs.size();
12490                for (int ia=0; ia<NA; ia++) {
12491                    ProcessRecord r = procs.valueAt(ia);
12492                    if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
12493                        continue;
12494                    }
12495                    if (!needSep) {
12496                        pw.println("  All known processes:");
12497                        needSep = true;
12498                        printedAnything = true;
12499                    }
12500                    pw.print(r.persistent ? "  *PERS*" : "  *APP*");
12501                        pw.print(" UID "); pw.print(procs.keyAt(ia));
12502                        pw.print(" "); pw.println(r);
12503                    r.dump(pw, "    ");
12504                    if (r.persistent) {
12505                        numPers++;
12506                    }
12507                }
12508            }
12509        }
12510
12511        if (mIsolatedProcesses.size() > 0) {
12512            boolean printed = false;
12513            for (int i=0; i<mIsolatedProcesses.size(); i++) {
12514                ProcessRecord r = mIsolatedProcesses.valueAt(i);
12515                if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
12516                    continue;
12517                }
12518                if (!printed) {
12519                    if (needSep) {
12520                        pw.println();
12521                    }
12522                    pw.println("  Isolated process list (sorted by uid):");
12523                    printedAnything = true;
12524                    printed = true;
12525                    needSep = true;
12526                }
12527                pw.println(String.format("%sIsolated #%2d: %s",
12528                        "    ", i, r.toString()));
12529            }
12530        }
12531
12532        if (mLruProcesses.size() > 0) {
12533            if (needSep) {
12534                pw.println();
12535            }
12536            pw.print("  Process LRU list (sorted by oom_adj, "); pw.print(mLruProcesses.size());
12537                    pw.print(" total, non-act at ");
12538                    pw.print(mLruProcesses.size()-mLruProcessActivityStart);
12539                    pw.print(", non-svc at ");
12540                    pw.print(mLruProcesses.size()-mLruProcessServiceStart);
12541                    pw.println("):");
12542            dumpProcessOomList(pw, this, mLruProcesses, "    ", "Proc", "PERS", false, dumpPackage);
12543            needSep = true;
12544            printedAnything = true;
12545        }
12546
12547        if (dumpAll || dumpPackage != null) {
12548            synchronized (mPidsSelfLocked) {
12549                boolean printed = false;
12550                for (int i=0; i<mPidsSelfLocked.size(); i++) {
12551                    ProcessRecord r = mPidsSelfLocked.valueAt(i);
12552                    if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
12553                        continue;
12554                    }
12555                    if (!printed) {
12556                        if (needSep) pw.println();
12557                        needSep = true;
12558                        pw.println("  PID mappings:");
12559                        printed = true;
12560                        printedAnything = true;
12561                    }
12562                    pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
12563                        pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
12564                }
12565            }
12566        }
12567
12568        if (mForegroundProcesses.size() > 0) {
12569            synchronized (mPidsSelfLocked) {
12570                boolean printed = false;
12571                for (int i=0; i<mForegroundProcesses.size(); i++) {
12572                    ProcessRecord r = mPidsSelfLocked.get(
12573                            mForegroundProcesses.valueAt(i).pid);
12574                    if (dumpPackage != null && (r == null
12575                            || !r.pkgList.containsKey(dumpPackage))) {
12576                        continue;
12577                    }
12578                    if (!printed) {
12579                        if (needSep) pw.println();
12580                        needSep = true;
12581                        pw.println("  Foreground Processes:");
12582                        printed = true;
12583                        printedAnything = true;
12584                    }
12585                    pw.print("    PID #"); pw.print(mForegroundProcesses.keyAt(i));
12586                            pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
12587                }
12588            }
12589        }
12590
12591        if (mPersistentStartingProcesses.size() > 0) {
12592            if (needSep) pw.println();
12593            needSep = true;
12594            printedAnything = true;
12595            pw.println("  Persisent processes that are starting:");
12596            dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
12597                    "Starting Norm", "Restarting PERS", dumpPackage);
12598        }
12599
12600        if (mRemovedProcesses.size() > 0) {
12601            if (needSep) pw.println();
12602            needSep = true;
12603            printedAnything = true;
12604            pw.println("  Processes that are being removed:");
12605            dumpProcessList(pw, this, mRemovedProcesses, "    ",
12606                    "Removed Norm", "Removed PERS", dumpPackage);
12607        }
12608
12609        if (mProcessesOnHold.size() > 0) {
12610            if (needSep) pw.println();
12611            needSep = true;
12612            printedAnything = true;
12613            pw.println("  Processes that are on old until the system is ready:");
12614            dumpProcessList(pw, this, mProcessesOnHold, "    ",
12615                    "OnHold Norm", "OnHold PERS", dumpPackage);
12616        }
12617
12618        needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
12619
12620        if (mProcessCrashTimes.getMap().size() > 0) {
12621            boolean printed = false;
12622            long now = SystemClock.uptimeMillis();
12623            final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
12624            final int NP = pmap.size();
12625            for (int ip=0; ip<NP; ip++) {
12626                String pname = pmap.keyAt(ip);
12627                SparseArray<Long> uids = pmap.valueAt(ip);
12628                final int N = uids.size();
12629                for (int i=0; i<N; i++) {
12630                    int puid = uids.keyAt(i);
12631                    ProcessRecord r = mProcessNames.get(pname, puid);
12632                    if (dumpPackage != null && (r == null
12633                            || !r.pkgList.containsKey(dumpPackage))) {
12634                        continue;
12635                    }
12636                    if (!printed) {
12637                        if (needSep) pw.println();
12638                        needSep = true;
12639                        pw.println("  Time since processes crashed:");
12640                        printed = true;
12641                        printedAnything = true;
12642                    }
12643                    pw.print("    Process "); pw.print(pname);
12644                            pw.print(" uid "); pw.print(puid);
12645                            pw.print(": last crashed ");
12646                            TimeUtils.formatDuration(now-uids.valueAt(i), pw);
12647                            pw.println(" ago");
12648                }
12649            }
12650        }
12651
12652        if (mBadProcesses.getMap().size() > 0) {
12653            boolean printed = false;
12654            final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap();
12655            final int NP = pmap.size();
12656            for (int ip=0; ip<NP; ip++) {
12657                String pname = pmap.keyAt(ip);
12658                SparseArray<BadProcessInfo> uids = pmap.valueAt(ip);
12659                final int N = uids.size();
12660                for (int i=0; i<N; i++) {
12661                    int puid = uids.keyAt(i);
12662                    ProcessRecord r = mProcessNames.get(pname, puid);
12663                    if (dumpPackage != null && (r == null
12664                            || !r.pkgList.containsKey(dumpPackage))) {
12665                        continue;
12666                    }
12667                    if (!printed) {
12668                        if (needSep) pw.println();
12669                        needSep = true;
12670                        pw.println("  Bad processes:");
12671                        printedAnything = true;
12672                    }
12673                    BadProcessInfo info = uids.valueAt(i);
12674                    pw.print("    Bad process "); pw.print(pname);
12675                            pw.print(" uid "); pw.print(puid);
12676                            pw.print(": crashed at time "); pw.println(info.time);
12677                    if (info.shortMsg != null) {
12678                        pw.print("      Short msg: "); pw.println(info.shortMsg);
12679                    }
12680                    if (info.longMsg != null) {
12681                        pw.print("      Long msg: "); pw.println(info.longMsg);
12682                    }
12683                    if (info.stack != null) {
12684                        pw.println("      Stack:");
12685                        int lastPos = 0;
12686                        for (int pos=0; pos<info.stack.length(); pos++) {
12687                            if (info.stack.charAt(pos) == '\n') {
12688                                pw.print("        ");
12689                                pw.write(info.stack, lastPos, pos-lastPos);
12690                                pw.println();
12691                                lastPos = pos+1;
12692                            }
12693                        }
12694                        if (lastPos < info.stack.length()) {
12695                            pw.print("        ");
12696                            pw.write(info.stack, lastPos, info.stack.length()-lastPos);
12697                            pw.println();
12698                        }
12699                    }
12700                }
12701            }
12702        }
12703
12704        if (dumpPackage == null) {
12705            pw.println();
12706            needSep = false;
12707            pw.println("  mStartedUsers:");
12708            for (int i=0; i<mStartedUsers.size(); i++) {
12709                UserStartedState uss = mStartedUsers.valueAt(i);
12710                pw.print("    User #"); pw.print(uss.mHandle.getIdentifier());
12711                        pw.print(": "); uss.dump("", pw);
12712            }
12713            pw.print("  mStartedUserArray: [");
12714            for (int i=0; i<mStartedUserArray.length; i++) {
12715                if (i > 0) pw.print(", ");
12716                pw.print(mStartedUserArray[i]);
12717            }
12718            pw.println("]");
12719            pw.print("  mUserLru: [");
12720            for (int i=0; i<mUserLru.size(); i++) {
12721                if (i > 0) pw.print(", ");
12722                pw.print(mUserLru.get(i));
12723            }
12724            pw.println("]");
12725            if (dumpAll) {
12726                pw.print("  mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
12727            }
12728            synchronized (mUserProfileGroupIdsSelfLocked) {
12729                if (mUserProfileGroupIdsSelfLocked.size() > 0) {
12730                    pw.println("  mUserProfileGroupIds:");
12731                    for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
12732                        pw.print("    User #");
12733                        pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
12734                        pw.print(" -> profile #");
12735                        pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
12736                    }
12737                }
12738            }
12739        }
12740        if (mHomeProcess != null && (dumpPackage == null
12741                || mHomeProcess.pkgList.containsKey(dumpPackage))) {
12742            if (needSep) {
12743                pw.println();
12744                needSep = false;
12745            }
12746            pw.println("  mHomeProcess: " + mHomeProcess);
12747        }
12748        if (mPreviousProcess != null && (dumpPackage == null
12749                || mPreviousProcess.pkgList.containsKey(dumpPackage))) {
12750            if (needSep) {
12751                pw.println();
12752                needSep = false;
12753            }
12754            pw.println("  mPreviousProcess: " + mPreviousProcess);
12755        }
12756        if (dumpAll) {
12757            StringBuilder sb = new StringBuilder(128);
12758            sb.append("  mPreviousProcessVisibleTime: ");
12759            TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
12760            pw.println(sb);
12761        }
12762        if (mHeavyWeightProcess != null && (dumpPackage == null
12763                || mHeavyWeightProcess.pkgList.containsKey(dumpPackage))) {
12764            if (needSep) {
12765                pw.println();
12766                needSep = false;
12767            }
12768            pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
12769        }
12770        if (dumpPackage == null) {
12771            pw.println("  mConfiguration: " + mConfiguration);
12772        }
12773        if (dumpAll) {
12774            pw.println("  mConfigWillChange: " + getFocusedStack().mConfigWillChange);
12775            if (mCompatModePackages.getPackages().size() > 0) {
12776                boolean printed = false;
12777                for (Map.Entry<String, Integer> entry
12778                        : mCompatModePackages.getPackages().entrySet()) {
12779                    String pkg = entry.getKey();
12780                    int mode = entry.getValue();
12781                    if (dumpPackage != null && !dumpPackage.equals(pkg)) {
12782                        continue;
12783                    }
12784                    if (!printed) {
12785                        pw.println("  mScreenCompatPackages:");
12786                        printed = true;
12787                    }
12788                    pw.print("    "); pw.print(pkg); pw.print(": ");
12789                            pw.print(mode); pw.println();
12790                }
12791            }
12792        }
12793        if (dumpPackage == null) {
12794            if (mSleeping || mWentToSleep || mLockScreenShown) {
12795                pw.println("  mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
12796                        + " mLockScreenShown " + mLockScreenShown);
12797            }
12798            if (mShuttingDown || mRunningVoice) {
12799                pw.print("  mShuttingDown=" + mShuttingDown + " mRunningVoice=" + mRunningVoice);
12800            }
12801        }
12802        if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
12803                || mOrigWaitForDebugger) {
12804            if (dumpPackage == null || dumpPackage.equals(mDebugApp)
12805                    || dumpPackage.equals(mOrigDebugApp)) {
12806                if (needSep) {
12807                    pw.println();
12808                    needSep = false;
12809                }
12810                pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
12811                        + " mDebugTransient=" + mDebugTransient
12812                        + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
12813            }
12814        }
12815        if (mOpenGlTraceApp != null) {
12816            if (dumpPackage == null || dumpPackage.equals(mOpenGlTraceApp)) {
12817                if (needSep) {
12818                    pw.println();
12819                    needSep = false;
12820                }
12821                pw.println("  mOpenGlTraceApp=" + mOpenGlTraceApp);
12822            }
12823        }
12824        if (mProfileApp != null || mProfileProc != null || mProfileFile != null
12825                || mProfileFd != null) {
12826            if (dumpPackage == null || dumpPackage.equals(mProfileApp)) {
12827                if (needSep) {
12828                    pw.println();
12829                    needSep = false;
12830                }
12831                pw.println("  mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
12832                pw.println("  mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
12833                pw.println("  mSamplingInterval=" + mSamplingInterval + " mAutoStopProfiler="
12834                        + mAutoStopProfiler);
12835                pw.println("  mProfileType=" + mProfileType);
12836            }
12837        }
12838        if (dumpPackage == null) {
12839            if (mAlwaysFinishActivities || mController != null) {
12840                pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities
12841                        + " mController=" + mController);
12842            }
12843            if (dumpAll) {
12844                pw.println("  Total persistent processes: " + numPers);
12845                pw.println("  mProcessesReady=" + mProcessesReady
12846                        + " mSystemReady=" + mSystemReady);
12847                pw.println("  mBooting=" + mBooting
12848                        + " mBooted=" + mBooted
12849                        + " mFactoryTest=" + mFactoryTest);
12850                pw.print("  mLastPowerCheckRealtime=");
12851                        TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
12852                        pw.println("");
12853                pw.print("  mLastPowerCheckUptime=");
12854                        TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
12855                        pw.println("");
12856                pw.println("  mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
12857                pw.println("  mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
12858                pw.println("  mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
12859                pw.println("  mNumNonCachedProcs=" + mNumNonCachedProcs
12860                        + " (" + mLruProcesses.size() + " total)"
12861                        + " mNumCachedHiddenProcs=" + mNumCachedHiddenProcs
12862                        + " mNumServiceProcs=" + mNumServiceProcs
12863                        + " mNewNumServiceProcs=" + mNewNumServiceProcs);
12864                pw.println("  mAllowLowerMemLevel=" + mAllowLowerMemLevel
12865                        + " mLastMemoryLevel" + mLastMemoryLevel
12866                        + " mLastNumProcesses" + mLastNumProcesses);
12867                long now = SystemClock.uptimeMillis();
12868                pw.print("  mLastIdleTime=");
12869                        TimeUtils.formatDuration(now, mLastIdleTime, pw);
12870                        pw.print(" mLowRamSinceLastIdle=");
12871                        TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw);
12872                        pw.println();
12873            }
12874        }
12875
12876        if (!printedAnything) {
12877            pw.println("  (nothing)");
12878        }
12879    }
12880
12881    boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
12882            int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
12883        if (mProcessesToGc.size() > 0) {
12884            boolean printed = false;
12885            long now = SystemClock.uptimeMillis();
12886            for (int i=0; i<mProcessesToGc.size(); i++) {
12887                ProcessRecord proc = mProcessesToGc.get(i);
12888                if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
12889                    continue;
12890                }
12891                if (!printed) {
12892                    if (needSep) pw.println();
12893                    needSep = true;
12894                    pw.println("  Processes that are waiting to GC:");
12895                    printed = true;
12896                }
12897                pw.print("    Process "); pw.println(proc);
12898                pw.print("      lowMem="); pw.print(proc.reportLowMemory);
12899                        pw.print(", last gced=");
12900                        pw.print(now-proc.lastRequestedGc);
12901                        pw.print(" ms ago, last lowMem=");
12902                        pw.print(now-proc.lastLowMemory);
12903                        pw.println(" ms ago");
12904
12905            }
12906        }
12907        return needSep;
12908    }
12909
12910    void printOomLevel(PrintWriter pw, String name, int adj) {
12911        pw.print("    ");
12912        if (adj >= 0) {
12913            pw.print(' ');
12914            if (adj < 10) pw.print(' ');
12915        } else {
12916            if (adj > -10) pw.print(' ');
12917        }
12918        pw.print(adj);
12919        pw.print(": ");
12920        pw.print(name);
12921        pw.print(" (");
12922        pw.print(mProcessList.getMemLevel(adj)/1024);
12923        pw.println(" kB)");
12924    }
12925
12926    boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12927            int opti, boolean dumpAll) {
12928        boolean needSep = false;
12929
12930        if (mLruProcesses.size() > 0) {
12931            if (needSep) pw.println();
12932            needSep = true;
12933            pw.println("  OOM levels:");
12934            printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ);
12935            printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ);
12936            printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ);
12937            printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ);
12938            printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ);
12939            printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ);
12940            printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ);
12941            printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ);
12942            printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ);
12943            printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ);
12944            printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ);
12945            printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ);
12946            printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ);
12947
12948            if (needSep) pw.println();
12949            pw.print("  Process OOM control ("); pw.print(mLruProcesses.size());
12950                    pw.print(" total, non-act at ");
12951                    pw.print(mLruProcesses.size()-mLruProcessActivityStart);
12952                    pw.print(", non-svc at ");
12953                    pw.print(mLruProcesses.size()-mLruProcessServiceStart);
12954                    pw.println("):");
12955            dumpProcessOomList(pw, this, mLruProcesses, "    ", "Proc", "PERS", true, null);
12956            needSep = true;
12957        }
12958
12959        dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
12960
12961        pw.println();
12962        pw.println("  mHomeProcess: " + mHomeProcess);
12963        pw.println("  mPreviousProcess: " + mPreviousProcess);
12964        if (mHeavyWeightProcess != null) {
12965            pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
12966        }
12967
12968        return true;
12969    }
12970
12971    /**
12972     * There are three ways to call this:
12973     *  - no provider specified: dump all the providers
12974     *  - a flattened component name that matched an existing provider was specified as the
12975     *    first arg: dump that one provider
12976     *  - the first arg isn't the flattened component name of an existing provider:
12977     *    dump all providers whose component contains the first arg as a substring
12978     */
12979    protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
12980            int opti, boolean dumpAll) {
12981        return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
12982    }
12983
12984    static class ItemMatcher {
12985        ArrayList<ComponentName> components;
12986        ArrayList<String> strings;
12987        ArrayList<Integer> objects;
12988        boolean all;
12989
12990        ItemMatcher() {
12991            all = true;
12992        }
12993
12994        void build(String name) {
12995            ComponentName componentName = ComponentName.unflattenFromString(name);
12996            if (componentName != null) {
12997                if (components == null) {
12998                    components = new ArrayList<ComponentName>();
12999                }
13000                components.add(componentName);
13001                all = false;
13002            } else {
13003                int objectId = 0;
13004                // Not a '/' separated full component name; maybe an object ID?
13005                try {
13006                    objectId = Integer.parseInt(name, 16);
13007                    if (objects == null) {
13008                        objects = new ArrayList<Integer>();
13009                    }
13010                    objects.add(objectId);
13011                    all = false;
13012                } catch (RuntimeException e) {
13013                    // Not an integer; just do string match.
13014                    if (strings == null) {
13015                        strings = new ArrayList<String>();
13016                    }
13017                    strings.add(name);
13018                    all = false;
13019                }
13020            }
13021        }
13022
13023        int build(String[] args, int opti) {
13024            for (; opti<args.length; opti++) {
13025                String name = args[opti];
13026                if ("--".equals(name)) {
13027                    return opti+1;
13028                }
13029                build(name);
13030            }
13031            return opti;
13032        }
13033
13034        boolean match(Object object, ComponentName comp) {
13035            if (all) {
13036                return true;
13037            }
13038            if (components != null) {
13039                for (int i=0; i<components.size(); i++) {
13040                    if (components.get(i).equals(comp)) {
13041                        return true;
13042                    }
13043                }
13044            }
13045            if (objects != null) {
13046                for (int i=0; i<objects.size(); i++) {
13047                    if (System.identityHashCode(object) == objects.get(i)) {
13048                        return true;
13049                    }
13050                }
13051            }
13052            if (strings != null) {
13053                String flat = comp.flattenToString();
13054                for (int i=0; i<strings.size(); i++) {
13055                    if (flat.contains(strings.get(i))) {
13056                        return true;
13057                    }
13058                }
13059            }
13060            return false;
13061        }
13062    }
13063
13064    /**
13065     * There are three things that cmd can be:
13066     *  - a flattened component name that matches an existing activity
13067     *  - the cmd arg isn't the flattened component name of an existing activity:
13068     *    dump all activity whose component contains the cmd as a substring
13069     *  - A hex number of the ActivityRecord object instance.
13070     */
13071    protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
13072            int opti, boolean dumpAll) {
13073        ArrayList<ActivityRecord> activities;
13074
13075        synchronized (this) {
13076            activities = mStackSupervisor.getDumpActivitiesLocked(name);
13077        }
13078
13079        if (activities.size() <= 0) {
13080            return false;
13081        }
13082
13083        String[] newArgs = new String[args.length - opti];
13084        System.arraycopy(args, opti, newArgs, 0, args.length - opti);
13085
13086        TaskRecord lastTask = null;
13087        boolean needSep = false;
13088        for (int i=activities.size()-1; i>=0; i--) {
13089            ActivityRecord r = activities.get(i);
13090            if (needSep) {
13091                pw.println();
13092            }
13093            needSep = true;
13094            synchronized (this) {
13095                if (lastTask != r.task) {
13096                    lastTask = r.task;
13097                    pw.print("TASK "); pw.print(lastTask.affinity);
13098                            pw.print(" id="); pw.println(lastTask.taskId);
13099                    if (dumpAll) {
13100                        lastTask.dump(pw, "  ");
13101                    }
13102                }
13103            }
13104            dumpActivity("  ", fd, pw, activities.get(i), newArgs, dumpAll);
13105        }
13106        return true;
13107    }
13108
13109    /**
13110     * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
13111     * there is a thread associated with the activity.
13112     */
13113    private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
13114            final ActivityRecord r, String[] args, boolean dumpAll) {
13115        String innerPrefix = prefix + "  ";
13116        synchronized (this) {
13117            pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
13118                    pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
13119                    pw.print(" pid=");
13120                    if (r.app != null) pw.println(r.app.pid);
13121                    else pw.println("(not running)");
13122            if (dumpAll) {
13123                r.dump(pw, innerPrefix);
13124            }
13125        }
13126        if (r.app != null && r.app.thread != null) {
13127            // flush anything that is already in the PrintWriter since the thread is going
13128            // to write to the file descriptor directly
13129            pw.flush();
13130            try {
13131                TransferPipe tp = new TransferPipe();
13132                try {
13133                    r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
13134                            r.appToken, innerPrefix, args);
13135                    tp.go(fd);
13136                } finally {
13137                    tp.kill();
13138                }
13139            } catch (IOException e) {
13140                pw.println(innerPrefix + "Failure while dumping the activity: " + e);
13141            } catch (RemoteException e) {
13142                pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
13143            }
13144        }
13145    }
13146
13147    void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
13148            int opti, boolean dumpAll, String dumpPackage) {
13149        boolean needSep = false;
13150        boolean onlyHistory = false;
13151        boolean printedAnything = false;
13152
13153        if ("history".equals(dumpPackage)) {
13154            if (opti < args.length && "-s".equals(args[opti])) {
13155                dumpAll = false;
13156            }
13157            onlyHistory = true;
13158            dumpPackage = null;
13159        }
13160
13161        pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
13162        if (!onlyHistory && dumpAll) {
13163            if (mRegisteredReceivers.size() > 0) {
13164                boolean printed = false;
13165                Iterator it = mRegisteredReceivers.values().iterator();
13166                while (it.hasNext()) {
13167                    ReceiverList r = (ReceiverList)it.next();
13168                    if (dumpPackage != null && (r.app == null ||
13169                            !dumpPackage.equals(r.app.info.packageName))) {
13170                        continue;
13171                    }
13172                    if (!printed) {
13173                        pw.println("  Registered Receivers:");
13174                        needSep = true;
13175                        printed = true;
13176                        printedAnything = true;
13177                    }
13178                    pw.print("  * "); pw.println(r);
13179                    r.dump(pw, "    ");
13180                }
13181            }
13182
13183            if (mReceiverResolver.dump(pw, needSep ?
13184                    "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
13185                    "    ", dumpPackage, false)) {
13186                needSep = true;
13187                printedAnything = true;
13188            }
13189        }
13190
13191        for (BroadcastQueue q : mBroadcastQueues) {
13192            needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
13193            printedAnything |= needSep;
13194        }
13195
13196        needSep = true;
13197
13198        if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
13199            for (int user=0; user<mStickyBroadcasts.size(); user++) {
13200                if (needSep) {
13201                    pw.println();
13202                }
13203                needSep = true;
13204                printedAnything = true;
13205                pw.print("  Sticky broadcasts for user ");
13206                        pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
13207                StringBuilder sb = new StringBuilder(128);
13208                for (Map.Entry<String, ArrayList<Intent>> ent
13209                        : mStickyBroadcasts.valueAt(user).entrySet()) {
13210                    pw.print("  * Sticky action "); pw.print(ent.getKey());
13211                    if (dumpAll) {
13212                        pw.println(":");
13213                        ArrayList<Intent> intents = ent.getValue();
13214                        final int N = intents.size();
13215                        for (int i=0; i<N; i++) {
13216                            sb.setLength(0);
13217                            sb.append("    Intent: ");
13218                            intents.get(i).toShortString(sb, false, true, false, false);
13219                            pw.println(sb.toString());
13220                            Bundle bundle = intents.get(i).getExtras();
13221                            if (bundle != null) {
13222                                pw.print("      ");
13223                                pw.println(bundle.toString());
13224                            }
13225                        }
13226                    } else {
13227                        pw.println("");
13228                    }
13229                }
13230            }
13231        }
13232
13233        if (!onlyHistory && dumpAll) {
13234            pw.println();
13235            for (BroadcastQueue queue : mBroadcastQueues) {
13236                pw.println("  mBroadcastsScheduled [" + queue.mQueueName + "]="
13237                        + queue.mBroadcastsScheduled);
13238            }
13239            pw.println("  mHandler:");
13240            mHandler.dump(new PrintWriterPrinter(pw), "    ");
13241            needSep = true;
13242            printedAnything = true;
13243        }
13244
13245        if (!printedAnything) {
13246            pw.println("  (nothing)");
13247        }
13248    }
13249
13250    void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
13251            int opti, boolean dumpAll, String dumpPackage) {
13252        boolean needSep;
13253        boolean printedAnything = false;
13254
13255        ItemMatcher matcher = new ItemMatcher();
13256        matcher.build(args, opti);
13257
13258        pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
13259
13260        needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage);
13261        printedAnything |= needSep;
13262
13263        if (mLaunchingProviders.size() > 0) {
13264            boolean printed = false;
13265            for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
13266                ContentProviderRecord r = mLaunchingProviders.get(i);
13267                if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
13268                    continue;
13269                }
13270                if (!printed) {
13271                    if (needSep) pw.println();
13272                    needSep = true;
13273                    pw.println("  Launching content providers:");
13274                    printed = true;
13275                    printedAnything = true;
13276                }
13277                pw.print("  Launching #"); pw.print(i); pw.print(": ");
13278                        pw.println(r);
13279            }
13280        }
13281
13282        if (mGrantedUriPermissions.size() > 0) {
13283            boolean printed = false;
13284            int dumpUid = -2;
13285            if (dumpPackage != null) {
13286                try {
13287                    dumpUid = mContext.getPackageManager().getPackageUid(dumpPackage, 0);
13288                } catch (NameNotFoundException e) {
13289                    dumpUid = -1;
13290                }
13291            }
13292            for (int i=0; i<mGrantedUriPermissions.size(); i++) {
13293                int uid = mGrantedUriPermissions.keyAt(i);
13294                if (dumpUid >= -1 && UserHandle.getAppId(uid) != dumpUid) {
13295                    continue;
13296                }
13297                final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
13298                if (!printed) {
13299                    if (needSep) pw.println();
13300                    needSep = true;
13301                    pw.println("  Granted Uri Permissions:");
13302                    printed = true;
13303                    printedAnything = true;
13304                }
13305                pw.print("  * UID "); pw.print(uid); pw.println(" holds:");
13306                for (UriPermission perm : perms.values()) {
13307                    pw.print("    "); pw.println(perm);
13308                    if (dumpAll) {
13309                        perm.dump(pw, "      ");
13310                    }
13311                }
13312            }
13313        }
13314
13315        if (!printedAnything) {
13316            pw.println("  (nothing)");
13317        }
13318    }
13319
13320    void dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
13321            int opti, boolean dumpAll, String dumpPackage) {
13322        boolean printed = false;
13323
13324        pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
13325
13326        if (mIntentSenderRecords.size() > 0) {
13327            Iterator<WeakReference<PendingIntentRecord>> it
13328                    = mIntentSenderRecords.values().iterator();
13329            while (it.hasNext()) {
13330                WeakReference<PendingIntentRecord> ref = it.next();
13331                PendingIntentRecord rec = ref != null ? ref.get(): null;
13332                if (dumpPackage != null && (rec == null
13333                        || !dumpPackage.equals(rec.key.packageName))) {
13334                    continue;
13335                }
13336                printed = true;
13337                if (rec != null) {
13338                    pw.print("  * "); pw.println(rec);
13339                    if (dumpAll) {
13340                        rec.dump(pw, "    ");
13341                    }
13342                } else {
13343                    pw.print("  * "); pw.println(ref);
13344                }
13345            }
13346        }
13347
13348        if (!printed) {
13349            pw.println("  (nothing)");
13350        }
13351    }
13352
13353    private static final int dumpProcessList(PrintWriter pw,
13354            ActivityManagerService service, List list,
13355            String prefix, String normalLabel, String persistentLabel,
13356            String dumpPackage) {
13357        int numPers = 0;
13358        final int N = list.size()-1;
13359        for (int i=N; i>=0; i--) {
13360            ProcessRecord r = (ProcessRecord)list.get(i);
13361            if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
13362                continue;
13363            }
13364            pw.println(String.format("%s%s #%2d: %s",
13365                    prefix, (r.persistent ? persistentLabel : normalLabel),
13366                    i, r.toString()));
13367            if (r.persistent) {
13368                numPers++;
13369            }
13370        }
13371        return numPers;
13372    }
13373
13374    private static final boolean dumpProcessOomList(PrintWriter pw,
13375            ActivityManagerService service, List<ProcessRecord> origList,
13376            String prefix, String normalLabel, String persistentLabel,
13377            boolean inclDetails, String dumpPackage) {
13378
13379        ArrayList<Pair<ProcessRecord, Integer>> list
13380                = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
13381        for (int i=0; i<origList.size(); i++) {
13382            ProcessRecord r = origList.get(i);
13383            if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
13384                continue;
13385            }
13386            list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
13387        }
13388
13389        if (list.size() <= 0) {
13390            return false;
13391        }
13392
13393        Comparator<Pair<ProcessRecord, Integer>> comparator
13394                = new Comparator<Pair<ProcessRecord, Integer>>() {
13395            @Override
13396            public int compare(Pair<ProcessRecord, Integer> object1,
13397                    Pair<ProcessRecord, Integer> object2) {
13398                if (object1.first.setAdj != object2.first.setAdj) {
13399                    return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
13400                }
13401                if (object1.second.intValue() != object2.second.intValue()) {
13402                    return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
13403                }
13404                return 0;
13405            }
13406        };
13407
13408        Collections.sort(list, comparator);
13409
13410        final long curRealtime = SystemClock.elapsedRealtime();
13411        final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
13412        final long curUptime = SystemClock.uptimeMillis();
13413        final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
13414
13415        for (int i=list.size()-1; i>=0; i--) {
13416            ProcessRecord r = list.get(i).first;
13417            String oomAdj = ProcessList.makeOomAdjString(r.setAdj);
13418            char schedGroup;
13419            switch (r.setSchedGroup) {
13420                case Process.THREAD_GROUP_BG_NONINTERACTIVE:
13421                    schedGroup = 'B';
13422                    break;
13423                case Process.THREAD_GROUP_DEFAULT:
13424                    schedGroup = 'F';
13425                    break;
13426                default:
13427                    schedGroup = '?';
13428                    break;
13429            }
13430            char foreground;
13431            if (r.foregroundActivities) {
13432                foreground = 'A';
13433            } else if (r.foregroundServices) {
13434                foreground = 'S';
13435            } else {
13436                foreground = ' ';
13437            }
13438            String procState = ProcessList.makeProcStateString(r.curProcState);
13439            pw.print(prefix);
13440            pw.print(r.persistent ? persistentLabel : normalLabel);
13441            pw.print(" #");
13442            int num = (origList.size()-1)-list.get(i).second;
13443            if (num < 10) pw.print(' ');
13444            pw.print(num);
13445            pw.print(": ");
13446            pw.print(oomAdj);
13447            pw.print(' ');
13448            pw.print(schedGroup);
13449            pw.print('/');
13450            pw.print(foreground);
13451            pw.print('/');
13452            pw.print(procState);
13453            pw.print(" trm:");
13454            if (r.trimMemoryLevel < 10) pw.print(' ');
13455            pw.print(r.trimMemoryLevel);
13456            pw.print(' ');
13457            pw.print(r.toShortString());
13458            pw.print(" (");
13459            pw.print(r.adjType);
13460            pw.println(')');
13461            if (r.adjSource != null || r.adjTarget != null) {
13462                pw.print(prefix);
13463                pw.print("    ");
13464                if (r.adjTarget instanceof ComponentName) {
13465                    pw.print(((ComponentName)r.adjTarget).flattenToShortString());
13466                } else if (r.adjTarget != null) {
13467                    pw.print(r.adjTarget.toString());
13468                } else {
13469                    pw.print("{null}");
13470                }
13471                pw.print("<=");
13472                if (r.adjSource instanceof ProcessRecord) {
13473                    pw.print("Proc{");
13474                    pw.print(((ProcessRecord)r.adjSource).toShortString());
13475                    pw.println("}");
13476                } else if (r.adjSource != null) {
13477                    pw.println(r.adjSource.toString());
13478                } else {
13479                    pw.println("{null}");
13480                }
13481            }
13482            if (inclDetails) {
13483                pw.print(prefix);
13484                pw.print("    ");
13485                pw.print("oom: max="); pw.print(r.maxAdj);
13486                pw.print(" curRaw="); pw.print(r.curRawAdj);
13487                pw.print(" setRaw="); pw.print(r.setRawAdj);
13488                pw.print(" cur="); pw.print(r.curAdj);
13489                pw.print(" set="); pw.println(r.setAdj);
13490                pw.print(prefix);
13491                pw.print("    ");
13492                pw.print("state: cur="); pw.print(ProcessList.makeProcStateString(r.curProcState));
13493                pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState));
13494                pw.print(" lastPss="); pw.print(r.lastPss);
13495                pw.print(" lastCachedPss="); pw.println(r.lastCachedPss);
13496                pw.print(prefix);
13497                pw.print("    ");
13498                pw.print("cached="); pw.print(r.cached);
13499                pw.print(" empty="); pw.print(r.empty);
13500                pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
13501
13502                if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
13503                    if (r.lastWakeTime != 0) {
13504                        long wtime;
13505                        BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
13506                        synchronized (stats) {
13507                            wtime = stats.getProcessWakeTime(r.info.uid,
13508                                    r.pid, curRealtime);
13509                        }
13510                        long timeUsed = wtime - r.lastWakeTime;
13511                        pw.print(prefix);
13512                        pw.print("    ");
13513                        pw.print("keep awake over ");
13514                        TimeUtils.formatDuration(realtimeSince, pw);
13515                        pw.print(" used ");
13516                        TimeUtils.formatDuration(timeUsed, pw);
13517                        pw.print(" (");
13518                        pw.print((timeUsed*100)/realtimeSince);
13519                        pw.println("%)");
13520                    }
13521                    if (r.lastCpuTime != 0) {
13522                        long timeUsed = r.curCpuTime - r.lastCpuTime;
13523                        pw.print(prefix);
13524                        pw.print("    ");
13525                        pw.print("run cpu over ");
13526                        TimeUtils.formatDuration(uptimeSince, pw);
13527                        pw.print(" used ");
13528                        TimeUtils.formatDuration(timeUsed, pw);
13529                        pw.print(" (");
13530                        pw.print((timeUsed*100)/uptimeSince);
13531                        pw.println("%)");
13532                    }
13533                }
13534            }
13535        }
13536        return true;
13537    }
13538
13539    ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
13540        ArrayList<ProcessRecord> procs;
13541        synchronized (this) {
13542            if (args != null && args.length > start
13543                    && args[start].charAt(0) != '-') {
13544                procs = new ArrayList<ProcessRecord>();
13545                int pid = -1;
13546                try {
13547                    pid = Integer.parseInt(args[start]);
13548                } catch (NumberFormatException e) {
13549                }
13550                for (int i=mLruProcesses.size()-1; i>=0; i--) {
13551                    ProcessRecord proc = mLruProcesses.get(i);
13552                    if (proc.pid == pid) {
13553                        procs.add(proc);
13554                    } else if (proc.processName.equals(args[start])) {
13555                        procs.add(proc);
13556                    }
13557                }
13558                if (procs.size() <= 0) {
13559                    return null;
13560                }
13561            } else {
13562                procs = new ArrayList<ProcessRecord>(mLruProcesses);
13563            }
13564        }
13565        return procs;
13566    }
13567
13568    final void dumpGraphicsHardwareUsage(FileDescriptor fd,
13569            PrintWriter pw, String[] args) {
13570        ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
13571        if (procs == null) {
13572            pw.println("No process found for: " + args[0]);
13573            return;
13574        }
13575
13576        long uptime = SystemClock.uptimeMillis();
13577        long realtime = SystemClock.elapsedRealtime();
13578        pw.println("Applications Graphics Acceleration Info:");
13579        pw.println("Uptime: " + uptime + " Realtime: " + realtime);
13580
13581        for (int i = procs.size() - 1 ; i >= 0 ; i--) {
13582            ProcessRecord r = procs.get(i);
13583            if (r.thread != null) {
13584                pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
13585                pw.flush();
13586                try {
13587                    TransferPipe tp = new TransferPipe();
13588                    try {
13589                        r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
13590                        tp.go(fd);
13591                    } finally {
13592                        tp.kill();
13593                    }
13594                } catch (IOException e) {
13595                    pw.println("Failure while dumping the app: " + r);
13596                    pw.flush();
13597                } catch (RemoteException e) {
13598                    pw.println("Got a RemoteException while dumping the app " + r);
13599                    pw.flush();
13600                }
13601            }
13602        }
13603    }
13604
13605    final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
13606        ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
13607        if (procs == null) {
13608            pw.println("No process found for: " + args[0]);
13609            return;
13610        }
13611
13612        pw.println("Applications Database Info:");
13613
13614        for (int i = procs.size() - 1 ; i >= 0 ; i--) {
13615            ProcessRecord r = procs.get(i);
13616            if (r.thread != null) {
13617                pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
13618                pw.flush();
13619                try {
13620                    TransferPipe tp = new TransferPipe();
13621                    try {
13622                        r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
13623                        tp.go(fd);
13624                    } finally {
13625                        tp.kill();
13626                    }
13627                } catch (IOException e) {
13628                    pw.println("Failure while dumping the app: " + r);
13629                    pw.flush();
13630                } catch (RemoteException e) {
13631                    pw.println("Got a RemoteException while dumping the app " + r);
13632                    pw.flush();
13633                }
13634            }
13635        }
13636    }
13637
13638    final static class MemItem {
13639        final boolean isProc;
13640        final String label;
13641        final String shortLabel;
13642        final long pss;
13643        final int id;
13644        final boolean hasActivities;
13645        ArrayList<MemItem> subitems;
13646
13647        public MemItem(String _label, String _shortLabel, long _pss, int _id,
13648                boolean _hasActivities) {
13649            isProc = true;
13650            label = _label;
13651            shortLabel = _shortLabel;
13652            pss = _pss;
13653            id = _id;
13654            hasActivities = _hasActivities;
13655        }
13656
13657        public MemItem(String _label, String _shortLabel, long _pss, int _id) {
13658            isProc = false;
13659            label = _label;
13660            shortLabel = _shortLabel;
13661            pss = _pss;
13662            id = _id;
13663            hasActivities = false;
13664        }
13665    }
13666
13667    static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
13668            ArrayList<MemItem> items, boolean sort, boolean isCompact) {
13669        if (sort && !isCompact) {
13670            Collections.sort(items, new Comparator<MemItem>() {
13671                @Override
13672                public int compare(MemItem lhs, MemItem rhs) {
13673                    if (lhs.pss < rhs.pss) {
13674                        return 1;
13675                    } else if (lhs.pss > rhs.pss) {
13676                        return -1;
13677                    }
13678                    return 0;
13679                }
13680            });
13681        }
13682
13683        for (int i=0; i<items.size(); i++) {
13684            MemItem mi = items.get(i);
13685            if (!isCompact) {
13686                pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
13687            } else if (mi.isProc) {
13688                pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
13689                pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss);
13690                pw.println(mi.hasActivities ? ",a" : ",e");
13691            } else {
13692                pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
13693                pw.println(mi.pss);
13694            }
13695            if (mi.subitems != null) {
13696                dumpMemItems(pw, prefix + "           ", mi.shortLabel, mi.subitems,
13697                        true, isCompact);
13698            }
13699        }
13700    }
13701
13702    // These are in KB.
13703    static final long[] DUMP_MEM_BUCKETS = new long[] {
13704        5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
13705        120*1024, 160*1024, 200*1024,
13706        250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
13707        1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
13708    };
13709
13710    static final void appendMemBucket(StringBuilder out, long memKB, String label,
13711            boolean stackLike) {
13712        int start = label.lastIndexOf('.');
13713        if (start >= 0) start++;
13714        else start = 0;
13715        int end = label.length();
13716        for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
13717            if (DUMP_MEM_BUCKETS[i] >= memKB) {
13718                long bucket = DUMP_MEM_BUCKETS[i]/1024;
13719                out.append(bucket);
13720                out.append(stackLike ? "MB." : "MB ");
13721                out.append(label, start, end);
13722                return;
13723            }
13724        }
13725        out.append(memKB/1024);
13726        out.append(stackLike ? "MB." : "MB ");
13727        out.append(label, start, end);
13728    }
13729
13730    static final int[] DUMP_MEM_OOM_ADJ = new int[] {
13731            ProcessList.NATIVE_ADJ,
13732            ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
13733            ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ,
13734            ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
13735            ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
13736            ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MAX_ADJ
13737    };
13738    static final String[] DUMP_MEM_OOM_LABEL = new String[] {
13739            "Native",
13740            "System", "Persistent", "Foreground",
13741            "Visible", "Perceptible",
13742            "Heavy Weight", "Backup",
13743            "A Services", "Home",
13744            "Previous", "B Services", "Cached"
13745    };
13746    static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
13747            "native",
13748            "sys", "pers", "fore",
13749            "vis", "percept",
13750            "heavy", "backup",
13751            "servicea", "home",
13752            "prev", "serviceb", "cached"
13753    };
13754
13755    private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
13756            long realtime, boolean isCheckinRequest, boolean isCompact) {
13757        if (isCheckinRequest || isCompact) {
13758            // short checkin version
13759            pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
13760        } else {
13761            pw.println("Applications Memory Usage (kB):");
13762            pw.println("Uptime: " + uptime + " Realtime: " + realtime);
13763        }
13764    }
13765
13766    final void dumpApplicationMemoryUsage(FileDescriptor fd,
13767            PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw) {
13768        boolean dumpDetails = false;
13769        boolean dumpFullDetails = false;
13770        boolean dumpDalvik = false;
13771        boolean oomOnly = false;
13772        boolean isCompact = false;
13773        boolean localOnly = false;
13774
13775        int opti = 0;
13776        while (opti < args.length) {
13777            String opt = args[opti];
13778            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13779                break;
13780            }
13781            opti++;
13782            if ("-a".equals(opt)) {
13783                dumpDetails = true;
13784                dumpFullDetails = true;
13785                dumpDalvik = true;
13786            } else if ("-d".equals(opt)) {
13787                dumpDalvik = true;
13788            } else if ("-c".equals(opt)) {
13789                isCompact = true;
13790            } else if ("--oom".equals(opt)) {
13791                oomOnly = true;
13792            } else if ("--local".equals(opt)) {
13793                localOnly = true;
13794            } else if ("-h".equals(opt)) {
13795                pw.println("meminfo dump options: [-a] [-d] [-c] [--oom] [process]");
13796                pw.println("  -a: include all available information for each process.");
13797                pw.println("  -d: include dalvik details when dumping process details.");
13798                pw.println("  -c: dump in a compact machine-parseable representation.");
13799                pw.println("  --oom: only show processes organized by oom adj.");
13800                pw.println("  --local: only collect details locally, don't call process.");
13801                pw.println("If [process] is specified it can be the name or ");
13802                pw.println("pid of a specific process to dump.");
13803                return;
13804            } else {
13805                pw.println("Unknown argument: " + opt + "; use -h for help");
13806            }
13807        }
13808
13809        final boolean isCheckinRequest = scanArgs(args, "--checkin");
13810        long uptime = SystemClock.uptimeMillis();
13811        long realtime = SystemClock.elapsedRealtime();
13812        final long[] tmpLong = new long[1];
13813
13814        ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
13815        if (procs == null) {
13816            // No Java processes.  Maybe they want to print a native process.
13817            if (args != null && args.length > opti
13818                    && args[opti].charAt(0) != '-') {
13819                ArrayList<ProcessCpuTracker.Stats> nativeProcs
13820                        = new ArrayList<ProcessCpuTracker.Stats>();
13821                updateCpuStatsNow();
13822                int findPid = -1;
13823                try {
13824                    findPid = Integer.parseInt(args[opti]);
13825                } catch (NumberFormatException e) {
13826                }
13827                synchronized (mProcessCpuTracker) {
13828                    final int N = mProcessCpuTracker.countStats();
13829                    for (int i=0; i<N; i++) {
13830                        ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13831                        if (st.pid == findPid || (st.baseName != null
13832                                && st.baseName.equals(args[opti]))) {
13833                            nativeProcs.add(st);
13834                        }
13835                    }
13836                }
13837                if (nativeProcs.size() > 0) {
13838                    dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest,
13839                            isCompact);
13840                    Debug.MemoryInfo mi = null;
13841                    for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
13842                        final ProcessCpuTracker.Stats r = nativeProcs.get(i);
13843                        final int pid = r.pid;
13844                        if (!isCheckinRequest && dumpDetails) {
13845                            pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **");
13846                        }
13847                        if (mi == null) {
13848                            mi = new Debug.MemoryInfo();
13849                        }
13850                        if (dumpDetails || (!brief && !oomOnly)) {
13851                            Debug.getMemoryInfo(pid, mi);
13852                        } else {
13853                            mi.dalvikPss = (int)Debug.getPss(pid, tmpLong);
13854                            mi.dalvikPrivateDirty = (int)tmpLong[0];
13855                        }
13856                        ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails,
13857                                dumpDalvik, pid, r.baseName, 0, 0, 0, 0, 0, 0);
13858                        if (isCheckinRequest) {
13859                            pw.println();
13860                        }
13861                    }
13862                    return;
13863                }
13864            }
13865            pw.println("No process found for: " + args[opti]);
13866            return;
13867        }
13868
13869        if (!brief && !oomOnly && (procs.size() == 1 || isCheckinRequest)) {
13870            dumpDetails = true;
13871        }
13872
13873        dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact);
13874
13875        String[] innerArgs = new String[args.length-opti];
13876        System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
13877
13878        ArrayList<MemItem> procMems = new ArrayList<MemItem>();
13879        final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
13880        long nativePss=0, dalvikPss=0, otherPss=0;
13881        long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13882
13883        long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13884        ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
13885                new ArrayList[DUMP_MEM_OOM_LABEL.length];
13886
13887        long totalPss = 0;
13888        long cachedPss = 0;
13889
13890        Debug.MemoryInfo mi = null;
13891        for (int i = procs.size() - 1 ; i >= 0 ; i--) {
13892            final ProcessRecord r = procs.get(i);
13893            final IApplicationThread thread;
13894            final int pid;
13895            final int oomAdj;
13896            final boolean hasActivities;
13897            synchronized (this) {
13898                thread = r.thread;
13899                pid = r.pid;
13900                oomAdj = r.getSetAdjWithServices();
13901                hasActivities = r.activities.size() > 0;
13902            }
13903            if (thread != null) {
13904                if (!isCheckinRequest && dumpDetails) {
13905                    pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
13906                }
13907                if (mi == null) {
13908                    mi = new Debug.MemoryInfo();
13909                }
13910                if (dumpDetails || (!brief && !oomOnly)) {
13911                    Debug.getMemoryInfo(pid, mi);
13912                } else {
13913                    mi.dalvikPss = (int)Debug.getPss(pid, tmpLong);
13914                    mi.dalvikPrivateDirty = (int)tmpLong[0];
13915                }
13916                if (dumpDetails) {
13917                    if (localOnly) {
13918                        ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails,
13919                                dumpDalvik, pid, r.processName, 0, 0, 0, 0, 0, 0);
13920                        if (isCheckinRequest) {
13921                            pw.println();
13922                        }
13923                    } else {
13924                        try {
13925                            pw.flush();
13926                            thread.dumpMemInfo(fd, mi, isCheckinRequest, dumpFullDetails,
13927                                    dumpDalvik, innerArgs);
13928                        } catch (RemoteException e) {
13929                            if (!isCheckinRequest) {
13930                                pw.println("Got RemoteException!");
13931                                pw.flush();
13932                            }
13933                        }
13934                    }
13935                }
13936
13937                final long myTotalPss = mi.getTotalPss();
13938                final long myTotalUss = mi.getTotalUss();
13939
13940                synchronized (this) {
13941                    if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
13942                        // Record this for posterity if the process has been stable.
13943                        r.baseProcessTracker.addPss(myTotalPss, myTotalUss, true, r.pkgList);
13944                    }
13945                }
13946
13947                if (!isCheckinRequest && mi != null) {
13948                    totalPss += myTotalPss;
13949                    MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
13950                            (hasActivities ? " / activities)" : ")"),
13951                            r.processName, myTotalPss, pid, hasActivities);
13952                    procMems.add(pssItem);
13953                    procMemsMap.put(pid, pssItem);
13954
13955                    nativePss += mi.nativePss;
13956                    dalvikPss += mi.dalvikPss;
13957                    otherPss += mi.otherPss;
13958                    for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13959                        long mem = mi.getOtherPss(j);
13960                        miscPss[j] += mem;
13961                        otherPss -= mem;
13962                    }
13963
13964                    if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
13965                        cachedPss += myTotalPss;
13966                    }
13967
13968                    for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
13969                        if (oomAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
13970                                || oomIndex == (oomPss.length-1)) {
13971                            oomPss[oomIndex] += myTotalPss;
13972                            if (oomProcs[oomIndex] == null) {
13973                                oomProcs[oomIndex] = new ArrayList<MemItem>();
13974                            }
13975                            oomProcs[oomIndex].add(pssItem);
13976                            break;
13977                        }
13978                    }
13979                }
13980            }
13981        }
13982
13983        long nativeProcTotalPss = 0;
13984
13985        if (!isCheckinRequest && procs.size() > 1) {
13986            // If we are showing aggregations, also look for native processes to
13987            // include so that our aggregations are more accurate.
13988            updateCpuStatsNow();
13989            synchronized (mProcessCpuTracker) {
13990                final int N = mProcessCpuTracker.countStats();
13991                for (int i=0; i<N; i++) {
13992                    ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13993                    if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
13994                        if (mi == null) {
13995                            mi = new Debug.MemoryInfo();
13996                        }
13997                        if (!brief && !oomOnly) {
13998                            Debug.getMemoryInfo(st.pid, mi);
13999                        } else {
14000                            mi.nativePss = (int)Debug.getPss(st.pid, tmpLong);
14001                            mi.nativePrivateDirty = (int)tmpLong[0];
14002                        }
14003
14004                        final long myTotalPss = mi.getTotalPss();
14005                        totalPss += myTotalPss;
14006                        nativeProcTotalPss += myTotalPss;
14007
14008                        MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
14009                                st.name, myTotalPss, st.pid, false);
14010                        procMems.add(pssItem);
14011
14012                        nativePss += mi.nativePss;
14013                        dalvikPss += mi.dalvikPss;
14014                        otherPss += mi.otherPss;
14015                        for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
14016                            long mem = mi.getOtherPss(j);
14017                            miscPss[j] += mem;
14018                            otherPss -= mem;
14019                        }
14020                        oomPss[0] += myTotalPss;
14021                        if (oomProcs[0] == null) {
14022                            oomProcs[0] = new ArrayList<MemItem>();
14023                        }
14024                        oomProcs[0].add(pssItem);
14025                    }
14026                }
14027            }
14028
14029            ArrayList<MemItem> catMems = new ArrayList<MemItem>();
14030
14031            catMems.add(new MemItem("Native", "Native", nativePss, -1));
14032            catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
14033            catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
14034            for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
14035                String label = Debug.MemoryInfo.getOtherLabel(j);
14036                catMems.add(new MemItem(label, label, miscPss[j], j));
14037            }
14038
14039            ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
14040            for (int j=0; j<oomPss.length; j++) {
14041                if (oomPss[j] != 0) {
14042                    String label = isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
14043                            : DUMP_MEM_OOM_LABEL[j];
14044                    MemItem item = new MemItem(label, label, oomPss[j],
14045                            DUMP_MEM_OOM_ADJ[j]);
14046                    item.subitems = oomProcs[j];
14047                    oomMems.add(item);
14048                }
14049            }
14050
14051            if (!brief && !oomOnly && !isCompact) {
14052                pw.println();
14053                pw.println("Total PSS by process:");
14054                dumpMemItems(pw, "  ", "proc", procMems, true, isCompact);
14055                pw.println();
14056            }
14057            if (!isCompact) {
14058                pw.println("Total PSS by OOM adjustment:");
14059            }
14060            dumpMemItems(pw, "  ", "oom", oomMems, false, isCompact);
14061            if (!brief && !oomOnly) {
14062                PrintWriter out = categoryPw != null ? categoryPw : pw;
14063                if (!isCompact) {
14064                    out.println();
14065                    out.println("Total PSS by category:");
14066                }
14067                dumpMemItems(out, "  ", "cat", catMems, true, isCompact);
14068            }
14069            if (!isCompact) {
14070                pw.println();
14071            }
14072            MemInfoReader memInfo = new MemInfoReader();
14073            memInfo.readMemInfo();
14074            if (nativeProcTotalPss > 0) {
14075                synchronized (this) {
14076                    mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(),
14077                            memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(),
14078                            memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb()+memInfo.getSlabSizeKb(),
14079                            nativeProcTotalPss);
14080                }
14081            }
14082            if (!brief) {
14083                if (!isCompact) {
14084                    pw.print("Total RAM: "); pw.print(memInfo.getTotalSizeKb());
14085                    pw.print(" kB (status ");
14086                    switch (mLastMemoryLevel) {
14087                        case ProcessStats.ADJ_MEM_FACTOR_NORMAL:
14088                            pw.println("normal)");
14089                            break;
14090                        case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
14091                            pw.println("moderate)");
14092                            break;
14093                        case ProcessStats.ADJ_MEM_FACTOR_LOW:
14094                            pw.println("low)");
14095                            break;
14096                        case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
14097                            pw.println("critical)");
14098                            break;
14099                        default:
14100                            pw.print(mLastMemoryLevel);
14101                            pw.println(")");
14102                            break;
14103                    }
14104                    pw.print(" Free RAM: "); pw.print(cachedPss + memInfo.getCachedSizeKb()
14105                            + memInfo.getFreeSizeKb()); pw.print(" kB (");
14106                            pw.print(cachedPss); pw.print(" cached pss + ");
14107                            pw.print(memInfo.getCachedSizeKb()); pw.print(" cached + ");
14108                            pw.print(memInfo.getFreeSizeKb()); pw.println(" free)");
14109                } else {
14110                    pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
14111                    pw.print(cachedPss + memInfo.getCachedSizeKb()
14112                            + memInfo.getFreeSizeKb()); pw.print(",");
14113                    pw.println(totalPss - cachedPss);
14114                }
14115            }
14116            if (!isCompact) {
14117                pw.print(" Used RAM: "); pw.print(totalPss - cachedPss
14118                        + memInfo.getBuffersSizeKb() + memInfo.getShmemSizeKb()
14119                        + memInfo.getSlabSizeKb()); pw.print(" kB (");
14120                        pw.print(totalPss - cachedPss); pw.print(" used pss + ");
14121                        pw.print(memInfo.getBuffersSizeKb()); pw.print(" buffers + ");
14122                        pw.print(memInfo.getShmemSizeKb()); pw.print(" shmem + ");
14123                        pw.print(memInfo.getSlabSizeKb()); pw.println(" slab)");
14124                pw.print(" Lost RAM: "); pw.print(memInfo.getTotalSizeKb()
14125                        - totalPss - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
14126                        - memInfo.getBuffersSizeKb() - memInfo.getShmemSizeKb()
14127                        - memInfo.getSlabSizeKb()); pw.println(" kB");
14128            }
14129            if (!brief) {
14130                if (memInfo.getZramTotalSizeKb() != 0) {
14131                    if (!isCompact) {
14132                        pw.print("     ZRAM: "); pw.print(memInfo.getZramTotalSizeKb());
14133                                pw.print(" kB physical used for ");
14134                                pw.print(memInfo.getSwapTotalSizeKb()
14135                                        - memInfo.getSwapFreeSizeKb());
14136                                pw.print(" kB in swap (");
14137                                pw.print(memInfo.getSwapTotalSizeKb());
14138                                pw.println(" kB total swap)");
14139                    } else {
14140                        pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
14141                                pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
14142                                pw.println(memInfo.getSwapFreeSizeKb());
14143                    }
14144                }
14145                final int[] SINGLE_LONG_FORMAT = new int[] {
14146                    Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
14147                };
14148                long[] longOut = new long[1];
14149                Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
14150                        SINGLE_LONG_FORMAT, null, longOut, null);
14151                long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
14152                longOut[0] = 0;
14153                Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
14154                        SINGLE_LONG_FORMAT, null, longOut, null);
14155                long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
14156                longOut[0] = 0;
14157                Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
14158                        SINGLE_LONG_FORMAT, null, longOut, null);
14159                long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
14160                longOut[0] = 0;
14161                Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
14162                        SINGLE_LONG_FORMAT, null, longOut, null);
14163                long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
14164                if (!isCompact) {
14165                    if (sharing != 0 || shared != 0 || unshared != 0 || voltile != 0) {
14166                        pw.print("      KSM: "); pw.print(sharing);
14167                                pw.print(" kB saved from shared ");
14168                                pw.print(shared); pw.println(" kB");
14169                        pw.print("           "); pw.print(unshared); pw.print(" kB unshared; ");
14170                                pw.print(voltile); pw.println(" kB volatile");
14171                    }
14172                    pw.print("   Tuning: ");
14173                    pw.print(ActivityManager.staticGetMemoryClass());
14174                    pw.print(" (large ");
14175                    pw.print(ActivityManager.staticGetLargeMemoryClass());
14176                    pw.print("), oom ");
14177                    pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
14178                    pw.print(" kB");
14179                    pw.print(", restore limit ");
14180                    pw.print(mProcessList.getCachedRestoreThresholdKb());
14181                    pw.print(" kB");
14182                    if (ActivityManager.isLowRamDeviceStatic()) {
14183                        pw.print(" (low-ram)");
14184                    }
14185                    if (ActivityManager.isHighEndGfx()) {
14186                        pw.print(" (high-end-gfx)");
14187                    }
14188                    pw.println();
14189                } else {
14190                    pw.print("ksm,"); pw.print(sharing); pw.print(",");
14191                    pw.print(shared); pw.print(","); pw.print(unshared); pw.print(",");
14192                    pw.println(voltile);
14193                    pw.print("tuning,");
14194                    pw.print(ActivityManager.staticGetMemoryClass());
14195                    pw.print(',');
14196                    pw.print(ActivityManager.staticGetLargeMemoryClass());
14197                    pw.print(',');
14198                    pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
14199                    if (ActivityManager.isLowRamDeviceStatic()) {
14200                        pw.print(",low-ram");
14201                    }
14202                    if (ActivityManager.isHighEndGfx()) {
14203                        pw.print(",high-end-gfx");
14204                    }
14205                    pw.println();
14206                }
14207            }
14208        }
14209    }
14210
14211    /**
14212     * Searches array of arguments for the specified string
14213     * @param args array of argument strings
14214     * @param value value to search for
14215     * @return true if the value is contained in the array
14216     */
14217    private static boolean scanArgs(String[] args, String value) {
14218        if (args != null) {
14219            for (String arg : args) {
14220                if (value.equals(arg)) {
14221                    return true;
14222                }
14223            }
14224        }
14225        return false;
14226    }
14227
14228    private final boolean removeDyingProviderLocked(ProcessRecord proc,
14229            ContentProviderRecord cpr, boolean always) {
14230        final boolean inLaunching = mLaunchingProviders.contains(cpr);
14231
14232        if (!inLaunching || always) {
14233            synchronized (cpr) {
14234                cpr.launchingApp = null;
14235                cpr.notifyAll();
14236            }
14237            mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
14238            String names[] = cpr.info.authority.split(";");
14239            for (int j = 0; j < names.length; j++) {
14240                mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
14241            }
14242        }
14243
14244        for (int i=0; i<cpr.connections.size(); i++) {
14245            ContentProviderConnection conn = cpr.connections.get(i);
14246            if (conn.waiting) {
14247                // If this connection is waiting for the provider, then we don't
14248                // need to mess with its process unless we are always removing
14249                // or for some reason the provider is not currently launching.
14250                if (inLaunching && !always) {
14251                    continue;
14252                }
14253            }
14254            ProcessRecord capp = conn.client;
14255            conn.dead = true;
14256            if (conn.stableCount > 0) {
14257                if (!capp.persistent && capp.thread != null
14258                        && capp.pid != 0
14259                        && capp.pid != MY_PID) {
14260                    capp.kill("depends on provider "
14261                            + cpr.name.flattenToShortString()
14262                            + " in dying proc " + (proc != null ? proc.processName : "??"), true);
14263                }
14264            } else if (capp.thread != null && conn.provider.provider != null) {
14265                try {
14266                    capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
14267                } catch (RemoteException e) {
14268                }
14269                // In the protocol here, we don't expect the client to correctly
14270                // clean up this connection, we'll just remove it.
14271                cpr.connections.remove(i);
14272                conn.client.conProviders.remove(conn);
14273            }
14274        }
14275
14276        if (inLaunching && always) {
14277            mLaunchingProviders.remove(cpr);
14278        }
14279        return inLaunching;
14280    }
14281
14282    /**
14283     * Main code for cleaning up a process when it has gone away.  This is
14284     * called both as a result of the process dying, or directly when stopping
14285     * a process when running in single process mode.
14286     */
14287    private final void cleanUpApplicationRecordLocked(ProcessRecord app,
14288            boolean restarting, boolean allowRestart, int index) {
14289        if (index >= 0) {
14290            removeLruProcessLocked(app);
14291            ProcessList.remove(app.pid);
14292        }
14293
14294        mProcessesToGc.remove(app);
14295        mPendingPssProcesses.remove(app);
14296
14297        // Dismiss any open dialogs.
14298        if (app.crashDialog != null && !app.forceCrashReport) {
14299            app.crashDialog.dismiss();
14300            app.crashDialog = null;
14301        }
14302        if (app.anrDialog != null) {
14303            app.anrDialog.dismiss();
14304            app.anrDialog = null;
14305        }
14306        if (app.waitDialog != null) {
14307            app.waitDialog.dismiss();
14308            app.waitDialog = null;
14309        }
14310
14311        app.crashing = false;
14312        app.notResponding = false;
14313
14314        app.resetPackageList(mProcessStats);
14315        app.unlinkDeathRecipient();
14316        app.makeInactive(mProcessStats);
14317        app.waitingToKill = null;
14318        app.forcingToForeground = null;
14319        updateProcessForegroundLocked(app, false, false);
14320        app.foregroundActivities = false;
14321        app.hasShownUi = false;
14322        app.treatLikeActivity = false;
14323        app.hasAboveClient = false;
14324        app.hasClientActivities = false;
14325
14326        mServices.killServicesLocked(app, allowRestart);
14327
14328        boolean restart = false;
14329
14330        // Remove published content providers.
14331        for (int i=app.pubProviders.size()-1; i>=0; i--) {
14332            ContentProviderRecord cpr = app.pubProviders.valueAt(i);
14333            final boolean always = app.bad || !allowRestart;
14334            if (removeDyingProviderLocked(app, cpr, always) || always) {
14335                // We left the provider in the launching list, need to
14336                // restart it.
14337                restart = true;
14338            }
14339
14340            cpr.provider = null;
14341            cpr.proc = null;
14342        }
14343        app.pubProviders.clear();
14344
14345        // Take care of any launching providers waiting for this process.
14346        if (checkAppInLaunchingProvidersLocked(app, false)) {
14347            restart = true;
14348        }
14349
14350        // Unregister from connected content providers.
14351        if (!app.conProviders.isEmpty()) {
14352            for (int i=0; i<app.conProviders.size(); i++) {
14353                ContentProviderConnection conn = app.conProviders.get(i);
14354                conn.provider.connections.remove(conn);
14355            }
14356            app.conProviders.clear();
14357        }
14358
14359        // At this point there may be remaining entries in mLaunchingProviders
14360        // where we were the only one waiting, so they are no longer of use.
14361        // Look for these and clean up if found.
14362        // XXX Commented out for now.  Trying to figure out a way to reproduce
14363        // the actual situation to identify what is actually going on.
14364        if (false) {
14365            for (int i=0; i<mLaunchingProviders.size(); i++) {
14366                ContentProviderRecord cpr = (ContentProviderRecord)
14367                        mLaunchingProviders.get(i);
14368                if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
14369                    synchronized (cpr) {
14370                        cpr.launchingApp = null;
14371                        cpr.notifyAll();
14372                    }
14373                }
14374            }
14375        }
14376
14377        skipCurrentReceiverLocked(app);
14378
14379        // Unregister any receivers.
14380        for (int i=app.receivers.size()-1; i>=0; i--) {
14381            removeReceiverLocked(app.receivers.valueAt(i));
14382        }
14383        app.receivers.clear();
14384
14385        // If the app is undergoing backup, tell the backup manager about it
14386        if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
14387            if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
14388                    + mBackupTarget.appInfo + " died during backup");
14389            try {
14390                IBackupManager bm = IBackupManager.Stub.asInterface(
14391                        ServiceManager.getService(Context.BACKUP_SERVICE));
14392                bm.agentDisconnected(app.info.packageName);
14393            } catch (RemoteException e) {
14394                // can't happen; backup manager is local
14395            }
14396        }
14397
14398        for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
14399            ProcessChangeItem item = mPendingProcessChanges.get(i);
14400            if (item.pid == app.pid) {
14401                mPendingProcessChanges.remove(i);
14402                mAvailProcessChanges.add(item);
14403            }
14404        }
14405        mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
14406
14407        // If the caller is restarting this app, then leave it in its
14408        // current lists and let the caller take care of it.
14409        if (restarting) {
14410            return;
14411        }
14412
14413        if (!app.persistent || app.isolated) {
14414            if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
14415                    "Removing non-persistent process during cleanup: " + app);
14416            mProcessNames.remove(app.processName, app.uid);
14417            mIsolatedProcesses.remove(app.uid);
14418            if (mHeavyWeightProcess == app) {
14419                mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
14420                        mHeavyWeightProcess.userId, 0));
14421                mHeavyWeightProcess = null;
14422            }
14423        } else if (!app.removed) {
14424            // This app is persistent, so we need to keep its record around.
14425            // If it is not already on the pending app list, add it there
14426            // and start a new process for it.
14427            if (mPersistentStartingProcesses.indexOf(app) < 0) {
14428                mPersistentStartingProcesses.add(app);
14429                restart = true;
14430            }
14431        }
14432        if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
14433                "Clean-up removing on hold: " + app);
14434        mProcessesOnHold.remove(app);
14435
14436        if (app == mHomeProcess) {
14437            mHomeProcess = null;
14438        }
14439        if (app == mPreviousProcess) {
14440            mPreviousProcess = null;
14441        }
14442
14443        if (restart && !app.isolated) {
14444            // We have components that still need to be running in the
14445            // process, so re-launch it.
14446            mProcessNames.put(app.processName, app.uid, app);
14447            startProcessLocked(app, "restart", app.processName);
14448        } else if (app.pid > 0 && app.pid != MY_PID) {
14449            // Goodbye!
14450            boolean removed;
14451            synchronized (mPidsSelfLocked) {
14452                mPidsSelfLocked.remove(app.pid);
14453                mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
14454            }
14455            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
14456            if (app.isolated) {
14457                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
14458            }
14459            app.setPid(0);
14460        }
14461    }
14462
14463    boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
14464        // Look through the content providers we are waiting to have launched,
14465        // and if any run in this process then either schedule a restart of
14466        // the process or kill the client waiting for it if this process has
14467        // gone bad.
14468        int NL = mLaunchingProviders.size();
14469        boolean restart = false;
14470        for (int i=0; i<NL; i++) {
14471            ContentProviderRecord cpr = mLaunchingProviders.get(i);
14472            if (cpr.launchingApp == app) {
14473                if (!alwaysBad && !app.bad) {
14474                    restart = true;
14475                } else {
14476                    removeDyingProviderLocked(app, cpr, true);
14477                    // cpr should have been removed from mLaunchingProviders
14478                    NL = mLaunchingProviders.size();
14479                    i--;
14480                }
14481            }
14482        }
14483        return restart;
14484    }
14485
14486    // =========================================================
14487    // SERVICES
14488    // =========================================================
14489
14490    @Override
14491    public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
14492            int flags) {
14493        enforceNotIsolatedCaller("getServices");
14494        synchronized (this) {
14495            return mServices.getRunningServiceInfoLocked(maxNum, flags);
14496        }
14497    }
14498
14499    @Override
14500    public PendingIntent getRunningServiceControlPanel(ComponentName name) {
14501        enforceNotIsolatedCaller("getRunningServiceControlPanel");
14502        synchronized (this) {
14503            return mServices.getRunningServiceControlPanelLocked(name);
14504        }
14505    }
14506
14507    @Override
14508    public ComponentName startService(IApplicationThread caller, Intent service,
14509            String resolvedType, int userId) {
14510        enforceNotIsolatedCaller("startService");
14511        // Refuse possible leaked file descriptors
14512        if (service != null && service.hasFileDescriptors() == true) {
14513            throw new IllegalArgumentException("File descriptors passed in Intent");
14514        }
14515
14516        if (DEBUG_SERVICE)
14517            Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
14518        synchronized(this) {
14519            final int callingPid = Binder.getCallingPid();
14520            final int callingUid = Binder.getCallingUid();
14521            final long origId = Binder.clearCallingIdentity();
14522            ComponentName res = mServices.startServiceLocked(caller, service,
14523                    resolvedType, callingPid, callingUid, userId);
14524            Binder.restoreCallingIdentity(origId);
14525            return res;
14526        }
14527    }
14528
14529    ComponentName startServiceInPackage(int uid,
14530            Intent service, String resolvedType, int userId) {
14531        synchronized(this) {
14532            if (DEBUG_SERVICE)
14533                Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
14534            final long origId = Binder.clearCallingIdentity();
14535            ComponentName res = mServices.startServiceLocked(null, service,
14536                    resolvedType, -1, uid, userId);
14537            Binder.restoreCallingIdentity(origId);
14538            return res;
14539        }
14540    }
14541
14542    @Override
14543    public int stopService(IApplicationThread caller, Intent service,
14544            String resolvedType, int userId) {
14545        enforceNotIsolatedCaller("stopService");
14546        // Refuse possible leaked file descriptors
14547        if (service != null && service.hasFileDescriptors() == true) {
14548            throw new IllegalArgumentException("File descriptors passed in Intent");
14549        }
14550
14551        synchronized(this) {
14552            return mServices.stopServiceLocked(caller, service, resolvedType, userId);
14553        }
14554    }
14555
14556    @Override
14557    public IBinder peekService(Intent service, String resolvedType) {
14558        enforceNotIsolatedCaller("peekService");
14559        // Refuse possible leaked file descriptors
14560        if (service != null && service.hasFileDescriptors() == true) {
14561            throw new IllegalArgumentException("File descriptors passed in Intent");
14562        }
14563        synchronized(this) {
14564            return mServices.peekServiceLocked(service, resolvedType);
14565        }
14566    }
14567
14568    @Override
14569    public boolean stopServiceToken(ComponentName className, IBinder token,
14570            int startId) {
14571        synchronized(this) {
14572            return mServices.stopServiceTokenLocked(className, token, startId);
14573        }
14574    }
14575
14576    @Override
14577    public void setServiceForeground(ComponentName className, IBinder token,
14578            int id, Notification notification, boolean removeNotification) {
14579        synchronized(this) {
14580            mServices.setServiceForegroundLocked(className, token, id, notification,
14581                    removeNotification);
14582        }
14583    }
14584
14585    @Override
14586    public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
14587            boolean requireFull, String name, String callerPackage) {
14588        return handleIncomingUser(callingPid, callingUid, userId, allowAll,
14589                requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
14590    }
14591
14592    int unsafeConvertIncomingUser(int userId) {
14593        return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
14594                ? mCurrentUserId : userId;
14595    }
14596
14597    int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
14598            int allowMode, String name, String callerPackage) {
14599        final int callingUserId = UserHandle.getUserId(callingUid);
14600        if (callingUserId == userId) {
14601            return userId;
14602        }
14603
14604        // Note that we may be accessing mCurrentUserId outside of a lock...
14605        // shouldn't be a big deal, if this is being called outside
14606        // of a locked context there is intrinsically a race with
14607        // the value the caller will receive and someone else changing it.
14608        // We assume that USER_CURRENT_OR_SELF will use the current user; later
14609        // we will switch to the calling user if access to the current user fails.
14610        int targetUserId = unsafeConvertIncomingUser(userId);
14611
14612        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14613            final boolean allow;
14614            if (checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
14615                    callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
14616                // If the caller has this permission, they always pass go.  And collect $200.
14617                allow = true;
14618            } else if (allowMode == ALLOW_FULL_ONLY) {
14619                // We require full access, sucks to be you.
14620                allow = false;
14621            } else if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
14622                    callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
14623                // If the caller does not have either permission, they are always doomed.
14624                allow = false;
14625            } else if (allowMode == ALLOW_NON_FULL) {
14626                // We are blanket allowing non-full access, you lucky caller!
14627                allow = true;
14628            } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
14629                // We may or may not allow this depending on whether the two users are
14630                // in the same profile.
14631                synchronized (mUserProfileGroupIdsSelfLocked) {
14632                    int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
14633                            UserInfo.NO_PROFILE_GROUP_ID);
14634                    int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
14635                            UserInfo.NO_PROFILE_GROUP_ID);
14636                    allow = callingProfile != UserInfo.NO_PROFILE_GROUP_ID
14637                            && callingProfile == targetProfile;
14638                }
14639            } else {
14640                throw new IllegalArgumentException("Unknown mode: " + allowMode);
14641            }
14642            if (!allow) {
14643                if (userId == UserHandle.USER_CURRENT_OR_SELF) {
14644                    // In this case, they would like to just execute as their
14645                    // owner user instead of failing.
14646                    targetUserId = callingUserId;
14647                } else {
14648                    StringBuilder builder = new StringBuilder(128);
14649                    builder.append("Permission Denial: ");
14650                    builder.append(name);
14651                    if (callerPackage != null) {
14652                        builder.append(" from ");
14653                        builder.append(callerPackage);
14654                    }
14655                    builder.append(" asks to run as user ");
14656                    builder.append(userId);
14657                    builder.append(" but is calling from user ");
14658                    builder.append(UserHandle.getUserId(callingUid));
14659                    builder.append("; this requires ");
14660                    builder.append(INTERACT_ACROSS_USERS_FULL);
14661                    if (allowMode != ALLOW_FULL_ONLY) {
14662                        builder.append(" or ");
14663                        builder.append(INTERACT_ACROSS_USERS);
14664                    }
14665                    String msg = builder.toString();
14666                    Slog.w(TAG, msg);
14667                    throw new SecurityException(msg);
14668                }
14669            }
14670        }
14671        if (!allowAll && targetUserId < 0) {
14672            throw new IllegalArgumentException(
14673                    "Call does not support special user #" + targetUserId);
14674        }
14675        // Check shell permission
14676        if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_OWNER) {
14677            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
14678                    targetUserId)) {
14679                throw new SecurityException("Shell does not have permission to access user "
14680                        + targetUserId + "\n " + Debug.getCallers(3));
14681            }
14682        }
14683        return targetUserId;
14684    }
14685
14686    boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
14687            String className, int flags) {
14688        boolean result = false;
14689        // For apps that don't have pre-defined UIDs, check for permission
14690        if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
14691            if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
14692                if (ActivityManager.checkUidPermission(
14693                        INTERACT_ACROSS_USERS,
14694                        aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
14695                    ComponentName comp = new ComponentName(aInfo.packageName, className);
14696                    String msg = "Permission Denial: Component " + comp.flattenToShortString()
14697                            + " requests FLAG_SINGLE_USER, but app does not hold "
14698                            + INTERACT_ACROSS_USERS;
14699                    Slog.w(TAG, msg);
14700                    throw new SecurityException(msg);
14701                }
14702                // Permission passed
14703                result = true;
14704            }
14705        } else if ("system".equals(componentProcessName)) {
14706            result = true;
14707        } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
14708            // Phone app and persistent apps are allowed to export singleuser providers.
14709            result = UserHandle.isSameApp(aInfo.uid, Process.PHONE_UID)
14710                    || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
14711        }
14712        if (DEBUG_MU) {
14713            Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
14714                    + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
14715        }
14716        return result;
14717    }
14718
14719    /**
14720     * Checks to see if the caller is in the same app as the singleton
14721     * component, or the component is in a special app. It allows special apps
14722     * to export singleton components but prevents exporting singleton
14723     * components for regular apps.
14724     */
14725    boolean isValidSingletonCall(int callingUid, int componentUid) {
14726        int componentAppId = UserHandle.getAppId(componentUid);
14727        return UserHandle.isSameApp(callingUid, componentUid)
14728                || componentAppId == Process.SYSTEM_UID
14729                || componentAppId == Process.PHONE_UID
14730                || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
14731                        == PackageManager.PERMISSION_GRANTED;
14732    }
14733
14734    public int bindService(IApplicationThread caller, IBinder token,
14735            Intent service, String resolvedType,
14736            IServiceConnection connection, int flags, int userId) {
14737        enforceNotIsolatedCaller("bindService");
14738
14739        // Refuse possible leaked file descriptors
14740        if (service != null && service.hasFileDescriptors() == true) {
14741            throw new IllegalArgumentException("File descriptors passed in Intent");
14742        }
14743
14744        synchronized(this) {
14745            return mServices.bindServiceLocked(caller, token, service, resolvedType,
14746                    connection, flags, userId);
14747        }
14748    }
14749
14750    public boolean unbindService(IServiceConnection connection) {
14751        synchronized (this) {
14752            return mServices.unbindServiceLocked(connection);
14753        }
14754    }
14755
14756    public void publishService(IBinder token, Intent intent, IBinder service) {
14757        // Refuse possible leaked file descriptors
14758        if (intent != null && intent.hasFileDescriptors() == true) {
14759            throw new IllegalArgumentException("File descriptors passed in Intent");
14760        }
14761
14762        synchronized(this) {
14763            if (!(token instanceof ServiceRecord)) {
14764                throw new IllegalArgumentException("Invalid service token");
14765            }
14766            mServices.publishServiceLocked((ServiceRecord)token, intent, service);
14767        }
14768    }
14769
14770    public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
14771        // Refuse possible leaked file descriptors
14772        if (intent != null && intent.hasFileDescriptors() == true) {
14773            throw new IllegalArgumentException("File descriptors passed in Intent");
14774        }
14775
14776        synchronized(this) {
14777            mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
14778        }
14779    }
14780
14781    public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
14782        synchronized(this) {
14783            if (!(token instanceof ServiceRecord)) {
14784                throw new IllegalArgumentException("Invalid service token");
14785            }
14786            mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
14787        }
14788    }
14789
14790    // =========================================================
14791    // BACKUP AND RESTORE
14792    // =========================================================
14793
14794    // Cause the target app to be launched if necessary and its backup agent
14795    // instantiated.  The backup agent will invoke backupAgentCreated() on the
14796    // activity manager to announce its creation.
14797    public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
14798        if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
14799        enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
14800
14801        synchronized(this) {
14802            // !!! TODO: currently no check here that we're already bound
14803            BatteryStatsImpl.Uid.Pkg.Serv ss = null;
14804            BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14805            synchronized (stats) {
14806                ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
14807            }
14808
14809            // Backup agent is now in use, its package can't be stopped.
14810            try {
14811                AppGlobals.getPackageManager().setPackageStoppedState(
14812                        app.packageName, false, UserHandle.getUserId(app.uid));
14813            } catch (RemoteException e) {
14814            } catch (IllegalArgumentException e) {
14815                Slog.w(TAG, "Failed trying to unstop package "
14816                        + app.packageName + ": " + e);
14817            }
14818
14819            BackupRecord r = new BackupRecord(ss, app, backupMode);
14820            ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
14821                    ? new ComponentName(app.packageName, app.backupAgentName)
14822                    : new ComponentName("android", "FullBackupAgent");
14823            // startProcessLocked() returns existing proc's record if it's already running
14824            ProcessRecord proc = startProcessLocked(app.processName, app,
14825                    false, 0, "backup", hostingName, false, false, false);
14826            if (proc == null) {
14827                Slog.e(TAG, "Unable to start backup agent process " + r);
14828                return false;
14829            }
14830
14831            r.app = proc;
14832            mBackupTarget = r;
14833            mBackupAppName = app.packageName;
14834
14835            // Try not to kill the process during backup
14836            updateOomAdjLocked(proc);
14837
14838            // If the process is already attached, schedule the creation of the backup agent now.
14839            // If it is not yet live, this will be done when it attaches to the framework.
14840            if (proc.thread != null) {
14841                if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
14842                try {
14843                    proc.thread.scheduleCreateBackupAgent(app,
14844                            compatibilityInfoForPackageLocked(app), backupMode);
14845                } catch (RemoteException e) {
14846                    // Will time out on the backup manager side
14847                }
14848            } else {
14849                if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
14850            }
14851            // Invariants: at this point, the target app process exists and the application
14852            // is either already running or in the process of coming up.  mBackupTarget and
14853            // mBackupAppName describe the app, so that when it binds back to the AM we
14854            // know that it's scheduled for a backup-agent operation.
14855        }
14856
14857        return true;
14858    }
14859
14860    @Override
14861    public void clearPendingBackup() {
14862        if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
14863        enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
14864
14865        synchronized (this) {
14866            mBackupTarget = null;
14867            mBackupAppName = null;
14868        }
14869    }
14870
14871    // A backup agent has just come up
14872    public void backupAgentCreated(String agentPackageName, IBinder agent) {
14873        if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
14874                + " = " + agent);
14875
14876        synchronized(this) {
14877            if (!agentPackageName.equals(mBackupAppName)) {
14878                Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
14879                return;
14880            }
14881        }
14882
14883        long oldIdent = Binder.clearCallingIdentity();
14884        try {
14885            IBackupManager bm = IBackupManager.Stub.asInterface(
14886                    ServiceManager.getService(Context.BACKUP_SERVICE));
14887            bm.agentConnected(agentPackageName, agent);
14888        } catch (RemoteException e) {
14889            // can't happen; the backup manager service is local
14890        } catch (Exception e) {
14891            Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
14892            e.printStackTrace();
14893        } finally {
14894            Binder.restoreCallingIdentity(oldIdent);
14895        }
14896    }
14897
14898    // done with this agent
14899    public void unbindBackupAgent(ApplicationInfo appInfo) {
14900        if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
14901        if (appInfo == null) {
14902            Slog.w(TAG, "unbind backup agent for null app");
14903            return;
14904        }
14905
14906        synchronized(this) {
14907            try {
14908                if (mBackupAppName == null) {
14909                    Slog.w(TAG, "Unbinding backup agent with no active backup");
14910                    return;
14911                }
14912
14913                if (!mBackupAppName.equals(appInfo.packageName)) {
14914                    Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
14915                    return;
14916                }
14917
14918                // Not backing this app up any more; reset its OOM adjustment
14919                final ProcessRecord proc = mBackupTarget.app;
14920                updateOomAdjLocked(proc);
14921
14922                // If the app crashed during backup, 'thread' will be null here
14923                if (proc.thread != null) {
14924                    try {
14925                        proc.thread.scheduleDestroyBackupAgent(appInfo,
14926                                compatibilityInfoForPackageLocked(appInfo));
14927                    } catch (Exception e) {
14928                        Slog.e(TAG, "Exception when unbinding backup agent:");
14929                        e.printStackTrace();
14930                    }
14931                }
14932            } finally {
14933                mBackupTarget = null;
14934                mBackupAppName = null;
14935            }
14936        }
14937    }
14938    // =========================================================
14939    // BROADCASTS
14940    // =========================================================
14941
14942    private final List getStickiesLocked(String action, IntentFilter filter,
14943            List cur, int userId) {
14944        final ContentResolver resolver = mContext.getContentResolver();
14945        ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
14946        if (stickies == null) {
14947            return cur;
14948        }
14949        final ArrayList<Intent> list = stickies.get(action);
14950        if (list == null) {
14951            return cur;
14952        }
14953        int N = list.size();
14954        for (int i=0; i<N; i++) {
14955            Intent intent = list.get(i);
14956            if (filter.match(resolver, intent, true, TAG) >= 0) {
14957                if (cur == null) {
14958                    cur = new ArrayList<Intent>();
14959                }
14960                cur.add(intent);
14961            }
14962        }
14963        return cur;
14964    }
14965
14966    boolean isPendingBroadcastProcessLocked(int pid) {
14967        return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
14968                || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
14969    }
14970
14971    void skipPendingBroadcastLocked(int pid) {
14972            Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
14973            for (BroadcastQueue queue : mBroadcastQueues) {
14974                queue.skipPendingBroadcastLocked(pid);
14975            }
14976    }
14977
14978    // The app just attached; send any pending broadcasts that it should receive
14979    boolean sendPendingBroadcastsLocked(ProcessRecord app) {
14980        boolean didSomething = false;
14981        for (BroadcastQueue queue : mBroadcastQueues) {
14982            didSomething |= queue.sendPendingBroadcastsLocked(app);
14983        }
14984        return didSomething;
14985    }
14986
14987    public Intent registerReceiver(IApplicationThread caller, String callerPackage,
14988            IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
14989        enforceNotIsolatedCaller("registerReceiver");
14990        int callingUid;
14991        int callingPid;
14992        synchronized(this) {
14993            ProcessRecord callerApp = null;
14994            if (caller != null) {
14995                callerApp = getRecordForAppLocked(caller);
14996                if (callerApp == null) {
14997                    throw new SecurityException(
14998                            "Unable to find app for caller " + caller
14999                            + " (pid=" + Binder.getCallingPid()
15000                            + ") when registering receiver " + receiver);
15001                }
15002                if (callerApp.info.uid != Process.SYSTEM_UID &&
15003                        !callerApp.pkgList.containsKey(callerPackage) &&
15004                        !"android".equals(callerPackage)) {
15005                    throw new SecurityException("Given caller package " + callerPackage
15006                            + " is not running in process " + callerApp);
15007                }
15008                callingUid = callerApp.info.uid;
15009                callingPid = callerApp.pid;
15010            } else {
15011                callerPackage = null;
15012                callingUid = Binder.getCallingUid();
15013                callingPid = Binder.getCallingPid();
15014            }
15015
15016            userId = this.handleIncomingUser(callingPid, callingUid, userId,
15017                    true, ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
15018
15019            List allSticky = null;
15020
15021            // Look for any matching sticky broadcasts...
15022            Iterator actions = filter.actionsIterator();
15023            if (actions != null) {
15024                while (actions.hasNext()) {
15025                    String action = (String)actions.next();
15026                    allSticky = getStickiesLocked(action, filter, allSticky,
15027                            UserHandle.USER_ALL);
15028                    allSticky = getStickiesLocked(action, filter, allSticky,
15029                            UserHandle.getUserId(callingUid));
15030                }
15031            } else {
15032                allSticky = getStickiesLocked(null, filter, allSticky,
15033                        UserHandle.USER_ALL);
15034                allSticky = getStickiesLocked(null, filter, allSticky,
15035                        UserHandle.getUserId(callingUid));
15036            }
15037
15038            // The first sticky in the list is returned directly back to
15039            // the client.
15040            Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
15041
15042            if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
15043                    + ": " + sticky);
15044
15045            if (receiver == null) {
15046                return sticky;
15047            }
15048
15049            ReceiverList rl
15050                = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
15051            if (rl == null) {
15052                rl = new ReceiverList(this, callerApp, callingPid, callingUid,
15053                        userId, receiver);
15054                if (rl.app != null) {
15055                    rl.app.receivers.add(rl);
15056                } else {
15057                    try {
15058                        receiver.asBinder().linkToDeath(rl, 0);
15059                    } catch (RemoteException e) {
15060                        return sticky;
15061                    }
15062                    rl.linkedToDeath = true;
15063                }
15064                mRegisteredReceivers.put(receiver.asBinder(), rl);
15065            } else if (rl.uid != callingUid) {
15066                throw new IllegalArgumentException(
15067                        "Receiver requested to register for uid " + callingUid
15068                        + " was previously registered for uid " + rl.uid);
15069            } else if (rl.pid != callingPid) {
15070                throw new IllegalArgumentException(
15071                        "Receiver requested to register for pid " + callingPid
15072                        + " was previously registered for pid " + rl.pid);
15073            } else if (rl.userId != userId) {
15074                throw new IllegalArgumentException(
15075                        "Receiver requested to register for user " + userId
15076                        + " was previously registered for user " + rl.userId);
15077            }
15078            BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
15079                    permission, callingUid, userId);
15080            rl.add(bf);
15081            if (!bf.debugCheck()) {
15082                Slog.w(TAG, "==> For Dynamic broadast");
15083            }
15084            mReceiverResolver.addFilter(bf);
15085
15086            // Enqueue broadcasts for all existing stickies that match
15087            // this filter.
15088            if (allSticky != null) {
15089                ArrayList receivers = new ArrayList();
15090                receivers.add(bf);
15091
15092                int N = allSticky.size();
15093                for (int i=0; i<N; i++) {
15094                    Intent intent = (Intent)allSticky.get(i);
15095                    BroadcastQueue queue = broadcastQueueForIntent(intent);
15096                    BroadcastRecord r = new BroadcastRecord(queue, intent, null,
15097                            null, -1, -1, null, null, AppOpsManager.OP_NONE, receivers, null, 0,
15098                            null, null, false, true, true, -1);
15099                    queue.enqueueParallelBroadcastLocked(r);
15100                    queue.scheduleBroadcastsLocked();
15101                }
15102            }
15103
15104            return sticky;
15105        }
15106    }
15107
15108    public void unregisterReceiver(IIntentReceiver receiver) {
15109        if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
15110
15111        final long origId = Binder.clearCallingIdentity();
15112        try {
15113            boolean doTrim = false;
15114
15115            synchronized(this) {
15116                ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
15117                if (rl != null) {
15118                    if (rl.curBroadcast != null) {
15119                        BroadcastRecord r = rl.curBroadcast;
15120                        final boolean doNext = finishReceiverLocked(
15121                                receiver.asBinder(), r.resultCode, r.resultData,
15122                                r.resultExtras, r.resultAbort);
15123                        if (doNext) {
15124                            doTrim = true;
15125                            r.queue.processNextBroadcast(false);
15126                        }
15127                    }
15128
15129                    if (rl.app != null) {
15130                        rl.app.receivers.remove(rl);
15131                    }
15132                    removeReceiverLocked(rl);
15133                    if (rl.linkedToDeath) {
15134                        rl.linkedToDeath = false;
15135                        rl.receiver.asBinder().unlinkToDeath(rl, 0);
15136                    }
15137                }
15138            }
15139
15140            // If we actually concluded any broadcasts, we might now be able
15141            // to trim the recipients' apps from our working set
15142            if (doTrim) {
15143                trimApplications();
15144                return;
15145            }
15146
15147        } finally {
15148            Binder.restoreCallingIdentity(origId);
15149        }
15150    }
15151
15152    void removeReceiverLocked(ReceiverList rl) {
15153        mRegisteredReceivers.remove(rl.receiver.asBinder());
15154        int N = rl.size();
15155        for (int i=0; i<N; i++) {
15156            mReceiverResolver.removeFilter(rl.get(i));
15157        }
15158    }
15159
15160    private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
15161        for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
15162            ProcessRecord r = mLruProcesses.get(i);
15163            if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
15164                try {
15165                    r.thread.dispatchPackageBroadcast(cmd, packages);
15166                } catch (RemoteException ex) {
15167                }
15168            }
15169        }
15170    }
15171
15172    private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
15173            int callingUid, int[] users) {
15174        List<ResolveInfo> receivers = null;
15175        try {
15176            HashSet<ComponentName> singleUserReceivers = null;
15177            boolean scannedFirstReceivers = false;
15178            for (int user : users) {
15179                // Skip users that have Shell restrictions
15180                if (callingUid == Process.SHELL_UID
15181                        && getUserManagerLocked().hasUserRestriction(
15182                                UserManager.DISALLOW_DEBUGGING_FEATURES, user)) {
15183                    continue;
15184                }
15185                List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
15186                        .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
15187                if (user != 0 && newReceivers != null) {
15188                    // If this is not the primary user, we need to check for
15189                    // any receivers that should be filtered out.
15190                    for (int i=0; i<newReceivers.size(); i++) {
15191                        ResolveInfo ri = newReceivers.get(i);
15192                        if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
15193                            newReceivers.remove(i);
15194                            i--;
15195                        }
15196                    }
15197                }
15198                if (newReceivers != null && newReceivers.size() == 0) {
15199                    newReceivers = null;
15200                }
15201                if (receivers == null) {
15202                    receivers = newReceivers;
15203                } else if (newReceivers != null) {
15204                    // We need to concatenate the additional receivers
15205                    // found with what we have do far.  This would be easy,
15206                    // but we also need to de-dup any receivers that are
15207                    // singleUser.
15208                    if (!scannedFirstReceivers) {
15209                        // Collect any single user receivers we had already retrieved.
15210                        scannedFirstReceivers = true;
15211                        for (int i=0; i<receivers.size(); i++) {
15212                            ResolveInfo ri = receivers.get(i);
15213                            if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
15214                                ComponentName cn = new ComponentName(
15215                                        ri.activityInfo.packageName, ri.activityInfo.name);
15216                                if (singleUserReceivers == null) {
15217                                    singleUserReceivers = new HashSet<ComponentName>();
15218                                }
15219                                singleUserReceivers.add(cn);
15220                            }
15221                        }
15222                    }
15223                    // Add the new results to the existing results, tracking
15224                    // and de-dupping single user receivers.
15225                    for (int i=0; i<newReceivers.size(); i++) {
15226                        ResolveInfo ri = newReceivers.get(i);
15227                        if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
15228                            ComponentName cn = new ComponentName(
15229                                    ri.activityInfo.packageName, ri.activityInfo.name);
15230                            if (singleUserReceivers == null) {
15231                                singleUserReceivers = new HashSet<ComponentName>();
15232                            }
15233                            if (!singleUserReceivers.contains(cn)) {
15234                                singleUserReceivers.add(cn);
15235                                receivers.add(ri);
15236                            }
15237                        } else {
15238                            receivers.add(ri);
15239                        }
15240                    }
15241                }
15242            }
15243        } catch (RemoteException ex) {
15244            // pm is in same process, this will never happen.
15245        }
15246        return receivers;
15247    }
15248
15249    private final int broadcastIntentLocked(ProcessRecord callerApp,
15250            String callerPackage, Intent intent, String resolvedType,
15251            IIntentReceiver resultTo, int resultCode, String resultData,
15252            Bundle map, String requiredPermission, int appOp,
15253            boolean ordered, boolean sticky, int callingPid, int callingUid,
15254            int userId) {
15255        intent = new Intent(intent);
15256
15257        // By default broadcasts do not go to stopped apps.
15258        intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
15259
15260        if (DEBUG_BROADCAST_LIGHT) Slog.v(
15261            TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
15262            + " ordered=" + ordered + " userid=" + userId);
15263        if ((resultTo != null) && !ordered) {
15264            Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
15265        }
15266
15267        userId = handleIncomingUser(callingPid, callingUid, userId,
15268                true, ALLOW_NON_FULL, "broadcast", callerPackage);
15269
15270        // Make sure that the user who is receiving this broadcast is started.
15271        // If not, we will just skip it.
15272
15273        if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
15274            if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
15275                    & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
15276                Slog.w(TAG, "Skipping broadcast of " + intent
15277                        + ": user " + userId + " is stopped");
15278                return ActivityManager.BROADCAST_SUCCESS;
15279            }
15280        }
15281
15282        /*
15283         * Prevent non-system code (defined here to be non-persistent
15284         * processes) from sending protected broadcasts.
15285         */
15286        int callingAppId = UserHandle.getAppId(callingUid);
15287        if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
15288            || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID
15289            || callingAppId == Process.NFC_UID || callingUid == 0) {
15290            // Always okay.
15291        } else if (callerApp == null || !callerApp.persistent) {
15292            try {
15293                if (AppGlobals.getPackageManager().isProtectedBroadcast(
15294                        intent.getAction())) {
15295                    String msg = "Permission Denial: not allowed to send broadcast "
15296                            + intent.getAction() + " from pid="
15297                            + callingPid + ", uid=" + callingUid;
15298                    Slog.w(TAG, msg);
15299                    throw new SecurityException(msg);
15300                } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) {
15301                    // Special case for compatibility: we don't want apps to send this,
15302                    // but historically it has not been protected and apps may be using it
15303                    // to poke their own app widget.  So, instead of making it protected,
15304                    // just limit it to the caller.
15305                    if (callerApp == null) {
15306                        String msg = "Permission Denial: not allowed to send broadcast "
15307                                + intent.getAction() + " from unknown caller.";
15308                        Slog.w(TAG, msg);
15309                        throw new SecurityException(msg);
15310                    } else if (intent.getComponent() != null) {
15311                        // They are good enough to send to an explicit component...  verify
15312                        // it is being sent to the calling app.
15313                        if (!intent.getComponent().getPackageName().equals(
15314                                callerApp.info.packageName)) {
15315                            String msg = "Permission Denial: not allowed to send broadcast "
15316                                    + intent.getAction() + " to "
15317                                    + intent.getComponent().getPackageName() + " from "
15318                                    + callerApp.info.packageName;
15319                            Slog.w(TAG, msg);
15320                            throw new SecurityException(msg);
15321                        }
15322                    } else {
15323                        // Limit broadcast to their own package.
15324                        intent.setPackage(callerApp.info.packageName);
15325                    }
15326                }
15327            } catch (RemoteException e) {
15328                Slog.w(TAG, "Remote exception", e);
15329                return ActivityManager.BROADCAST_SUCCESS;
15330            }
15331        }
15332
15333        // Handle special intents: if this broadcast is from the package
15334        // manager about a package being removed, we need to remove all of
15335        // its activities from the history stack.
15336        final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
15337                intent.getAction());
15338        if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
15339                || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
15340                || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
15341                || Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())
15342                || uidRemoved) {
15343            if (checkComponentPermission(
15344                    android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
15345                    callingPid, callingUid, -1, true)
15346                    == PackageManager.PERMISSION_GRANTED) {
15347                if (uidRemoved) {
15348                    final Bundle intentExtras = intent.getExtras();
15349                    final int uid = intentExtras != null
15350                            ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
15351                    if (uid >= 0) {
15352                        BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
15353                        synchronized (bs) {
15354                            bs.removeUidStatsLocked(uid);
15355                        }
15356                        mAppOpsService.uidRemoved(uid);
15357                    }
15358                } else {
15359                    // If resources are unavailable just force stop all
15360                    // those packages and flush the attribute cache as well.
15361                    if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
15362                        String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15363                        if (list != null && (list.length > 0)) {
15364                            for (String pkg : list) {
15365                                forceStopPackageLocked(pkg, -1, false, true, true, false, false, userId,
15366                                        "storage unmount");
15367                            }
15368                            cleanupRecentTasksLocked(UserHandle.USER_ALL);
15369                            sendPackageBroadcastLocked(
15370                                    IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
15371                        }
15372                    } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(
15373                            intent.getAction())) {
15374                        cleanupRecentTasksLocked(UserHandle.USER_ALL);
15375                    } else {
15376                        Uri data = intent.getData();
15377                        String ssp;
15378                        if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
15379                            boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(
15380                                    intent.getAction());
15381                            boolean fullUninstall = removed &&
15382                                    !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
15383                            if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
15384                                forceStopPackageLocked(ssp, UserHandle.getAppId(
15385                                        intent.getIntExtra(Intent.EXTRA_UID, -1)), false, true, true,
15386                                        false, fullUninstall, userId,
15387                                        removed ? "pkg removed" : "pkg changed");
15388                            }
15389                            if (removed) {
15390                                sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
15391                                        new String[] {ssp}, userId);
15392                                if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
15393                                    mAppOpsService.packageRemoved(
15394                                            intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
15395
15396                                    // Remove all permissions granted from/to this package
15397                                    removeUriPermissionsForPackageLocked(ssp, userId, true);
15398                                }
15399                            }
15400                        }
15401                    }
15402                }
15403            } else {
15404                String msg = "Permission Denial: " + intent.getAction()
15405                        + " broadcast from " + callerPackage + " (pid=" + callingPid
15406                        + ", uid=" + callingUid + ")"
15407                        + " requires "
15408                        + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
15409                Slog.w(TAG, msg);
15410                throw new SecurityException(msg);
15411            }
15412
15413        // Special case for adding a package: by default turn on compatibility
15414        // mode.
15415        } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
15416            Uri data = intent.getData();
15417            String ssp;
15418            if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
15419                mCompatModePackages.handlePackageAddedLocked(ssp,
15420                        intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
15421            }
15422        }
15423
15424        /*
15425         * If this is the time zone changed action, queue up a message that will reset the timezone
15426         * of all currently running processes. This message will get queued up before the broadcast
15427         * happens.
15428         */
15429        if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
15430            mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
15431        }
15432
15433        /*
15434         * If the user set the time, let all running processes know.
15435         */
15436        if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
15437            final int is24Hour = intent.getBooleanExtra(
15438                    Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, false) ? 1 : 0;
15439            mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TIME, is24Hour, 0));
15440            BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
15441            synchronized (stats) {
15442                stats.noteCurrentTimeChangedLocked();
15443            }
15444        }
15445
15446        if (Intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
15447            mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
15448        }
15449
15450        if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
15451            ProxyInfo proxy = intent.getParcelableExtra(Proxy.EXTRA_PROXY_INFO);
15452            mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy));
15453        }
15454
15455        // Add to the sticky list if requested.
15456        if (sticky) {
15457            if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
15458                    callingPid, callingUid)
15459                    != PackageManager.PERMISSION_GRANTED) {
15460                String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
15461                        + callingPid + ", uid=" + callingUid
15462                        + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15463                Slog.w(TAG, msg);
15464                throw new SecurityException(msg);
15465            }
15466            if (requiredPermission != null) {
15467                Slog.w(TAG, "Can't broadcast sticky intent " + intent
15468                        + " and enforce permission " + requiredPermission);
15469                return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
15470            }
15471            if (intent.getComponent() != null) {
15472                throw new SecurityException(
15473                        "Sticky broadcasts can't target a specific component");
15474            }
15475            // We use userId directly here, since the "all" target is maintained
15476            // as a separate set of sticky broadcasts.
15477            if (userId != UserHandle.USER_ALL) {
15478                // But first, if this is not a broadcast to all users, then
15479                // make sure it doesn't conflict with an existing broadcast to
15480                // all users.
15481                ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
15482                        UserHandle.USER_ALL);
15483                if (stickies != null) {
15484                    ArrayList<Intent> list = stickies.get(intent.getAction());
15485                    if (list != null) {
15486                        int N = list.size();
15487                        int i;
15488                        for (i=0; i<N; i++) {
15489                            if (intent.filterEquals(list.get(i))) {
15490                                throw new IllegalArgumentException(
15491                                        "Sticky broadcast " + intent + " for user "
15492                                        + userId + " conflicts with existing global broadcast");
15493                            }
15494                        }
15495                    }
15496                }
15497            }
15498            ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
15499            if (stickies == null) {
15500                stickies = new ArrayMap<String, ArrayList<Intent>>();
15501                mStickyBroadcasts.put(userId, stickies);
15502            }
15503            ArrayList<Intent> list = stickies.get(intent.getAction());
15504            if (list == null) {
15505                list = new ArrayList<Intent>();
15506                stickies.put(intent.getAction(), list);
15507            }
15508            int N = list.size();
15509            int i;
15510            for (i=0; i<N; i++) {
15511                if (intent.filterEquals(list.get(i))) {
15512                    // This sticky already exists, replace it.
15513                    list.set(i, new Intent(intent));
15514                    break;
15515                }
15516            }
15517            if (i >= N) {
15518                list.add(new Intent(intent));
15519            }
15520        }
15521
15522        int[] users;
15523        if (userId == UserHandle.USER_ALL) {
15524            // Caller wants broadcast to go to all started users.
15525            users = mStartedUserArray;
15526        } else {
15527            // Caller wants broadcast to go to one specific user.
15528            users = new int[] {userId};
15529        }
15530
15531        // Figure out who all will receive this broadcast.
15532        List receivers = null;
15533        List<BroadcastFilter> registeredReceivers = null;
15534        // Need to resolve the intent to interested receivers...
15535        if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
15536                 == 0) {
15537            receivers = collectReceiverComponents(intent, resolvedType, callingUid, users);
15538        }
15539        if (intent.getComponent() == null) {
15540            if (userId == UserHandle.USER_ALL && callingUid == Process.SHELL_UID) {
15541                // Query one target user at a time, excluding shell-restricted users
15542                UserManagerService ums = getUserManagerLocked();
15543                for (int i = 0; i < users.length; i++) {
15544                    if (ums.hasUserRestriction(
15545                            UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
15546                        continue;
15547                    }
15548                    List<BroadcastFilter> registeredReceiversForUser =
15549                            mReceiverResolver.queryIntent(intent,
15550                                    resolvedType, false, users[i]);
15551                    if (registeredReceivers == null) {
15552                        registeredReceivers = registeredReceiversForUser;
15553                    } else if (registeredReceiversForUser != null) {
15554                        registeredReceivers.addAll(registeredReceiversForUser);
15555                    }
15556                }
15557            } else {
15558                registeredReceivers = mReceiverResolver.queryIntent(intent,
15559                        resolvedType, false, userId);
15560            }
15561        }
15562
15563        final boolean replacePending =
15564                (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
15565
15566        if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
15567                + " replacePending=" + replacePending);
15568
15569        int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
15570        if (!ordered && NR > 0) {
15571            // If we are not serializing this broadcast, then send the
15572            // registered receivers separately so they don't wait for the
15573            // components to be launched.
15574            final BroadcastQueue queue = broadcastQueueForIntent(intent);
15575            BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
15576                    callerPackage, callingPid, callingUid, resolvedType, requiredPermission,
15577                    appOp, registeredReceivers, resultTo, resultCode, resultData, map,
15578                    ordered, sticky, false, userId);
15579            if (DEBUG_BROADCAST) Slog.v(
15580                    TAG, "Enqueueing parallel broadcast " + r);
15581            final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
15582            if (!replaced) {
15583                queue.enqueueParallelBroadcastLocked(r);
15584                queue.scheduleBroadcastsLocked();
15585            }
15586            registeredReceivers = null;
15587            NR = 0;
15588        }
15589
15590        // Merge into one list.
15591        int ir = 0;
15592        if (receivers != null) {
15593            // A special case for PACKAGE_ADDED: do not allow the package
15594            // being added to see this broadcast.  This prevents them from
15595            // using this as a back door to get run as soon as they are
15596            // installed.  Maybe in the future we want to have a special install
15597            // broadcast or such for apps, but we'd like to deliberately make
15598            // this decision.
15599            String skipPackages[] = null;
15600            if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
15601                    || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
15602                    || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
15603                Uri data = intent.getData();
15604                if (data != null) {
15605                    String pkgName = data.getSchemeSpecificPart();
15606                    if (pkgName != null) {
15607                        skipPackages = new String[] { pkgName };
15608                    }
15609                }
15610            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
15611                skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15612            }
15613            if (skipPackages != null && (skipPackages.length > 0)) {
15614                for (String skipPackage : skipPackages) {
15615                    if (skipPackage != null) {
15616                        int NT = receivers.size();
15617                        for (int it=0; it<NT; it++) {
15618                            ResolveInfo curt = (ResolveInfo)receivers.get(it);
15619                            if (curt.activityInfo.packageName.equals(skipPackage)) {
15620                                receivers.remove(it);
15621                                it--;
15622                                NT--;
15623                            }
15624                        }
15625                    }
15626                }
15627            }
15628
15629            int NT = receivers != null ? receivers.size() : 0;
15630            int it = 0;
15631            ResolveInfo curt = null;
15632            BroadcastFilter curr = null;
15633            while (it < NT && ir < NR) {
15634                if (curt == null) {
15635                    curt = (ResolveInfo)receivers.get(it);
15636                }
15637                if (curr == null) {
15638                    curr = registeredReceivers.get(ir);
15639                }
15640                if (curr.getPriority() >= curt.priority) {
15641                    // Insert this broadcast record into the final list.
15642                    receivers.add(it, curr);
15643                    ir++;
15644                    curr = null;
15645                    it++;
15646                    NT++;
15647                } else {
15648                    // Skip to the next ResolveInfo in the final list.
15649                    it++;
15650                    curt = null;
15651                }
15652            }
15653        }
15654        while (ir < NR) {
15655            if (receivers == null) {
15656                receivers = new ArrayList();
15657            }
15658            receivers.add(registeredReceivers.get(ir));
15659            ir++;
15660        }
15661
15662        if ((receivers != null && receivers.size() > 0)
15663                || resultTo != null) {
15664            BroadcastQueue queue = broadcastQueueForIntent(intent);
15665            BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
15666                    callerPackage, callingPid, callingUid, resolvedType,
15667                    requiredPermission, appOp, receivers, resultTo, resultCode,
15668                    resultData, map, ordered, sticky, false, userId);
15669            if (DEBUG_BROADCAST) Slog.v(
15670                    TAG, "Enqueueing ordered broadcast " + r
15671                    + ": prev had " + queue.mOrderedBroadcasts.size());
15672            if (DEBUG_BROADCAST) {
15673                int seq = r.intent.getIntExtra("seq", -1);
15674                Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
15675            }
15676            boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
15677            if (!replaced) {
15678                queue.enqueueOrderedBroadcastLocked(r);
15679                queue.scheduleBroadcastsLocked();
15680            }
15681        }
15682
15683        return ActivityManager.BROADCAST_SUCCESS;
15684    }
15685
15686    final Intent verifyBroadcastLocked(Intent intent) {
15687        // Refuse possible leaked file descriptors
15688        if (intent != null && intent.hasFileDescriptors() == true) {
15689            throw new IllegalArgumentException("File descriptors passed in Intent");
15690        }
15691
15692        int flags = intent.getFlags();
15693
15694        if (!mProcessesReady) {
15695            // if the caller really truly claims to know what they're doing, go
15696            // ahead and allow the broadcast without launching any receivers
15697            if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
15698                intent = new Intent(intent);
15699                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
15700            } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15701                Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
15702                        + " before boot completion");
15703                throw new IllegalStateException("Cannot broadcast before boot completed");
15704            }
15705        }
15706
15707        if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
15708            throw new IllegalArgumentException(
15709                    "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
15710        }
15711
15712        return intent;
15713    }
15714
15715    public final int broadcastIntent(IApplicationThread caller,
15716            Intent intent, String resolvedType, IIntentReceiver resultTo,
15717            int resultCode, String resultData, Bundle map,
15718            String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
15719        enforceNotIsolatedCaller("broadcastIntent");
15720        synchronized(this) {
15721            intent = verifyBroadcastLocked(intent);
15722
15723            final ProcessRecord callerApp = getRecordForAppLocked(caller);
15724            final int callingPid = Binder.getCallingPid();
15725            final int callingUid = Binder.getCallingUid();
15726            final long origId = Binder.clearCallingIdentity();
15727            int res = broadcastIntentLocked(callerApp,
15728                    callerApp != null ? callerApp.info.packageName : null,
15729                    intent, resolvedType, resultTo,
15730                    resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
15731                    callingPid, callingUid, userId);
15732            Binder.restoreCallingIdentity(origId);
15733            return res;
15734        }
15735    }
15736
15737    int broadcastIntentInPackage(String packageName, int uid,
15738            Intent intent, String resolvedType, IIntentReceiver resultTo,
15739            int resultCode, String resultData, Bundle map,
15740            String requiredPermission, boolean serialized, boolean sticky, int userId) {
15741        synchronized(this) {
15742            intent = verifyBroadcastLocked(intent);
15743
15744            final long origId = Binder.clearCallingIdentity();
15745            int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
15746                    resultTo, resultCode, resultData, map, requiredPermission,
15747                    AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
15748            Binder.restoreCallingIdentity(origId);
15749            return res;
15750        }
15751    }
15752
15753    public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
15754        // Refuse possible leaked file descriptors
15755        if (intent != null && intent.hasFileDescriptors() == true) {
15756            throw new IllegalArgumentException("File descriptors passed in Intent");
15757        }
15758
15759        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
15760                userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
15761
15762        synchronized(this) {
15763            if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
15764                    != PackageManager.PERMISSION_GRANTED) {
15765                String msg = "Permission Denial: unbroadcastIntent() from pid="
15766                        + Binder.getCallingPid()
15767                        + ", uid=" + Binder.getCallingUid()
15768                        + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15769                Slog.w(TAG, msg);
15770                throw new SecurityException(msg);
15771            }
15772            ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
15773            if (stickies != null) {
15774                ArrayList<Intent> list = stickies.get(intent.getAction());
15775                if (list != null) {
15776                    int N = list.size();
15777                    int i;
15778                    for (i=0; i<N; i++) {
15779                        if (intent.filterEquals(list.get(i))) {
15780                            list.remove(i);
15781                            break;
15782                        }
15783                    }
15784                    if (list.size() <= 0) {
15785                        stickies.remove(intent.getAction());
15786                    }
15787                }
15788                if (stickies.size() <= 0) {
15789                    mStickyBroadcasts.remove(userId);
15790                }
15791            }
15792        }
15793    }
15794
15795    private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
15796            String resultData, Bundle resultExtras, boolean resultAbort) {
15797        final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
15798        if (r == null) {
15799            Slog.w(TAG, "finishReceiver called but not found on queue");
15800            return false;
15801        }
15802
15803        return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort, false);
15804    }
15805
15806    void backgroundServicesFinishedLocked(int userId) {
15807        for (BroadcastQueue queue : mBroadcastQueues) {
15808            queue.backgroundServicesFinishedLocked(userId);
15809        }
15810    }
15811
15812    public void finishReceiver(IBinder who, int resultCode, String resultData,
15813            Bundle resultExtras, boolean resultAbort) {
15814        if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
15815
15816        // Refuse possible leaked file descriptors
15817        if (resultExtras != null && resultExtras.hasFileDescriptors()) {
15818            throw new IllegalArgumentException("File descriptors passed in Bundle");
15819        }
15820
15821        final long origId = Binder.clearCallingIdentity();
15822        try {
15823            boolean doNext = false;
15824            BroadcastRecord r;
15825
15826            synchronized(this) {
15827                r = broadcastRecordForReceiverLocked(who);
15828                if (r != null) {
15829                    doNext = r.queue.finishReceiverLocked(r, resultCode,
15830                        resultData, resultExtras, resultAbort, true);
15831                }
15832            }
15833
15834            if (doNext) {
15835                r.queue.processNextBroadcast(false);
15836            }
15837            trimApplications();
15838        } finally {
15839            Binder.restoreCallingIdentity(origId);
15840        }
15841    }
15842
15843    // =========================================================
15844    // INSTRUMENTATION
15845    // =========================================================
15846
15847    public boolean startInstrumentation(ComponentName className,
15848            String profileFile, int flags, Bundle arguments,
15849            IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
15850            int userId, String abiOverride) {
15851        enforceNotIsolatedCaller("startInstrumentation");
15852        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
15853                userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
15854        // Refuse possible leaked file descriptors
15855        if (arguments != null && arguments.hasFileDescriptors()) {
15856            throw new IllegalArgumentException("File descriptors passed in Bundle");
15857        }
15858
15859        synchronized(this) {
15860            InstrumentationInfo ii = null;
15861            ApplicationInfo ai = null;
15862            try {
15863                ii = mContext.getPackageManager().getInstrumentationInfo(
15864                    className, STOCK_PM_FLAGS);
15865                ai = AppGlobals.getPackageManager().getApplicationInfo(
15866                        ii.targetPackage, STOCK_PM_FLAGS, userId);
15867            } catch (PackageManager.NameNotFoundException e) {
15868            } catch (RemoteException e) {
15869            }
15870            if (ii == null) {
15871                reportStartInstrumentationFailure(watcher, className,
15872                        "Unable to find instrumentation info for: " + className);
15873                return false;
15874            }
15875            if (ai == null) {
15876                reportStartInstrumentationFailure(watcher, className,
15877                        "Unable to find instrumentation target package: " + ii.targetPackage);
15878                return false;
15879            }
15880
15881            int match = mContext.getPackageManager().checkSignatures(
15882                    ii.targetPackage, ii.packageName);
15883            if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
15884                String msg = "Permission Denial: starting instrumentation "
15885                        + className + " from pid="
15886                        + Binder.getCallingPid()
15887                        + ", uid=" + Binder.getCallingPid()
15888                        + " not allowed because package " + ii.packageName
15889                        + " does not have a signature matching the target "
15890                        + ii.targetPackage;
15891                reportStartInstrumentationFailure(watcher, className, msg);
15892                throw new SecurityException(msg);
15893            }
15894
15895            final long origId = Binder.clearCallingIdentity();
15896            // Instrumentation can kill and relaunch even persistent processes
15897            forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId,
15898                    "start instr");
15899            ProcessRecord app = addAppLocked(ai, false, abiOverride);
15900            app.instrumentationClass = className;
15901            app.instrumentationInfo = ai;
15902            app.instrumentationProfileFile = profileFile;
15903            app.instrumentationArguments = arguments;
15904            app.instrumentationWatcher = watcher;
15905            app.instrumentationUiAutomationConnection = uiAutomationConnection;
15906            app.instrumentationResultClass = className;
15907            Binder.restoreCallingIdentity(origId);
15908        }
15909
15910        return true;
15911    }
15912
15913    /**
15914     * Report errors that occur while attempting to start Instrumentation.  Always writes the
15915     * error to the logs, but if somebody is watching, send the report there too.  This enables
15916     * the "am" command to report errors with more information.
15917     *
15918     * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
15919     * @param cn The component name of the instrumentation.
15920     * @param report The error report.
15921     */
15922    private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
15923            ComponentName cn, String report) {
15924        Slog.w(TAG, report);
15925        try {
15926            if (watcher != null) {
15927                Bundle results = new Bundle();
15928                results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
15929                results.putString("Error", report);
15930                watcher.instrumentationStatus(cn, -1, results);
15931            }
15932        } catch (RemoteException e) {
15933            Slog.w(TAG, e);
15934        }
15935    }
15936
15937    void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
15938        if (app.instrumentationWatcher != null) {
15939            try {
15940                // NOTE:  IInstrumentationWatcher *must* be oneway here
15941                app.instrumentationWatcher.instrumentationFinished(
15942                    app.instrumentationClass,
15943                    resultCode,
15944                    results);
15945            } catch (RemoteException e) {
15946            }
15947        }
15948        if (app.instrumentationUiAutomationConnection != null) {
15949            try {
15950                app.instrumentationUiAutomationConnection.shutdown();
15951            } catch (RemoteException re) {
15952                /* ignore */
15953            }
15954            // Only a UiAutomation can set this flag and now that
15955            // it is finished we make sure it is reset to its default.
15956            mUserIsMonkey = false;
15957        }
15958        app.instrumentationWatcher = null;
15959        app.instrumentationUiAutomationConnection = null;
15960        app.instrumentationClass = null;
15961        app.instrumentationInfo = null;
15962        app.instrumentationProfileFile = null;
15963        app.instrumentationArguments = null;
15964
15965        forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId,
15966                "finished inst");
15967    }
15968
15969    public void finishInstrumentation(IApplicationThread target,
15970            int resultCode, Bundle results) {
15971        int userId = UserHandle.getCallingUserId();
15972        // Refuse possible leaked file descriptors
15973        if (results != null && results.hasFileDescriptors()) {
15974            throw new IllegalArgumentException("File descriptors passed in Intent");
15975        }
15976
15977        synchronized(this) {
15978            ProcessRecord app = getRecordForAppLocked(target);
15979            if (app == null) {
15980                Slog.w(TAG, "finishInstrumentation: no app for " + target);
15981                return;
15982            }
15983            final long origId = Binder.clearCallingIdentity();
15984            finishInstrumentationLocked(app, resultCode, results);
15985            Binder.restoreCallingIdentity(origId);
15986        }
15987    }
15988
15989    // =========================================================
15990    // CONFIGURATION
15991    // =========================================================
15992
15993    public ConfigurationInfo getDeviceConfigurationInfo() {
15994        ConfigurationInfo config = new ConfigurationInfo();
15995        synchronized (this) {
15996            config.reqTouchScreen = mConfiguration.touchscreen;
15997            config.reqKeyboardType = mConfiguration.keyboard;
15998            config.reqNavigation = mConfiguration.navigation;
15999            if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
16000                    || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
16001                config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
16002            }
16003            if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
16004                    && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
16005                config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
16006            }
16007            config.reqGlEsVersion = GL_ES_VERSION;
16008        }
16009        return config;
16010    }
16011
16012    ActivityStack getFocusedStack() {
16013        return mStackSupervisor.getFocusedStack();
16014    }
16015
16016    public Configuration getConfiguration() {
16017        Configuration ci;
16018        synchronized(this) {
16019            ci = new Configuration(mConfiguration);
16020        }
16021        return ci;
16022    }
16023
16024    public void updatePersistentConfiguration(Configuration values) {
16025        enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
16026                "updateConfiguration()");
16027        enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
16028                "updateConfiguration()");
16029        if (values == null) {
16030            throw new NullPointerException("Configuration must not be null");
16031        }
16032
16033        synchronized(this) {
16034            final long origId = Binder.clearCallingIdentity();
16035            updateConfigurationLocked(values, null, true, false);
16036            Binder.restoreCallingIdentity(origId);
16037        }
16038    }
16039
16040    public void updateConfiguration(Configuration values) {
16041        enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
16042                "updateConfiguration()");
16043
16044        synchronized(this) {
16045            if (values == null && mWindowManager != null) {
16046                // sentinel: fetch the current configuration from the window manager
16047                values = mWindowManager.computeNewConfiguration();
16048            }
16049
16050            if (mWindowManager != null) {
16051                mProcessList.applyDisplaySize(mWindowManager);
16052            }
16053
16054            final long origId = Binder.clearCallingIdentity();
16055            if (values != null) {
16056                Settings.System.clearConfiguration(values);
16057            }
16058            updateConfigurationLocked(values, null, false, false);
16059            Binder.restoreCallingIdentity(origId);
16060        }
16061    }
16062
16063    /**
16064     * Do either or both things: (1) change the current configuration, and (2)
16065     * make sure the given activity is running with the (now) current
16066     * configuration.  Returns true if the activity has been left running, or
16067     * false if <var>starting</var> is being destroyed to match the new
16068     * configuration.
16069     * @param persistent TODO
16070     */
16071    boolean updateConfigurationLocked(Configuration values,
16072            ActivityRecord starting, boolean persistent, boolean initLocale) {
16073        int changes = 0;
16074
16075        if (values != null) {
16076            Configuration newConfig = new Configuration(mConfiguration);
16077            changes = newConfig.updateFrom(values);
16078            if (changes != 0) {
16079                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
16080                    Slog.i(TAG, "Updating configuration to: " + values);
16081                }
16082
16083                EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
16084
16085                if (values.locale != null && !initLocale) {
16086                    saveLocaleLocked(values.locale,
16087                                     !values.locale.equals(mConfiguration.locale),
16088                                     values.userSetLocale);
16089                }
16090
16091                mConfigurationSeq++;
16092                if (mConfigurationSeq <= 0) {
16093                    mConfigurationSeq = 1;
16094                }
16095                newConfig.seq = mConfigurationSeq;
16096                mConfiguration = newConfig;
16097                Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
16098                mUsageStatsService.reportConfigurationChange(newConfig, mCurrentUserId);
16099                //mUsageStatsService.noteStartConfig(newConfig);
16100
16101                final Configuration configCopy = new Configuration(mConfiguration);
16102
16103                // TODO: If our config changes, should we auto dismiss any currently
16104                // showing dialogs?
16105                mShowDialogs = shouldShowDialogs(newConfig);
16106
16107                AttributeCache ac = AttributeCache.instance();
16108                if (ac != null) {
16109                    ac.updateConfiguration(configCopy);
16110                }
16111
16112                // Make sure all resources in our process are updated
16113                // right now, so that anyone who is going to retrieve
16114                // resource values after we return will be sure to get
16115                // the new ones.  This is especially important during
16116                // boot, where the first config change needs to guarantee
16117                // all resources have that config before following boot
16118                // code is executed.
16119                mSystemThread.applyConfigurationToResources(configCopy);
16120
16121                if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
16122                    Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
16123                    msg.obj = new Configuration(configCopy);
16124                    mHandler.sendMessage(msg);
16125                }
16126
16127                for (int i=mLruProcesses.size()-1; i>=0; i--) {
16128                    ProcessRecord app = mLruProcesses.get(i);
16129                    try {
16130                        if (app.thread != null) {
16131                            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
16132                                    + app.processName + " new config " + mConfiguration);
16133                            app.thread.scheduleConfigurationChanged(configCopy);
16134                        }
16135                    } catch (Exception e) {
16136                    }
16137                }
16138                Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
16139                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
16140                        | Intent.FLAG_RECEIVER_REPLACE_PENDING
16141                        | Intent.FLAG_RECEIVER_FOREGROUND);
16142                broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
16143                        null, AppOpsManager.OP_NONE, false, false, MY_PID,
16144                        Process.SYSTEM_UID, UserHandle.USER_ALL);
16145                if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
16146                    intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
16147                    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16148                    broadcastIntentLocked(null, null, intent,
16149                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
16150                            false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
16151                }
16152            }
16153        }
16154
16155        boolean kept = true;
16156        final ActivityStack mainStack = mStackSupervisor.getFocusedStack();
16157        // mainStack is null during startup.
16158        if (mainStack != null) {
16159            if (changes != 0 && starting == null) {
16160                // If the configuration changed, and the caller is not already
16161                // in the process of starting an activity, then find the top
16162                // activity to check if its configuration needs to change.
16163                starting = mainStack.topRunningActivityLocked(null);
16164            }
16165
16166            if (starting != null) {
16167                kept = mainStack.ensureActivityConfigurationLocked(starting, changes);
16168                // And we need to make sure at this point that all other activities
16169                // are made visible with the correct configuration.
16170                mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes);
16171            }
16172        }
16173
16174        if (values != null && mWindowManager != null) {
16175            mWindowManager.setNewConfiguration(mConfiguration);
16176        }
16177
16178        return kept;
16179    }
16180
16181    /**
16182     * Decide based on the configuration whether we should shouw the ANR,
16183     * crash, etc dialogs.  The idea is that if there is no affordnace to
16184     * press the on-screen buttons, we shouldn't show the dialog.
16185     *
16186     * A thought: SystemUI might also want to get told about this, the Power
16187     * dialog / global actions also might want different behaviors.
16188     */
16189    private static final boolean shouldShowDialogs(Configuration config) {
16190        return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
16191                && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
16192    }
16193
16194    /**
16195     * Save the locale.  You must be inside a synchronized (this) block.
16196     */
16197    private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
16198        if(isDiff) {
16199            SystemProperties.set("user.language", l.getLanguage());
16200            SystemProperties.set("user.region", l.getCountry());
16201        }
16202
16203        if(isPersist) {
16204            SystemProperties.set("persist.sys.language", l.getLanguage());
16205            SystemProperties.set("persist.sys.country", l.getCountry());
16206            SystemProperties.set("persist.sys.localevar", l.getVariant());
16207        }
16208    }
16209
16210    @Override
16211    public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
16212        synchronized (this) {
16213            ActivityRecord srec = ActivityRecord.forToken(token);
16214            if (srec.task != null && srec.task.stack != null) {
16215                return srec.task.stack.shouldUpRecreateTaskLocked(srec, destAffinity);
16216            }
16217        }
16218        return false;
16219    }
16220
16221    public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
16222            Intent resultData) {
16223
16224        synchronized (this) {
16225            final ActivityStack stack = ActivityRecord.getStackLocked(token);
16226            if (stack != null) {
16227                return stack.navigateUpToLocked(token, destIntent, resultCode, resultData);
16228            }
16229            return false;
16230        }
16231    }
16232
16233    public int getLaunchedFromUid(IBinder activityToken) {
16234        ActivityRecord srec = ActivityRecord.forToken(activityToken);
16235        if (srec == null) {
16236            return -1;
16237        }
16238        return srec.launchedFromUid;
16239    }
16240
16241    public String getLaunchedFromPackage(IBinder activityToken) {
16242        ActivityRecord srec = ActivityRecord.forToken(activityToken);
16243        if (srec == null) {
16244            return null;
16245        }
16246        return srec.launchedFromPackage;
16247    }
16248
16249    // =========================================================
16250    // LIFETIME MANAGEMENT
16251    // =========================================================
16252
16253    // Returns which broadcast queue the app is the current [or imminent] receiver
16254    // on, or 'null' if the app is not an active broadcast recipient.
16255    private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
16256        BroadcastRecord r = app.curReceiver;
16257        if (r != null) {
16258            return r.queue;
16259        }
16260
16261        // It's not the current receiver, but it might be starting up to become one
16262        synchronized (this) {
16263            for (BroadcastQueue queue : mBroadcastQueues) {
16264                r = queue.mPendingBroadcast;
16265                if (r != null && r.curApp == app) {
16266                    // found it; report which queue it's in
16267                    return queue;
16268                }
16269            }
16270        }
16271
16272        return null;
16273    }
16274
16275    private final int computeOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP,
16276            boolean doingAll, long now) {
16277        if (mAdjSeq == app.adjSeq) {
16278            // This adjustment has already been computed.
16279            return app.curRawAdj;
16280        }
16281
16282        if (app.thread == null) {
16283            app.adjSeq = mAdjSeq;
16284            app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
16285            app.curProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
16286            return (app.curAdj=app.curRawAdj=ProcessList.CACHED_APP_MAX_ADJ);
16287        }
16288
16289        app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
16290        app.adjSource = null;
16291        app.adjTarget = null;
16292        app.empty = false;
16293        app.cached = false;
16294
16295        final int activitiesSize = app.activities.size();
16296
16297        if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
16298            // The max adjustment doesn't allow this app to be anything
16299            // below foreground, so it is not worth doing work for it.
16300            app.adjType = "fixed";
16301            app.adjSeq = mAdjSeq;
16302            app.curRawAdj = app.maxAdj;
16303            app.foregroundActivities = false;
16304            app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
16305            app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT;
16306            // System processes can do UI, and when they do we want to have
16307            // them trim their memory after the user leaves the UI.  To
16308            // facilitate this, here we need to determine whether or not it
16309            // is currently showing UI.
16310            app.systemNoUi = true;
16311            if (app == TOP_APP) {
16312                app.systemNoUi = false;
16313            } else if (activitiesSize > 0) {
16314                for (int j = 0; j < activitiesSize; j++) {
16315                    final ActivityRecord r = app.activities.get(j);
16316                    if (r.visible) {
16317                        app.systemNoUi = false;
16318                    }
16319                }
16320            }
16321            if (!app.systemNoUi) {
16322                app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT_UI;
16323            }
16324            return (app.curAdj=app.maxAdj);
16325        }
16326
16327        app.systemNoUi = false;
16328
16329        // Determine the importance of the process, starting with most
16330        // important to least, and assign an appropriate OOM adjustment.
16331        int adj;
16332        int schedGroup;
16333        int procState;
16334        boolean foregroundActivities = false;
16335        BroadcastQueue queue;
16336        if (app == TOP_APP) {
16337            // The last app on the list is the foreground app.
16338            adj = ProcessList.FOREGROUND_APP_ADJ;
16339            schedGroup = Process.THREAD_GROUP_DEFAULT;
16340            app.adjType = "top-activity";
16341            foregroundActivities = true;
16342            procState = ActivityManager.PROCESS_STATE_TOP;
16343        } else if (app.instrumentationClass != null) {
16344            // Don't want to kill running instrumentation.
16345            adj = ProcessList.FOREGROUND_APP_ADJ;
16346            schedGroup = Process.THREAD_GROUP_DEFAULT;
16347            app.adjType = "instrumentation";
16348            procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
16349        } else if ((queue = isReceivingBroadcast(app)) != null) {
16350            // An app that is currently receiving a broadcast also
16351            // counts as being in the foreground for OOM killer purposes.
16352            // It's placed in a sched group based on the nature of the
16353            // broadcast as reflected by which queue it's active in.
16354            adj = ProcessList.FOREGROUND_APP_ADJ;
16355            schedGroup = (queue == mFgBroadcastQueue)
16356                    ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
16357            app.adjType = "broadcast";
16358            procState = ActivityManager.PROCESS_STATE_RECEIVER;
16359        } else if (app.executingServices.size() > 0) {
16360            // An app that is currently executing a service callback also
16361            // counts as being in the foreground.
16362            adj = ProcessList.FOREGROUND_APP_ADJ;
16363            schedGroup = app.execServicesFg ?
16364                    Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
16365            app.adjType = "exec-service";
16366            procState = ActivityManager.PROCESS_STATE_SERVICE;
16367            //Slog.i(TAG, "EXEC " + (app.execServicesFg ? "FG" : "BG") + ": " + app);
16368        } else {
16369            // As far as we know the process is empty.  We may change our mind later.
16370            schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
16371            // At this point we don't actually know the adjustment.  Use the cached adj
16372            // value that the caller wants us to.
16373            adj = cachedAdj;
16374            procState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
16375            app.cached = true;
16376            app.empty = true;
16377            app.adjType = "cch-empty";
16378        }
16379
16380        // Examine all activities if not already foreground.
16381        if (!foregroundActivities && activitiesSize > 0) {
16382            for (int j = 0; j < activitiesSize; j++) {
16383                final ActivityRecord r = app.activities.get(j);
16384                if (r.app != app) {
16385                    Slog.w(TAG, "Wtf, activity " + r + " in proc activity list not using proc "
16386                            + app + "?!?");
16387                    continue;
16388                }
16389                if (r.visible) {
16390                    // App has a visible activity; only upgrade adjustment.
16391                    if (adj > ProcessList.VISIBLE_APP_ADJ) {
16392                        adj = ProcessList.VISIBLE_APP_ADJ;
16393                        app.adjType = "visible";
16394                    }
16395                    if (procState > ActivityManager.PROCESS_STATE_TOP) {
16396                        procState = ActivityManager.PROCESS_STATE_TOP;
16397                    }
16398                    schedGroup = Process.THREAD_GROUP_DEFAULT;
16399                    app.cached = false;
16400                    app.empty = false;
16401                    foregroundActivities = true;
16402                    break;
16403                } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
16404                    if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
16405                        adj = ProcessList.PERCEPTIBLE_APP_ADJ;
16406                        app.adjType = "pausing";
16407                    }
16408                    if (procState > ActivityManager.PROCESS_STATE_TOP) {
16409                        procState = ActivityManager.PROCESS_STATE_TOP;
16410                    }
16411                    schedGroup = Process.THREAD_GROUP_DEFAULT;
16412                    app.cached = false;
16413                    app.empty = false;
16414                    foregroundActivities = true;
16415                } else if (r.state == ActivityState.STOPPING) {
16416                    if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
16417                        adj = ProcessList.PERCEPTIBLE_APP_ADJ;
16418                        app.adjType = "stopping";
16419                    }
16420                    // For the process state, we will at this point consider the
16421                    // process to be cached.  It will be cached either as an activity
16422                    // or empty depending on whether the activity is finishing.  We do
16423                    // this so that we can treat the process as cached for purposes of
16424                    // memory trimming (determing current memory level, trim command to
16425                    // send to process) since there can be an arbitrary number of stopping
16426                    // processes and they should soon all go into the cached state.
16427                    if (!r.finishing) {
16428                        if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
16429                            procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY;
16430                        }
16431                    }
16432                    app.cached = false;
16433                    app.empty = false;
16434                    foregroundActivities = true;
16435                } else {
16436                    if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
16437                        procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY;
16438                        app.adjType = "cch-act";
16439                    }
16440                }
16441            }
16442        }
16443
16444        if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
16445            if (app.foregroundServices) {
16446                // The user is aware of this app, so make it visible.
16447                adj = ProcessList.PERCEPTIBLE_APP_ADJ;
16448                procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
16449                app.cached = false;
16450                app.adjType = "fg-service";
16451                schedGroup = Process.THREAD_GROUP_DEFAULT;
16452            } else if (app.forcingToForeground != null) {
16453                // The user is aware of this app, so make it visible.
16454                adj = ProcessList.PERCEPTIBLE_APP_ADJ;
16455                procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
16456                app.cached = false;
16457                app.adjType = "force-fg";
16458                app.adjSource = app.forcingToForeground;
16459                schedGroup = Process.THREAD_GROUP_DEFAULT;
16460            }
16461        }
16462
16463        if (app == mHeavyWeightProcess) {
16464            if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ) {
16465                // We don't want to kill the current heavy-weight process.
16466                adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
16467                schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
16468                app.cached = false;
16469                app.adjType = "heavy";
16470            }
16471            if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
16472                procState = ActivityManager.PROCESS_STATE_HEAVY_WEIGHT;
16473            }
16474        }
16475
16476        if (app == mHomeProcess) {
16477            if (adj > ProcessList.HOME_APP_ADJ) {
16478                // This process is hosting what we currently consider to be the
16479                // home app, so we don't want to let it go into the background.
16480                adj = ProcessList.HOME_APP_ADJ;
16481                schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
16482                app.cached = false;
16483                app.adjType = "home";
16484            }
16485            if (procState > ActivityManager.PROCESS_STATE_HOME) {
16486                procState = ActivityManager.PROCESS_STATE_HOME;
16487            }
16488        }
16489
16490        if (app == mPreviousProcess && app.activities.size() > 0) {
16491            if (adj > ProcessList.PREVIOUS_APP_ADJ) {
16492                // This was the previous process that showed UI to the user.
16493                // We want to try to keep it around more aggressively, to give
16494                // a good experience around switching between two apps.
16495                adj = ProcessList.PREVIOUS_APP_ADJ;
16496                schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
16497                app.cached = false;
16498                app.adjType = "previous";
16499            }
16500            if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
16501                procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY;
16502            }
16503        }
16504
16505        if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
16506                + " reason=" + app.adjType);
16507
16508        // By default, we use the computed adjustment.  It may be changed if
16509        // there are applications dependent on our services or providers, but
16510        // this gives us a baseline and makes sure we don't get into an
16511        // infinite recursion.
16512        app.adjSeq = mAdjSeq;
16513        app.curRawAdj = adj;
16514        app.hasStartedServices = false;
16515
16516        if (mBackupTarget != null && app == mBackupTarget.app) {
16517            // If possible we want to avoid killing apps while they're being backed up
16518            if (adj > ProcessList.BACKUP_APP_ADJ) {
16519                if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
16520                adj = ProcessList.BACKUP_APP_ADJ;
16521                if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
16522                    procState = ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND;
16523                }
16524                app.adjType = "backup";
16525                app.cached = false;
16526            }
16527            if (procState > ActivityManager.PROCESS_STATE_BACKUP) {
16528                procState = ActivityManager.PROCESS_STATE_BACKUP;
16529            }
16530        }
16531
16532        boolean mayBeTop = false;
16533
16534        for (int is = app.services.size()-1;
16535                is >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
16536                        || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
16537                        || procState > ActivityManager.PROCESS_STATE_TOP);
16538                is--) {
16539            ServiceRecord s = app.services.valueAt(is);
16540            if (s.startRequested) {
16541                app.hasStartedServices = true;
16542                if (procState > ActivityManager.PROCESS_STATE_SERVICE) {
16543                    procState = ActivityManager.PROCESS_STATE_SERVICE;
16544                }
16545                if (app.hasShownUi && app != mHomeProcess) {
16546                    // If this process has shown some UI, let it immediately
16547                    // go to the LRU list because it may be pretty heavy with
16548                    // UI stuff.  We'll tag it with a label just to help
16549                    // debug and understand what is going on.
16550                    if (adj > ProcessList.SERVICE_ADJ) {
16551                        app.adjType = "cch-started-ui-services";
16552                    }
16553                } else {
16554                    if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
16555                        // This service has seen some activity within
16556                        // recent memory, so we will keep its process ahead
16557                        // of the background processes.
16558                        if (adj > ProcessList.SERVICE_ADJ) {
16559                            adj = ProcessList.SERVICE_ADJ;
16560                            app.adjType = "started-services";
16561                            app.cached = false;
16562                        }
16563                    }
16564                    // If we have let the service slide into the background
16565                    // state, still have some text describing what it is doing
16566                    // even though the service no longer has an impact.
16567                    if (adj > ProcessList.SERVICE_ADJ) {
16568                        app.adjType = "cch-started-services";
16569                    }
16570                }
16571            }
16572            for (int conni = s.connections.size()-1;
16573                    conni >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
16574                            || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
16575                            || procState > ActivityManager.PROCESS_STATE_TOP);
16576                    conni--) {
16577                ArrayList<ConnectionRecord> clist = s.connections.valueAt(conni);
16578                for (int i = 0;
16579                        i < clist.size() && (adj > ProcessList.FOREGROUND_APP_ADJ
16580                                || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
16581                                || procState > ActivityManager.PROCESS_STATE_TOP);
16582                        i++) {
16583                    // XXX should compute this based on the max of
16584                    // all connected clients.
16585                    ConnectionRecord cr = clist.get(i);
16586                    if (cr.binding.client == app) {
16587                        // Binding to ourself is not interesting.
16588                        continue;
16589                    }
16590                    if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
16591                        ProcessRecord client = cr.binding.client;
16592                        int clientAdj = computeOomAdjLocked(client, cachedAdj,
16593                                TOP_APP, doingAll, now);
16594                        int clientProcState = client.curProcState;
16595                        if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
16596                            // If the other app is cached for any reason, for purposes here
16597                            // we are going to consider it empty.  The specific cached state
16598                            // doesn't propagate except under certain conditions.
16599                            clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
16600                        }
16601                        String adjType = null;
16602                        if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
16603                            // Not doing bind OOM management, so treat
16604                            // this guy more like a started service.
16605                            if (app.hasShownUi && app != mHomeProcess) {
16606                                // If this process has shown some UI, let it immediately
16607                                // go to the LRU list because it may be pretty heavy with
16608                                // UI stuff.  We'll tag it with a label just to help
16609                                // debug and understand what is going on.
16610                                if (adj > clientAdj) {
16611                                    adjType = "cch-bound-ui-services";
16612                                }
16613                                app.cached = false;
16614                                clientAdj = adj;
16615                                clientProcState = procState;
16616                            } else {
16617                                if (now >= (s.lastActivity
16618                                        + ActiveServices.MAX_SERVICE_INACTIVITY)) {
16619                                    // This service has not seen activity within
16620                                    // recent memory, so allow it to drop to the
16621                                    // LRU list if there is no other reason to keep
16622                                    // it around.  We'll also tag it with a label just
16623                                    // to help debug and undertand what is going on.
16624                                    if (adj > clientAdj) {
16625                                        adjType = "cch-bound-services";
16626                                    }
16627                                    clientAdj = adj;
16628                                }
16629                            }
16630                        }
16631                        if (adj > clientAdj) {
16632                            // If this process has recently shown UI, and
16633                            // the process that is binding to it is less
16634                            // important than being visible, then we don't
16635                            // care about the binding as much as we care
16636                            // about letting this process get into the LRU
16637                            // list to be killed and restarted if needed for
16638                            // memory.
16639                            if (app.hasShownUi && app != mHomeProcess
16640                                    && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
16641                                adjType = "cch-bound-ui-services";
16642                            } else {
16643                                if ((cr.flags&(Context.BIND_ABOVE_CLIENT
16644                                        |Context.BIND_IMPORTANT)) != 0) {
16645                                    adj = clientAdj;
16646                                } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
16647                                        && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
16648                                        && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
16649                                    adj = ProcessList.PERCEPTIBLE_APP_ADJ;
16650                                } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
16651                                    adj = clientAdj;
16652                                } else {
16653                                    if (adj > ProcessList.VISIBLE_APP_ADJ) {
16654                                        adj = ProcessList.VISIBLE_APP_ADJ;
16655                                    }
16656                                }
16657                                if (!client.cached) {
16658                                    app.cached = false;
16659                                }
16660                                adjType = "service";
16661                            }
16662                        }
16663                        if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
16664                            if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
16665                                schedGroup = Process.THREAD_GROUP_DEFAULT;
16666                            }
16667                            if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) {
16668                                if (clientProcState == ActivityManager.PROCESS_STATE_TOP) {
16669                                    // Special handling of clients who are in the top state.
16670                                    // We *may* want to consider this process to be in the
16671                                    // top state as well, but only if there is not another
16672                                    // reason for it to be running.  Being on the top is a
16673                                    // special state, meaning you are specifically running
16674                                    // for the current top app.  If the process is already
16675                                    // running in the background for some other reason, it
16676                                    // is more important to continue considering it to be
16677                                    // in the background state.
16678                                    mayBeTop = true;
16679                                    clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
16680                                } else {
16681                                    // Special handling for above-top states (persistent
16682                                    // processes).  These should not bring the current process
16683                                    // into the top state, since they are not on top.  Instead
16684                                    // give them the best state after that.
16685                                    clientProcState =
16686                                            ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
16687                                }
16688                            }
16689                        } else {
16690                            if (clientProcState <
16691                                    ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
16692                                clientProcState =
16693                                        ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND;
16694                            }
16695                        }
16696                        if (procState > clientProcState) {
16697                            procState = clientProcState;
16698                        }
16699                        if (procState < ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
16700                                && (cr.flags&Context.BIND_SHOWING_UI) != 0) {
16701                            app.pendingUiClean = true;
16702                        }
16703                        if (adjType != null) {
16704                            app.adjType = adjType;
16705                            app.adjTypeCode = ActivityManager.RunningAppProcessInfo
16706                                    .REASON_SERVICE_IN_USE;
16707                            app.adjSource = cr.binding.client;
16708                            app.adjSourceProcState = clientProcState;
16709                            app.adjTarget = s.name;
16710                        }
16711                    }
16712                    if ((cr.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
16713                        app.treatLikeActivity = true;
16714                    }
16715                    final ActivityRecord a = cr.activity;
16716                    if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
16717                        if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
16718                                (a.visible || a.state == ActivityState.RESUMED
16719                                 || a.state == ActivityState.PAUSING)) {
16720                            adj = ProcessList.FOREGROUND_APP_ADJ;
16721                            if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
16722                                schedGroup = Process.THREAD_GROUP_DEFAULT;
16723                            }
16724                            app.cached = false;
16725                            app.adjType = "service";
16726                            app.adjTypeCode = ActivityManager.RunningAppProcessInfo
16727                                    .REASON_SERVICE_IN_USE;
16728                            app.adjSource = a;
16729                            app.adjSourceProcState = procState;
16730                            app.adjTarget = s.name;
16731                        }
16732                    }
16733                }
16734            }
16735        }
16736
16737        for (int provi = app.pubProviders.size()-1;
16738                provi >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
16739                        || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
16740                        || procState > ActivityManager.PROCESS_STATE_TOP);
16741                provi--) {
16742            ContentProviderRecord cpr = app.pubProviders.valueAt(provi);
16743            for (int i = cpr.connections.size()-1;
16744                    i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
16745                            || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
16746                            || procState > ActivityManager.PROCESS_STATE_TOP);
16747                    i--) {
16748                ContentProviderConnection conn = cpr.connections.get(i);
16749                ProcessRecord client = conn.client;
16750                if (client == app) {
16751                    // Being our own client is not interesting.
16752                    continue;
16753                }
16754                int clientAdj = computeOomAdjLocked(client, cachedAdj, TOP_APP, doingAll, now);
16755                int clientProcState = client.curProcState;
16756                if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
16757                    // If the other app is cached for any reason, for purposes here
16758                    // we are going to consider it empty.
16759                    clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
16760                }
16761                if (adj > clientAdj) {
16762                    if (app.hasShownUi && app != mHomeProcess
16763                            && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
16764                        app.adjType = "cch-ui-provider";
16765                    } else {
16766                        adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
16767                                ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
16768                        app.adjType = "provider";
16769                    }
16770                    app.cached &= client.cached;
16771                    app.adjTypeCode = ActivityManager.RunningAppProcessInfo
16772                            .REASON_PROVIDER_IN_USE;
16773                    app.adjSource = client;
16774                    app.adjSourceProcState = clientProcState;
16775                    app.adjTarget = cpr.name;
16776                }
16777                if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) {
16778                    if (clientProcState == ActivityManager.PROCESS_STATE_TOP) {
16779                        // Special handling of clients who are in the top state.
16780                        // We *may* want to consider this process to be in the
16781                        // top state as well, but only if there is not another
16782                        // reason for it to be running.  Being on the top is a
16783                        // special state, meaning you are specifically running
16784                        // for the current top app.  If the process is already
16785                        // running in the background for some other reason, it
16786                        // is more important to continue considering it to be
16787                        // in the background state.
16788                        mayBeTop = true;
16789                        clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
16790                    } else {
16791                        // Special handling for above-top states (persistent
16792                        // processes).  These should not bring the current process
16793                        // into the top state, since they are not on top.  Instead
16794                        // give them the best state after that.
16795                        clientProcState =
16796                                ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
16797                    }
16798                }
16799                if (procState > clientProcState) {
16800                    procState = clientProcState;
16801                }
16802                if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
16803                    schedGroup = Process.THREAD_GROUP_DEFAULT;
16804                }
16805            }
16806            // If the provider has external (non-framework) process
16807            // dependencies, ensure that its adjustment is at least
16808            // FOREGROUND_APP_ADJ.
16809            if (cpr.hasExternalProcessHandles()) {
16810                if (adj > ProcessList.FOREGROUND_APP_ADJ) {
16811                    adj = ProcessList.FOREGROUND_APP_ADJ;
16812                    schedGroup = Process.THREAD_GROUP_DEFAULT;
16813                    app.cached = false;
16814                    app.adjType = "provider";
16815                    app.adjTarget = cpr.name;
16816                }
16817                if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
16818                    procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
16819                }
16820            }
16821        }
16822
16823        if (mayBeTop && procState > ActivityManager.PROCESS_STATE_TOP) {
16824            // A client of one of our services or providers is in the top state.  We
16825            // *may* want to be in the top state, but not if we are already running in
16826            // the background for some other reason.  For the decision here, we are going
16827            // to pick out a few specific states that we want to remain in when a client
16828            // is top (states that tend to be longer-term) and otherwise allow it to go
16829            // to the top state.
16830            switch (procState) {
16831                case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND:
16832                case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND:
16833                case ActivityManager.PROCESS_STATE_SERVICE:
16834                    // These all are longer-term states, so pull them up to the top
16835                    // of the background states, but not all the way to the top state.
16836                    procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
16837                    break;
16838                default:
16839                    // Otherwise, top is a better choice, so take it.
16840                    procState = ActivityManager.PROCESS_STATE_TOP;
16841                    break;
16842            }
16843        }
16844
16845        if (procState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
16846            if (app.hasClientActivities) {
16847                // This is a cached process, but with client activities.  Mark it so.
16848                procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT;
16849                app.adjType = "cch-client-act";
16850            } else if (app.treatLikeActivity) {
16851                // This is a cached process, but somebody wants us to treat it like it has
16852                // an activity, okay!
16853                procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY;
16854                app.adjType = "cch-as-act";
16855            }
16856        }
16857
16858        if (adj == ProcessList.SERVICE_ADJ) {
16859            if (doingAll) {
16860                app.serviceb = mNewNumAServiceProcs > (mNumServiceProcs/3);
16861                mNewNumServiceProcs++;
16862                //Slog.i(TAG, "ADJ " + app + " serviceb=" + app.serviceb);
16863                if (!app.serviceb) {
16864                    // This service isn't far enough down on the LRU list to
16865                    // normally be a B service, but if we are low on RAM and it
16866                    // is large we want to force it down since we would prefer to
16867                    // keep launcher over it.
16868                    if (mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
16869                            && app.lastPss >= mProcessList.getCachedRestoreThresholdKb()) {
16870                        app.serviceHighRam = true;
16871                        app.serviceb = true;
16872                        //Slog.i(TAG, "ADJ " + app + " high ram!");
16873                    } else {
16874                        mNewNumAServiceProcs++;
16875                        //Slog.i(TAG, "ADJ " + app + " not high ram!");
16876                    }
16877                } else {
16878                    app.serviceHighRam = false;
16879                }
16880            }
16881            if (app.serviceb) {
16882                adj = ProcessList.SERVICE_B_ADJ;
16883            }
16884        }
16885
16886        app.curRawAdj = adj;
16887
16888        //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
16889        //      " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
16890        if (adj > app.maxAdj) {
16891            adj = app.maxAdj;
16892            if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
16893                schedGroup = Process.THREAD_GROUP_DEFAULT;
16894            }
16895        }
16896
16897        // Do final modification to adj.  Everything we do between here and applying
16898        // the final setAdj must be done in this function, because we will also use
16899        // it when computing the final cached adj later.  Note that we don't need to
16900        // worry about this for max adj above, since max adj will always be used to
16901        // keep it out of the cached vaues.
16902        app.curAdj = app.modifyRawOomAdj(adj);
16903        app.curSchedGroup = schedGroup;
16904        app.curProcState = procState;
16905        app.foregroundActivities = foregroundActivities;
16906
16907        return app.curRawAdj;
16908    }
16909
16910    /**
16911     * Schedule PSS collection of a process.
16912     */
16913    void requestPssLocked(ProcessRecord proc, int procState) {
16914        if (mPendingPssProcesses.contains(proc)) {
16915            return;
16916        }
16917        if (mPendingPssProcesses.size() == 0) {
16918            mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG);
16919        }
16920        if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of: " + proc);
16921        proc.pssProcState = procState;
16922        mPendingPssProcesses.add(proc);
16923    }
16924
16925    /**
16926     * Schedule PSS collection of all processes.
16927     */
16928    void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) {
16929        if (!always) {
16930            if (now < (mLastFullPssTime +
16931                    (memLowered ? FULL_PSS_LOWERED_INTERVAL : FULL_PSS_MIN_INTERVAL))) {
16932                return;
16933            }
16934        }
16935        if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of all procs!  memLowered=" + memLowered);
16936        mLastFullPssTime = now;
16937        mFullPssPending = true;
16938        mPendingPssProcesses.ensureCapacity(mLruProcesses.size());
16939        mPendingPssProcesses.clear();
16940        for (int i=mLruProcesses.size()-1; i>=0; i--) {
16941            ProcessRecord app = mLruProcesses.get(i);
16942            if (memLowered || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) {
16943                app.pssProcState = app.setProcState;
16944                app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true,
16945                        isSleeping(), now);
16946                mPendingPssProcesses.add(app);
16947            }
16948        }
16949        mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG);
16950    }
16951
16952    /**
16953     * Ask a given process to GC right now.
16954     */
16955    final void performAppGcLocked(ProcessRecord app) {
16956        try {
16957            app.lastRequestedGc = SystemClock.uptimeMillis();
16958            if (app.thread != null) {
16959                if (app.reportLowMemory) {
16960                    app.reportLowMemory = false;
16961                    app.thread.scheduleLowMemory();
16962                } else {
16963                    app.thread.processInBackground();
16964                }
16965            }
16966        } catch (Exception e) {
16967            // whatever.
16968        }
16969    }
16970
16971    /**
16972     * Returns true if things are idle enough to perform GCs.
16973     */
16974    private final boolean canGcNowLocked() {
16975        boolean processingBroadcasts = false;
16976        for (BroadcastQueue q : mBroadcastQueues) {
16977            if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
16978                processingBroadcasts = true;
16979            }
16980        }
16981        return !processingBroadcasts
16982                && (isSleeping() || mStackSupervisor.allResumedActivitiesIdle());
16983    }
16984
16985    /**
16986     * Perform GCs on all processes that are waiting for it, but only
16987     * if things are idle.
16988     */
16989    final void performAppGcsLocked() {
16990        final int N = mProcessesToGc.size();
16991        if (N <= 0) {
16992            return;
16993        }
16994        if (canGcNowLocked()) {
16995            while (mProcessesToGc.size() > 0) {
16996                ProcessRecord proc = mProcessesToGc.remove(0);
16997                if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
16998                    if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
16999                            <= SystemClock.uptimeMillis()) {
17000                        // To avoid spamming the system, we will GC processes one
17001                        // at a time, waiting a few seconds between each.
17002                        performAppGcLocked(proc);
17003                        scheduleAppGcsLocked();
17004                        return;
17005                    } else {
17006                        // It hasn't been long enough since we last GCed this
17007                        // process...  put it in the list to wait for its time.
17008                        addProcessToGcListLocked(proc);
17009                        break;
17010                    }
17011                }
17012            }
17013
17014            scheduleAppGcsLocked();
17015        }
17016    }
17017
17018    /**
17019     * If all looks good, perform GCs on all processes waiting for them.
17020     */
17021    final void performAppGcsIfAppropriateLocked() {
17022        if (canGcNowLocked()) {
17023            performAppGcsLocked();
17024            return;
17025        }
17026        // Still not idle, wait some more.
17027        scheduleAppGcsLocked();
17028    }
17029
17030    /**
17031     * Schedule the execution of all pending app GCs.
17032     */
17033    final void scheduleAppGcsLocked() {
17034        mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
17035
17036        if (mProcessesToGc.size() > 0) {
17037            // Schedule a GC for the time to the next process.
17038            ProcessRecord proc = mProcessesToGc.get(0);
17039            Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
17040
17041            long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
17042            long now = SystemClock.uptimeMillis();
17043            if (when < (now+GC_TIMEOUT)) {
17044                when = now + GC_TIMEOUT;
17045            }
17046            mHandler.sendMessageAtTime(msg, when);
17047        }
17048    }
17049
17050    /**
17051     * Add a process to the array of processes waiting to be GCed.  Keeps the
17052     * list in sorted order by the last GC time.  The process can't already be
17053     * on the list.
17054     */
17055    final void addProcessToGcListLocked(ProcessRecord proc) {
17056        boolean added = false;
17057        for (int i=mProcessesToGc.size()-1; i>=0; i--) {
17058            if (mProcessesToGc.get(i).lastRequestedGc <
17059                    proc.lastRequestedGc) {
17060                added = true;
17061                mProcessesToGc.add(i+1, proc);
17062                break;
17063            }
17064        }
17065        if (!added) {
17066            mProcessesToGc.add(0, proc);
17067        }
17068    }
17069
17070    /**
17071     * Set up to ask a process to GC itself.  This will either do it
17072     * immediately, or put it on the list of processes to gc the next
17073     * time things are idle.
17074     */
17075    final void scheduleAppGcLocked(ProcessRecord app) {
17076        long now = SystemClock.uptimeMillis();
17077        if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
17078            return;
17079        }
17080        if (!mProcessesToGc.contains(app)) {
17081            addProcessToGcListLocked(app);
17082            scheduleAppGcsLocked();
17083        }
17084    }
17085
17086    final void checkExcessivePowerUsageLocked(boolean doKills) {
17087        updateCpuStatsNow();
17088
17089        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
17090        boolean doWakeKills = doKills;
17091        boolean doCpuKills = doKills;
17092        if (mLastPowerCheckRealtime == 0) {
17093            doWakeKills = false;
17094        }
17095        if (mLastPowerCheckUptime == 0) {
17096            doCpuKills = false;
17097        }
17098        if (stats.isScreenOn()) {
17099            doWakeKills = false;
17100        }
17101        final long curRealtime = SystemClock.elapsedRealtime();
17102        final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
17103        final long curUptime = SystemClock.uptimeMillis();
17104        final long uptimeSince = curUptime - mLastPowerCheckUptime;
17105        mLastPowerCheckRealtime = curRealtime;
17106        mLastPowerCheckUptime = curUptime;
17107        if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
17108            doWakeKills = false;
17109        }
17110        if (uptimeSince < CPU_MIN_CHECK_DURATION) {
17111            doCpuKills = false;
17112        }
17113        int i = mLruProcesses.size();
17114        while (i > 0) {
17115            i--;
17116            ProcessRecord app = mLruProcesses.get(i);
17117            if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
17118                long wtime;
17119                synchronized (stats) {
17120                    wtime = stats.getProcessWakeTime(app.info.uid,
17121                            app.pid, curRealtime);
17122                }
17123                long wtimeUsed = wtime - app.lastWakeTime;
17124                long cputimeUsed = app.curCpuTime - app.lastCpuTime;
17125                if (DEBUG_POWER) {
17126                    StringBuilder sb = new StringBuilder(128);
17127                    sb.append("Wake for ");
17128                    app.toShortString(sb);
17129                    sb.append(": over ");
17130                    TimeUtils.formatDuration(realtimeSince, sb);
17131                    sb.append(" used ");
17132                    TimeUtils.formatDuration(wtimeUsed, sb);
17133                    sb.append(" (");
17134                    sb.append((wtimeUsed*100)/realtimeSince);
17135                    sb.append("%)");
17136                    Slog.i(TAG, sb.toString());
17137                    sb.setLength(0);
17138                    sb.append("CPU for ");
17139                    app.toShortString(sb);
17140                    sb.append(": over ");
17141                    TimeUtils.formatDuration(uptimeSince, sb);
17142                    sb.append(" used ");
17143                    TimeUtils.formatDuration(cputimeUsed, sb);
17144                    sb.append(" (");
17145                    sb.append((cputimeUsed*100)/uptimeSince);
17146                    sb.append("%)");
17147                    Slog.i(TAG, sb.toString());
17148                }
17149                // If a process has held a wake lock for more
17150                // than 50% of the time during this period,
17151                // that sounds bad.  Kill!
17152                if (doWakeKills && realtimeSince > 0
17153                        && ((wtimeUsed*100)/realtimeSince) >= 50) {
17154                    synchronized (stats) {
17155                        stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
17156                                realtimeSince, wtimeUsed);
17157                    }
17158                    app.kill("excessive wake held " + wtimeUsed + " during " + realtimeSince, true);
17159                    app.baseProcessTracker.reportExcessiveWake(app.pkgList);
17160                } else if (doCpuKills && uptimeSince > 0
17161                        && ((cputimeUsed*100)/uptimeSince) >= 25) {
17162                    synchronized (stats) {
17163                        stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
17164                                uptimeSince, cputimeUsed);
17165                    }
17166                    app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince, true);
17167                    app.baseProcessTracker.reportExcessiveCpu(app.pkgList);
17168                } else {
17169                    app.lastWakeTime = wtime;
17170                    app.lastCpuTime = app.curCpuTime;
17171                }
17172            }
17173        }
17174    }
17175
17176    private final boolean applyOomAdjLocked(ProcessRecord app,
17177            ProcessRecord TOP_APP, boolean doingAll, long now) {
17178        boolean success = true;
17179
17180        if (app.curRawAdj != app.setRawAdj) {
17181            app.setRawAdj = app.curRawAdj;
17182        }
17183
17184        int changes = 0;
17185
17186        if (app.curAdj != app.setAdj) {
17187            ProcessList.setOomAdj(app.pid, app.info.uid, app.curAdj);
17188            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
17189                TAG, "Set " + app.pid + " " + app.processName +
17190                " adj " + app.curAdj + ": " + app.adjType);
17191            app.setAdj = app.curAdj;
17192        }
17193
17194        if (app.setSchedGroup != app.curSchedGroup) {
17195            app.setSchedGroup = app.curSchedGroup;
17196            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
17197                    "Setting process group of " + app.processName
17198                    + " to " + app.curSchedGroup);
17199            if (app.waitingToKill != null &&
17200                    app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
17201                app.kill(app.waitingToKill, true);
17202                success = false;
17203            } else {
17204                if (true) {
17205                    long oldId = Binder.clearCallingIdentity();
17206                    try {
17207                        Process.setProcessGroup(app.pid, app.curSchedGroup);
17208                    } catch (Exception e) {
17209                        Slog.w(TAG, "Failed setting process group of " + app.pid
17210                                + " to " + app.curSchedGroup);
17211                        e.printStackTrace();
17212                    } finally {
17213                        Binder.restoreCallingIdentity(oldId);
17214                    }
17215                } else {
17216                    if (app.thread != null) {
17217                        try {
17218                            app.thread.setSchedulingGroup(app.curSchedGroup);
17219                        } catch (RemoteException e) {
17220                        }
17221                    }
17222                }
17223                Process.setSwappiness(app.pid,
17224                        app.curSchedGroup <= Process.THREAD_GROUP_BG_NONINTERACTIVE);
17225            }
17226        }
17227        if (app.repForegroundActivities != app.foregroundActivities) {
17228            app.repForegroundActivities = app.foregroundActivities;
17229            changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
17230        }
17231        if (app.repProcState != app.curProcState) {
17232            app.repProcState = app.curProcState;
17233            changes |= ProcessChangeItem.CHANGE_PROCESS_STATE;
17234            if (app.thread != null) {
17235                try {
17236                    if (false) {
17237                        //RuntimeException h = new RuntimeException("here");
17238                        Slog.i(TAG, "Sending new process state " + app.repProcState
17239                                + " to " + app /*, h*/);
17240                    }
17241                    app.thread.setProcessState(app.repProcState);
17242                } catch (RemoteException e) {
17243                }
17244            }
17245        }
17246        if (app.setProcState < 0 || ProcessList.procStatesDifferForMem(app.curProcState,
17247                app.setProcState)) {
17248            app.lastStateTime = now;
17249            app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true,
17250                    isSleeping(), now);
17251            if (DEBUG_PSS) Slog.d(TAG, "Process state change from "
17252                    + ProcessList.makeProcStateString(app.setProcState) + " to "
17253                    + ProcessList.makeProcStateString(app.curProcState) + " next pss in "
17254                    + (app.nextPssTime-now) + ": " + app);
17255        } else {
17256            if (now > app.nextPssTime || (now > (app.lastPssTime+ProcessList.PSS_MAX_INTERVAL)
17257                    && now > (app.lastStateTime+ProcessList.PSS_MIN_TIME_FROM_STATE_CHANGE))) {
17258                requestPssLocked(app, app.setProcState);
17259                app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, false,
17260                        isSleeping(), now);
17261            } else if (false && DEBUG_PSS) {
17262                Slog.d(TAG, "Not requesting PSS of " + app + ": next=" + (app.nextPssTime-now));
17263            }
17264        }
17265        if (app.setProcState != app.curProcState) {
17266            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
17267                    "Proc state change of " + app.processName
17268                    + " to " + app.curProcState);
17269            boolean setImportant = app.setProcState < ActivityManager.PROCESS_STATE_SERVICE;
17270            boolean curImportant = app.curProcState < ActivityManager.PROCESS_STATE_SERVICE;
17271            if (setImportant && !curImportant) {
17272                // This app is no longer something we consider important enough to allow to
17273                // use arbitrary amounts of battery power.  Note
17274                // its current wake lock time to later know to kill it if
17275                // it is not behaving well.
17276                BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
17277                synchronized (stats) {
17278                    app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
17279                            app.pid, SystemClock.elapsedRealtime());
17280                }
17281                app.lastCpuTime = app.curCpuTime;
17282
17283            }
17284            app.setProcState = app.curProcState;
17285            if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
17286                app.notCachedSinceIdle = false;
17287            }
17288            if (!doingAll) {
17289                setProcessTrackerStateLocked(app, mProcessStats.getMemFactorLocked(), now);
17290            } else {
17291                app.procStateChanged = true;
17292            }
17293        }
17294
17295        if (changes != 0) {
17296            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
17297            int i = mPendingProcessChanges.size()-1;
17298            ProcessChangeItem item = null;
17299            while (i >= 0) {
17300                item = mPendingProcessChanges.get(i);
17301                if (item.pid == app.pid) {
17302                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
17303                    break;
17304                }
17305                i--;
17306            }
17307            if (i < 0) {
17308                // No existing item in pending changes; need a new one.
17309                final int NA = mAvailProcessChanges.size();
17310                if (NA > 0) {
17311                    item = mAvailProcessChanges.remove(NA-1);
17312                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
17313                } else {
17314                    item = new ProcessChangeItem();
17315                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
17316                }
17317                item.changes = 0;
17318                item.pid = app.pid;
17319                item.uid = app.info.uid;
17320                if (mPendingProcessChanges.size() == 0) {
17321                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
17322                            "*** Enqueueing dispatch processes changed!");
17323                    mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
17324                }
17325                mPendingProcessChanges.add(item);
17326            }
17327            item.changes |= changes;
17328            item.processState = app.repProcState;
17329            item.foregroundActivities = app.repForegroundActivities;
17330            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
17331                    + Integer.toHexString(System.identityHashCode(item))
17332                    + " " + app.toShortString() + ": changes=" + item.changes
17333                    + " procState=" + item.processState
17334                    + " foreground=" + item.foregroundActivities
17335                    + " type=" + app.adjType + " source=" + app.adjSource
17336                    + " target=" + app.adjTarget);
17337        }
17338
17339        return success;
17340    }
17341
17342    private final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) {
17343        if (proc.thread != null) {
17344            if (proc.baseProcessTracker != null) {
17345                proc.baseProcessTracker.setState(proc.repProcState, memFactor, now, proc.pkgList);
17346            }
17347            if (proc.repProcState >= 0) {
17348                mBatteryStatsService.noteProcessState(proc.processName, proc.info.uid,
17349                        proc.repProcState);
17350            }
17351        }
17352    }
17353
17354    private final boolean updateOomAdjLocked(ProcessRecord app, int cachedAdj,
17355            ProcessRecord TOP_APP, boolean doingAll, long now) {
17356        if (app.thread == null) {
17357            return false;
17358        }
17359
17360        computeOomAdjLocked(app, cachedAdj, TOP_APP, doingAll, now);
17361
17362        return applyOomAdjLocked(app, TOP_APP, doingAll, now);
17363    }
17364
17365    final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
17366            boolean oomAdj) {
17367        if (isForeground != proc.foregroundServices) {
17368            proc.foregroundServices = isForeground;
17369            ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
17370                    proc.info.uid);
17371            if (isForeground) {
17372                if (curProcs == null) {
17373                    curProcs = new ArrayList<ProcessRecord>();
17374                    mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
17375                }
17376                if (!curProcs.contains(proc)) {
17377                    curProcs.add(proc);
17378                    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
17379                            proc.info.packageName, proc.info.uid);
17380                }
17381            } else {
17382                if (curProcs != null) {
17383                    if (curProcs.remove(proc)) {
17384                        mBatteryStatsService.noteEvent(
17385                                BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
17386                                proc.info.packageName, proc.info.uid);
17387                        if (curProcs.size() <= 0) {
17388                            mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
17389                        }
17390                    }
17391                }
17392            }
17393            if (oomAdj) {
17394                updateOomAdjLocked();
17395            }
17396        }
17397    }
17398
17399    private final ActivityRecord resumedAppLocked() {
17400        ActivityRecord act = mStackSupervisor.resumedAppLocked();
17401        String pkg;
17402        int uid;
17403        if (act != null) {
17404            pkg = act.packageName;
17405            uid = act.info.applicationInfo.uid;
17406        } else {
17407            pkg = null;
17408            uid = -1;
17409        }
17410        // Has the UID or resumed package name changed?
17411        if (uid != mCurResumedUid || (pkg != mCurResumedPackage
17412                && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
17413            if (mCurResumedPackage != null) {
17414                mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
17415                        mCurResumedPackage, mCurResumedUid);
17416            }
17417            mCurResumedPackage = pkg;
17418            mCurResumedUid = uid;
17419            if (mCurResumedPackage != null) {
17420                mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
17421                        mCurResumedPackage, mCurResumedUid);
17422            }
17423        }
17424        return act;
17425    }
17426
17427    final boolean updateOomAdjLocked(ProcessRecord app) {
17428        final ActivityRecord TOP_ACT = resumedAppLocked();
17429        final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
17430        final boolean wasCached = app.cached;
17431
17432        mAdjSeq++;
17433
17434        // This is the desired cached adjusment we want to tell it to use.
17435        // If our app is currently cached, we know it, and that is it.  Otherwise,
17436        // we don't know it yet, and it needs to now be cached we will then
17437        // need to do a complete oom adj.
17438        final int cachedAdj = app.curRawAdj >= ProcessList.CACHED_APP_MIN_ADJ
17439                ? app.curRawAdj : ProcessList.UNKNOWN_ADJ;
17440        boolean success = updateOomAdjLocked(app, cachedAdj, TOP_APP, false,
17441                SystemClock.uptimeMillis());
17442        if (wasCached != app.cached || app.curRawAdj == ProcessList.UNKNOWN_ADJ) {
17443            // Changed to/from cached state, so apps after it in the LRU
17444            // list may also be changed.
17445            updateOomAdjLocked();
17446        }
17447        return success;
17448    }
17449
17450    final void updateOomAdjLocked() {
17451        final ActivityRecord TOP_ACT = resumedAppLocked();
17452        final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
17453        final long now = SystemClock.uptimeMillis();
17454        final long oldTime = now - ProcessList.MAX_EMPTY_TIME;
17455        final int N = mLruProcesses.size();
17456
17457        if (false) {
17458            RuntimeException e = new RuntimeException();
17459            e.fillInStackTrace();
17460            Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
17461        }
17462
17463        mAdjSeq++;
17464        mNewNumServiceProcs = 0;
17465        mNewNumAServiceProcs = 0;
17466
17467        final int emptyProcessLimit;
17468        final int cachedProcessLimit;
17469        if (mProcessLimit <= 0) {
17470            emptyProcessLimit = cachedProcessLimit = 0;
17471        } else if (mProcessLimit == 1) {
17472            emptyProcessLimit = 1;
17473            cachedProcessLimit = 0;
17474        } else {
17475            emptyProcessLimit = ProcessList.computeEmptyProcessLimit(mProcessLimit);
17476            cachedProcessLimit = mProcessLimit - emptyProcessLimit;
17477        }
17478
17479        // Let's determine how many processes we have running vs.
17480        // how many slots we have for background processes; we may want
17481        // to put multiple processes in a slot of there are enough of
17482        // them.
17483        int numSlots = (ProcessList.CACHED_APP_MAX_ADJ
17484                - ProcessList.CACHED_APP_MIN_ADJ + 1) / 2;
17485        int numEmptyProcs = N - mNumNonCachedProcs - mNumCachedHiddenProcs;
17486        if (numEmptyProcs > cachedProcessLimit) {
17487            // If there are more empty processes than our limit on cached
17488            // processes, then use the cached process limit for the factor.
17489            // This ensures that the really old empty processes get pushed
17490            // down to the bottom, so if we are running low on memory we will
17491            // have a better chance at keeping around more cached processes
17492            // instead of a gazillion empty processes.
17493            numEmptyProcs = cachedProcessLimit;
17494        }
17495        int emptyFactor = numEmptyProcs/numSlots;
17496        if (emptyFactor < 1) emptyFactor = 1;
17497        int cachedFactor = (mNumCachedHiddenProcs > 0 ? mNumCachedHiddenProcs : 1)/numSlots;
17498        if (cachedFactor < 1) cachedFactor = 1;
17499        int stepCached = 0;
17500        int stepEmpty = 0;
17501        int numCached = 0;
17502        int numEmpty = 0;
17503        int numTrimming = 0;
17504
17505        mNumNonCachedProcs = 0;
17506        mNumCachedHiddenProcs = 0;
17507
17508        // First update the OOM adjustment for each of the
17509        // application processes based on their current state.
17510        int curCachedAdj = ProcessList.CACHED_APP_MIN_ADJ;
17511        int nextCachedAdj = curCachedAdj+1;
17512        int curEmptyAdj = ProcessList.CACHED_APP_MIN_ADJ;
17513        int nextEmptyAdj = curEmptyAdj+2;
17514        for (int i=N-1; i>=0; i--) {
17515            ProcessRecord app = mLruProcesses.get(i);
17516            if (!app.killedByAm && app.thread != null) {
17517                app.procStateChanged = false;
17518                computeOomAdjLocked(app, ProcessList.UNKNOWN_ADJ, TOP_APP, true, now);
17519
17520                // If we haven't yet assigned the final cached adj
17521                // to the process, do that now.
17522                if (app.curAdj >= ProcessList.UNKNOWN_ADJ) {
17523                    switch (app.curProcState) {
17524                        case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY:
17525                        case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
17526                            // This process is a cached process holding activities...
17527                            // assign it the next cached value for that type, and then
17528                            // step that cached level.
17529                            app.curRawAdj = curCachedAdj;
17530                            app.curAdj = app.modifyRawOomAdj(curCachedAdj);
17531                            if (DEBUG_LRU && false) Slog.d(TAG, "Assigning activity LRU #" + i
17532                                    + " adj: " + app.curAdj + " (curCachedAdj=" + curCachedAdj
17533                                    + ")");
17534                            if (curCachedAdj != nextCachedAdj) {
17535                                stepCached++;
17536                                if (stepCached >= cachedFactor) {
17537                                    stepCached = 0;
17538                                    curCachedAdj = nextCachedAdj;
17539                                    nextCachedAdj += 2;
17540                                    if (nextCachedAdj > ProcessList.CACHED_APP_MAX_ADJ) {
17541                                        nextCachedAdj = ProcessList.CACHED_APP_MAX_ADJ;
17542                                    }
17543                                }
17544                            }
17545                            break;
17546                        default:
17547                            // For everything else, assign next empty cached process
17548                            // level and bump that up.  Note that this means that
17549                            // long-running services that have dropped down to the
17550                            // cached level will be treated as empty (since their process
17551                            // state is still as a service), which is what we want.
17552                            app.curRawAdj = curEmptyAdj;
17553                            app.curAdj = app.modifyRawOomAdj(curEmptyAdj);
17554                            if (DEBUG_LRU && false) Slog.d(TAG, "Assigning empty LRU #" + i
17555                                    + " adj: " + app.curAdj + " (curEmptyAdj=" + curEmptyAdj
17556                                    + ")");
17557                            if (curEmptyAdj != nextEmptyAdj) {
17558                                stepEmpty++;
17559                                if (stepEmpty >= emptyFactor) {
17560                                    stepEmpty = 0;
17561                                    curEmptyAdj = nextEmptyAdj;
17562                                    nextEmptyAdj += 2;
17563                                    if (nextEmptyAdj > ProcessList.CACHED_APP_MAX_ADJ) {
17564                                        nextEmptyAdj = ProcessList.CACHED_APP_MAX_ADJ;
17565                                    }
17566                                }
17567                            }
17568                            break;
17569                    }
17570                }
17571
17572                applyOomAdjLocked(app, TOP_APP, true, now);
17573
17574                // Count the number of process types.
17575                switch (app.curProcState) {
17576                    case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY:
17577                    case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
17578                        mNumCachedHiddenProcs++;
17579                        numCached++;
17580                        if (numCached > cachedProcessLimit) {
17581                            app.kill("cached #" + numCached, true);
17582                        }
17583                        break;
17584                    case ActivityManager.PROCESS_STATE_CACHED_EMPTY:
17585                        if (numEmpty > ProcessList.TRIM_EMPTY_APPS
17586                                && app.lastActivityTime < oldTime) {
17587                            app.kill("empty for "
17588                                    + ((oldTime + ProcessList.MAX_EMPTY_TIME - app.lastActivityTime)
17589                                    / 1000) + "s", true);
17590                        } else {
17591                            numEmpty++;
17592                            if (numEmpty > emptyProcessLimit) {
17593                                app.kill("empty #" + numEmpty, true);
17594                            }
17595                        }
17596                        break;
17597                    default:
17598                        mNumNonCachedProcs++;
17599                        break;
17600                }
17601
17602                if (app.isolated && app.services.size() <= 0) {
17603                    // If this is an isolated process, and there are no
17604                    // services running in it, then the process is no longer
17605                    // needed.  We agressively kill these because we can by
17606                    // definition not re-use the same process again, and it is
17607                    // good to avoid having whatever code was running in them
17608                    // left sitting around after no longer needed.
17609                    app.kill("isolated not needed", true);
17610                }
17611
17612                if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME
17613                        && !app.killedByAm) {
17614                    numTrimming++;
17615                }
17616            }
17617        }
17618
17619        mNumServiceProcs = mNewNumServiceProcs;
17620
17621        // Now determine the memory trimming level of background processes.
17622        // Unfortunately we need to start at the back of the list to do this
17623        // properly.  We only do this if the number of background apps we
17624        // are managing to keep around is less than half the maximum we desire;
17625        // if we are keeping a good number around, we'll let them use whatever
17626        // memory they want.
17627        final int numCachedAndEmpty = numCached + numEmpty;
17628        int memFactor;
17629        if (numCached <= ProcessList.TRIM_CACHED_APPS
17630                && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
17631            if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
17632                memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL;
17633            } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
17634                memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW;
17635            } else {
17636                memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE;
17637            }
17638        } else {
17639            memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
17640        }
17641        // We always allow the memory level to go up (better).  We only allow it to go
17642        // down if we are in a state where that is allowed, *and* the total number of processes
17643        // has gone down since last time.
17644        if (DEBUG_OOM_ADJ) Slog.d(TAG, "oom: memFactor=" + memFactor + " last=" + mLastMemoryLevel
17645                + " allowLow=" + mAllowLowerMemLevel + " numProcs=" + mLruProcesses.size()
17646                + " last=" + mLastNumProcesses);
17647        if (memFactor > mLastMemoryLevel) {
17648            if (!mAllowLowerMemLevel || mLruProcesses.size() >= mLastNumProcesses) {
17649                memFactor = mLastMemoryLevel;
17650                if (DEBUG_OOM_ADJ) Slog.d(TAG, "Keeping last mem factor!");
17651            }
17652        }
17653        mLastMemoryLevel = memFactor;
17654        mLastNumProcesses = mLruProcesses.size();
17655        boolean allChanged = mProcessStats.setMemFactorLocked(memFactor, !isSleeping(), now);
17656        final int trackerMemFactor = mProcessStats.getMemFactorLocked();
17657        if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) {
17658            if (mLowRamStartTime == 0) {
17659                mLowRamStartTime = now;
17660            }
17661            int step = 0;
17662            int fgTrimLevel;
17663            switch (memFactor) {
17664                case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
17665                    fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
17666                    break;
17667                case ProcessStats.ADJ_MEM_FACTOR_LOW:
17668                    fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
17669                    break;
17670                default:
17671                    fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
17672                    break;
17673            }
17674            int factor = numTrimming/3;
17675            int minFactor = 2;
17676            if (mHomeProcess != null) minFactor++;
17677            if (mPreviousProcess != null) minFactor++;
17678            if (factor < minFactor) factor = minFactor;
17679            int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
17680            for (int i=N-1; i>=0; i--) {
17681                ProcessRecord app = mLruProcesses.get(i);
17682                if (allChanged || app.procStateChanged) {
17683                    setProcessTrackerStateLocked(app, trackerMemFactor, now);
17684                    app.procStateChanged = false;
17685                }
17686                if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME
17687                        && !app.killedByAm) {
17688                    if (app.trimMemoryLevel < curLevel && app.thread != null) {
17689                        try {
17690                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
17691                                    "Trimming memory of " + app.processName
17692                                    + " to " + curLevel);
17693                            app.thread.scheduleTrimMemory(curLevel);
17694                        } catch (RemoteException e) {
17695                        }
17696                        if (false) {
17697                            // For now we won't do this; our memory trimming seems
17698                            // to be good enough at this point that destroying
17699                            // activities causes more harm than good.
17700                            if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
17701                                    && app != mHomeProcess && app != mPreviousProcess) {
17702                                // Need to do this on its own message because the stack may not
17703                                // be in a consistent state at this point.
17704                                // For these apps we will also finish their activities
17705                                // to help them free memory.
17706                                mStackSupervisor.scheduleDestroyAllActivities(app, "trim");
17707                            }
17708                        }
17709                    }
17710                    app.trimMemoryLevel = curLevel;
17711                    step++;
17712                    if (step >= factor) {
17713                        step = 0;
17714                        switch (curLevel) {
17715                            case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
17716                                curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
17717                                break;
17718                            case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
17719                                curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
17720                                break;
17721                        }
17722                    }
17723                } else if (app.curProcState == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
17724                    if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
17725                            && app.thread != null) {
17726                        try {
17727                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
17728                                    "Trimming memory of heavy-weight " + app.processName
17729                                    + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
17730                            app.thread.scheduleTrimMemory(
17731                                    ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
17732                        } catch (RemoteException e) {
17733                        }
17734                    }
17735                    app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
17736                } else {
17737                    if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
17738                            || app.systemNoUi) && app.pendingUiClean) {
17739                        // If this application is now in the background and it
17740                        // had done UI, then give it the special trim level to
17741                        // have it free UI resources.
17742                        final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
17743                        if (app.trimMemoryLevel < level && app.thread != null) {
17744                            try {
17745                                if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
17746                                        "Trimming memory of bg-ui " + app.processName
17747                                        + " to " + level);
17748                                app.thread.scheduleTrimMemory(level);
17749                            } catch (RemoteException e) {
17750                            }
17751                        }
17752                        app.pendingUiClean = false;
17753                    }
17754                    if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
17755                        try {
17756                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
17757                                    "Trimming memory of fg " + app.processName
17758                                    + " to " + fgTrimLevel);
17759                            app.thread.scheduleTrimMemory(fgTrimLevel);
17760                        } catch (RemoteException e) {
17761                        }
17762                    }
17763                    app.trimMemoryLevel = fgTrimLevel;
17764                }
17765            }
17766        } else {
17767            if (mLowRamStartTime != 0) {
17768                mLowRamTimeSinceLastIdle += now - mLowRamStartTime;
17769                mLowRamStartTime = 0;
17770            }
17771            for (int i=N-1; i>=0; i--) {
17772                ProcessRecord app = mLruProcesses.get(i);
17773                if (allChanged || app.procStateChanged) {
17774                    setProcessTrackerStateLocked(app, trackerMemFactor, now);
17775                    app.procStateChanged = false;
17776                }
17777                if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
17778                        || app.systemNoUi) && app.pendingUiClean) {
17779                    if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
17780                            && app.thread != null) {
17781                        try {
17782                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
17783                                    "Trimming memory of ui hidden " + app.processName
17784                                    + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
17785                            app.thread.scheduleTrimMemory(
17786                                    ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
17787                        } catch (RemoteException e) {
17788                        }
17789                    }
17790                    app.pendingUiClean = false;
17791                }
17792                app.trimMemoryLevel = 0;
17793            }
17794        }
17795
17796        if (mAlwaysFinishActivities) {
17797            // Need to do this on its own message because the stack may not
17798            // be in a consistent state at this point.
17799            mStackSupervisor.scheduleDestroyAllActivities(null, "always-finish");
17800        }
17801
17802        if (allChanged) {
17803            requestPssAllProcsLocked(now, false, mProcessStats.isMemFactorLowered());
17804        }
17805
17806        if (mProcessStats.shouldWriteNowLocked(now)) {
17807            mHandler.post(new Runnable() {
17808                @Override public void run() {
17809                    synchronized (ActivityManagerService.this) {
17810                        mProcessStats.writeStateAsyncLocked();
17811                    }
17812                }
17813            });
17814        }
17815
17816        if (DEBUG_OOM_ADJ) {
17817            if (false) {
17818                RuntimeException here = new RuntimeException("here");
17819                here.fillInStackTrace();
17820                Slog.d(TAG, "Did OOM ADJ in " + (SystemClock.uptimeMillis()-now) + "ms", here);
17821            } else {
17822                Slog.d(TAG, "Did OOM ADJ in " + (SystemClock.uptimeMillis()-now) + "ms");
17823            }
17824        }
17825    }
17826
17827    final void trimApplications() {
17828        synchronized (this) {
17829            int i;
17830
17831            // First remove any unused application processes whose package
17832            // has been removed.
17833            for (i=mRemovedProcesses.size()-1; i>=0; i--) {
17834                final ProcessRecord app = mRemovedProcesses.get(i);
17835                if (app.activities.size() == 0
17836                        && app.curReceiver == null && app.services.size() == 0) {
17837                    Slog.i(
17838                        TAG, "Exiting empty application process "
17839                        + app.processName + " ("
17840                        + (app.thread != null ? app.thread.asBinder() : null)
17841                        + ")\n");
17842                    if (app.pid > 0 && app.pid != MY_PID) {
17843                        app.kill("empty", false);
17844                    } else {
17845                        try {
17846                            app.thread.scheduleExit();
17847                        } catch (Exception e) {
17848                            // Ignore exceptions.
17849                        }
17850                    }
17851                    cleanUpApplicationRecordLocked(app, false, true, -1);
17852                    mRemovedProcesses.remove(i);
17853
17854                    if (app.persistent) {
17855                        addAppLocked(app.info, false, null /* ABI override */);
17856                    }
17857                }
17858            }
17859
17860            // Now update the oom adj for all processes.
17861            updateOomAdjLocked();
17862        }
17863    }
17864
17865    /** This method sends the specified signal to each of the persistent apps */
17866    public void signalPersistentProcesses(int sig) throws RemoteException {
17867        if (sig != Process.SIGNAL_USR1) {
17868            throw new SecurityException("Only SIGNAL_USR1 is allowed");
17869        }
17870
17871        synchronized (this) {
17872            if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
17873                    != PackageManager.PERMISSION_GRANTED) {
17874                throw new SecurityException("Requires permission "
17875                        + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
17876            }
17877
17878            for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
17879                ProcessRecord r = mLruProcesses.get(i);
17880                if (r.thread != null && r.persistent) {
17881                    Process.sendSignal(r.pid, sig);
17882                }
17883            }
17884        }
17885    }
17886
17887    private void stopProfilerLocked(ProcessRecord proc, int profileType) {
17888        if (proc == null || proc == mProfileProc) {
17889            proc = mProfileProc;
17890            profileType = mProfileType;
17891            clearProfilerLocked();
17892        }
17893        if (proc == null) {
17894            return;
17895        }
17896        try {
17897            proc.thread.profilerControl(false, null, profileType);
17898        } catch (RemoteException e) {
17899            throw new IllegalStateException("Process disappeared");
17900        }
17901    }
17902
17903    private void clearProfilerLocked() {
17904        if (mProfileFd != null) {
17905            try {
17906                mProfileFd.close();
17907            } catch (IOException e) {
17908            }
17909        }
17910        mProfileApp = null;
17911        mProfileProc = null;
17912        mProfileFile = null;
17913        mProfileType = 0;
17914        mAutoStopProfiler = false;
17915        mSamplingInterval = 0;
17916    }
17917
17918    public boolean profileControl(String process, int userId, boolean start,
17919            ProfilerInfo profilerInfo, int profileType) throws RemoteException {
17920
17921        try {
17922            synchronized (this) {
17923                // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17924                // its own permission.
17925                if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17926                        != PackageManager.PERMISSION_GRANTED) {
17927                    throw new SecurityException("Requires permission "
17928                            + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17929                }
17930
17931                if (start && (profilerInfo == null || profilerInfo.profileFd == null)) {
17932                    throw new IllegalArgumentException("null profile info or fd");
17933                }
17934
17935                ProcessRecord proc = null;
17936                if (process != null) {
17937                    proc = findProcessLocked(process, userId, "profileControl");
17938                }
17939
17940                if (start && (proc == null || proc.thread == null)) {
17941                    throw new IllegalArgumentException("Unknown process: " + process);
17942                }
17943
17944                if (start) {
17945                    stopProfilerLocked(null, 0);
17946                    setProfileApp(proc.info, proc.processName, profilerInfo);
17947                    mProfileProc = proc;
17948                    mProfileType = profileType;
17949                    ParcelFileDescriptor fd = profilerInfo.profileFd;
17950                    try {
17951                        fd = fd.dup();
17952                    } catch (IOException e) {
17953                        fd = null;
17954                    }
17955                    profilerInfo.profileFd = fd;
17956                    proc.thread.profilerControl(start, profilerInfo, profileType);
17957                    fd = null;
17958                    mProfileFd = null;
17959                } else {
17960                    stopProfilerLocked(proc, profileType);
17961                    if (profilerInfo != null && profilerInfo.profileFd != null) {
17962                        try {
17963                            profilerInfo.profileFd.close();
17964                        } catch (IOException e) {
17965                        }
17966                    }
17967                }
17968
17969                return true;
17970            }
17971        } catch (RemoteException e) {
17972            throw new IllegalStateException("Process disappeared");
17973        } finally {
17974            if (profilerInfo != null && profilerInfo.profileFd != null) {
17975                try {
17976                    profilerInfo.profileFd.close();
17977                } catch (IOException e) {
17978                }
17979            }
17980        }
17981    }
17982
17983    private ProcessRecord findProcessLocked(String process, int userId, String callName) {
17984        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
17985                userId, true, ALLOW_FULL_ONLY, callName, null);
17986        ProcessRecord proc = null;
17987        try {
17988            int pid = Integer.parseInt(process);
17989            synchronized (mPidsSelfLocked) {
17990                proc = mPidsSelfLocked.get(pid);
17991            }
17992        } catch (NumberFormatException e) {
17993        }
17994
17995        if (proc == null) {
17996            ArrayMap<String, SparseArray<ProcessRecord>> all
17997                    = mProcessNames.getMap();
17998            SparseArray<ProcessRecord> procs = all.get(process);
17999            if (procs != null && procs.size() > 0) {
18000                proc = procs.valueAt(0);
18001                if (userId != UserHandle.USER_ALL && proc.userId != userId) {
18002                    for (int i=1; i<procs.size(); i++) {
18003                        ProcessRecord thisProc = procs.valueAt(i);
18004                        if (thisProc.userId == userId) {
18005                            proc = thisProc;
18006                            break;
18007                        }
18008                    }
18009                }
18010            }
18011        }
18012
18013        return proc;
18014    }
18015
18016    public boolean dumpHeap(String process, int userId, boolean managed,
18017            String path, ParcelFileDescriptor fd) throws RemoteException {
18018
18019        try {
18020            synchronized (this) {
18021                // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
18022                // its own permission (same as profileControl).
18023                if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
18024                        != PackageManager.PERMISSION_GRANTED) {
18025                    throw new SecurityException("Requires permission "
18026                            + android.Manifest.permission.SET_ACTIVITY_WATCHER);
18027                }
18028
18029                if (fd == null) {
18030                    throw new IllegalArgumentException("null fd");
18031                }
18032
18033                ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
18034                if (proc == null || proc.thread == null) {
18035                    throw new IllegalArgumentException("Unknown process: " + process);
18036                }
18037
18038                boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
18039                if (!isDebuggable) {
18040                    if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
18041                        throw new SecurityException("Process not debuggable: " + proc);
18042                    }
18043                }
18044
18045                proc.thread.dumpHeap(managed, path, fd);
18046                fd = null;
18047                return true;
18048            }
18049        } catch (RemoteException e) {
18050            throw new IllegalStateException("Process disappeared");
18051        } finally {
18052            if (fd != null) {
18053                try {
18054                    fd.close();
18055                } catch (IOException e) {
18056                }
18057            }
18058        }
18059    }
18060
18061    /** In this method we try to acquire our lock to make sure that we have not deadlocked */
18062    public void monitor() {
18063        synchronized (this) { }
18064    }
18065
18066    void onCoreSettingsChange(Bundle settings) {
18067        for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
18068            ProcessRecord processRecord = mLruProcesses.get(i);
18069            try {
18070                if (processRecord.thread != null) {
18071                    processRecord.thread.setCoreSettings(settings);
18072                }
18073            } catch (RemoteException re) {
18074                /* ignore */
18075            }
18076        }
18077    }
18078
18079    // Multi-user methods
18080
18081    /**
18082     * Start user, if its not already running, but don't bring it to foreground.
18083     */
18084    @Override
18085    public boolean startUserInBackground(final int userId) {
18086        return startUser(userId, /* foreground */ false);
18087    }
18088
18089    /**
18090     * Start user, if its not already running, and bring it to foreground.
18091     */
18092    boolean startUserInForeground(final int userId, Dialog dlg) {
18093        boolean result = startUser(userId, /* foreground */ true);
18094        dlg.dismiss();
18095        return result;
18096    }
18097
18098    /**
18099     * Refreshes the list of users related to the current user when either a
18100     * user switch happens or when a new related user is started in the
18101     * background.
18102     */
18103    private void updateCurrentProfileIdsLocked() {
18104        final List<UserInfo> profiles = getUserManagerLocked().getProfiles(
18105                mCurrentUserId, false /* enabledOnly */);
18106        int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
18107        for (int i = 0; i < currentProfileIds.length; i++) {
18108            currentProfileIds[i] = profiles.get(i).id;
18109        }
18110        mCurrentProfileIds = currentProfileIds;
18111
18112        synchronized (mUserProfileGroupIdsSelfLocked) {
18113            mUserProfileGroupIdsSelfLocked.clear();
18114            final List<UserInfo> users = getUserManagerLocked().getUsers(false);
18115            for (int i = 0; i < users.size(); i++) {
18116                UserInfo user = users.get(i);
18117                if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
18118                    mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
18119                }
18120            }
18121        }
18122    }
18123
18124    private Set getProfileIdsLocked(int userId) {
18125        Set userIds = new HashSet<Integer>();
18126        final List<UserInfo> profiles = getUserManagerLocked().getProfiles(
18127                userId, false /* enabledOnly */);
18128        for (UserInfo user : profiles) {
18129            userIds.add(Integer.valueOf(user.id));
18130        }
18131        return userIds;
18132    }
18133
18134    @Override
18135    public boolean switchUser(final int userId) {
18136        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
18137        String userName;
18138        synchronized (this) {
18139            UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
18140            if (userInfo == null) {
18141                Slog.w(TAG, "No user info for user #" + userId);
18142                return false;
18143            }
18144            if (userInfo.isManagedProfile()) {
18145                Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
18146                return false;
18147            }
18148            userName = userInfo.name;
18149            mTargetUserId = userId;
18150        }
18151        mHandler.removeMessages(START_USER_SWITCH_MSG);
18152        mHandler.sendMessage(mHandler.obtainMessage(START_USER_SWITCH_MSG, userId, 0, userName));
18153        return true;
18154    }
18155
18156    private void showUserSwitchDialog(int userId, String userName) {
18157        // The dialog will show and then initiate the user switch by calling startUserInForeground
18158        Dialog d = new UserSwitchingDialog(this, mContext, userId, userName,
18159                true /* above system */);
18160        d.show();
18161    }
18162
18163    private boolean startUser(final int userId, final boolean foreground) {
18164        if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
18165                != PackageManager.PERMISSION_GRANTED) {
18166            String msg = "Permission Denial: switchUser() from pid="
18167                    + Binder.getCallingPid()
18168                    + ", uid=" + Binder.getCallingUid()
18169                    + " requires " + INTERACT_ACROSS_USERS_FULL;
18170            Slog.w(TAG, msg);
18171            throw new SecurityException(msg);
18172        }
18173
18174        if (DEBUG_MU) Slog.i(TAG_MU, "starting userid:" + userId + " fore:" + foreground);
18175
18176        final long ident = Binder.clearCallingIdentity();
18177        try {
18178            synchronized (this) {
18179                final int oldUserId = mCurrentUserId;
18180                if (oldUserId == userId) {
18181                    return true;
18182                }
18183
18184                mStackSupervisor.setLockTaskModeLocked(null, false);
18185
18186                final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
18187                if (userInfo == null) {
18188                    Slog.w(TAG, "No user info for user #" + userId);
18189                    return false;
18190                }
18191                if (foreground && userInfo.isManagedProfile()) {
18192                    Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
18193                    return false;
18194                }
18195
18196                if (foreground) {
18197                    mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
18198                            R.anim.screen_user_enter);
18199                }
18200
18201                boolean needStart = false;
18202
18203                // If the user we are switching to is not currently started, then
18204                // we need to start it now.
18205                if (mStartedUsers.get(userId) == null) {
18206                    mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
18207                    updateStartedUserArrayLocked();
18208                    needStart = true;
18209                }
18210
18211                final Integer userIdInt = Integer.valueOf(userId);
18212                mUserLru.remove(userIdInt);
18213                mUserLru.add(userIdInt);
18214
18215                if (foreground) {
18216                    mCurrentUserId = userId;
18217                    mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
18218                    updateCurrentProfileIdsLocked();
18219                    mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
18220                    // Once the internal notion of the active user has switched, we lock the device
18221                    // with the option to show the user switcher on the keyguard.
18222                    mWindowManager.lockNow(null);
18223                } else {
18224                    final Integer currentUserIdInt = Integer.valueOf(mCurrentUserId);
18225                    updateCurrentProfileIdsLocked();
18226                    mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
18227                    mUserLru.remove(currentUserIdInt);
18228                    mUserLru.add(currentUserIdInt);
18229                }
18230
18231                final UserStartedState uss = mStartedUsers.get(userId);
18232
18233                // Make sure user is in the started state.  If it is currently
18234                // stopping, we need to knock that off.
18235                if (uss.mState == UserStartedState.STATE_STOPPING) {
18236                    // If we are stopping, we haven't sent ACTION_SHUTDOWN,
18237                    // so we can just fairly silently bring the user back from
18238                    // the almost-dead.
18239                    uss.mState = UserStartedState.STATE_RUNNING;
18240                    updateStartedUserArrayLocked();
18241                    needStart = true;
18242                } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
18243                    // This means ACTION_SHUTDOWN has been sent, so we will
18244                    // need to treat this as a new boot of the user.
18245                    uss.mState = UserStartedState.STATE_BOOTING;
18246                    updateStartedUserArrayLocked();
18247                    needStart = true;
18248                }
18249
18250                if (uss.mState == UserStartedState.STATE_BOOTING) {
18251                    // Booting up a new user, need to tell system services about it.
18252                    // Note that this is on the same handler as scheduling of broadcasts,
18253                    // which is important because it needs to go first.
18254                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
18255                }
18256
18257                if (foreground) {
18258                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
18259                            oldUserId));
18260                    mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
18261                    mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
18262                    mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
18263                            oldUserId, userId, uss));
18264                    mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
18265                            oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
18266                }
18267
18268                if (needStart) {
18269                    // Send USER_STARTED broadcast
18270                    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
18271                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18272                            | Intent.FLAG_RECEIVER_FOREGROUND);
18273                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18274                    broadcastIntentLocked(null, null, intent,
18275                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
18276                            false, false, MY_PID, Process.SYSTEM_UID, userId);
18277                }
18278
18279                if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
18280                    if (userId != UserHandle.USER_OWNER) {
18281                        Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
18282                        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
18283                        broadcastIntentLocked(null, null, intent, null,
18284                                new IIntentReceiver.Stub() {
18285                                    public void performReceive(Intent intent, int resultCode,
18286                                            String data, Bundle extras, boolean ordered,
18287                                            boolean sticky, int sendingUser) {
18288                                        onUserInitialized(uss, foreground, oldUserId, userId);
18289                                    }
18290                                }, 0, null, null, null, AppOpsManager.OP_NONE,
18291                                true, false, MY_PID, Process.SYSTEM_UID,
18292                                userId);
18293                        uss.initializing = true;
18294                    } else {
18295                        getUserManagerLocked().makeInitialized(userInfo.id);
18296                    }
18297                }
18298
18299                if (foreground) {
18300                    if (!uss.initializing) {
18301                        moveUserToForeground(uss, oldUserId, userId);
18302                    }
18303                } else {
18304                    mStackSupervisor.startBackgroundUserLocked(userId, uss);
18305                }
18306
18307                if (needStart) {
18308                    Intent intent = new Intent(Intent.ACTION_USER_STARTING);
18309                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
18310                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18311                    broadcastIntentLocked(null, null, intent,
18312                            null, new IIntentReceiver.Stub() {
18313                                @Override
18314                                public void performReceive(Intent intent, int resultCode, String data,
18315                                        Bundle extras, boolean ordered, boolean sticky, int sendingUser)
18316                                        throws RemoteException {
18317                                }
18318                            }, 0, null, null,
18319                            INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
18320                            true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
18321                }
18322            }
18323        } finally {
18324            Binder.restoreCallingIdentity(ident);
18325        }
18326
18327        return true;
18328    }
18329
18330    void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
18331        long ident = Binder.clearCallingIdentity();
18332        try {
18333            Intent intent;
18334            if (oldUserId >= 0) {
18335                // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
18336                List<UserInfo> profiles = mUserManager.getProfiles(oldUserId, false);
18337                int count = profiles.size();
18338                for (int i = 0; i < count; i++) {
18339                    int profileUserId = profiles.get(i).id;
18340                    intent = new Intent(Intent.ACTION_USER_BACKGROUND);
18341                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18342                            | Intent.FLAG_RECEIVER_FOREGROUND);
18343                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
18344                    broadcastIntentLocked(null, null, intent,
18345                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
18346                            false, false, MY_PID, Process.SYSTEM_UID, profileUserId);
18347                }
18348            }
18349            if (newUserId >= 0) {
18350                // Send USER_FOREGROUND broadcast to all profiles of the incoming user
18351                List<UserInfo> profiles = mUserManager.getProfiles(newUserId, false);
18352                int count = profiles.size();
18353                for (int i = 0; i < count; i++) {
18354                    int profileUserId = profiles.get(i).id;
18355                    intent = new Intent(Intent.ACTION_USER_FOREGROUND);
18356                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18357                            | Intent.FLAG_RECEIVER_FOREGROUND);
18358                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
18359                    broadcastIntentLocked(null, null, intent,
18360                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
18361                            false, false, MY_PID, Process.SYSTEM_UID, profileUserId);
18362                }
18363                intent = new Intent(Intent.ACTION_USER_SWITCHED);
18364                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18365                        | Intent.FLAG_RECEIVER_FOREGROUND);
18366                intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
18367                broadcastIntentLocked(null, null, intent,
18368                        null, null, 0, null, null,
18369                        android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
18370                        false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
18371            }
18372        } finally {
18373            Binder.restoreCallingIdentity(ident);
18374        }
18375    }
18376
18377    void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
18378            final int newUserId) {
18379        final int N = mUserSwitchObservers.beginBroadcast();
18380        if (N > 0) {
18381            final IRemoteCallback callback = new IRemoteCallback.Stub() {
18382                int mCount = 0;
18383                @Override
18384                public void sendResult(Bundle data) throws RemoteException {
18385                    synchronized (ActivityManagerService.this) {
18386                        if (mCurUserSwitchCallback == this) {
18387                            mCount++;
18388                            if (mCount == N) {
18389                                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
18390                            }
18391                        }
18392                    }
18393                }
18394            };
18395            synchronized (this) {
18396                uss.switching = true;
18397                mCurUserSwitchCallback = callback;
18398            }
18399            for (int i=0; i<N; i++) {
18400                try {
18401                    mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
18402                            newUserId, callback);
18403                } catch (RemoteException e) {
18404                }
18405            }
18406        } else {
18407            synchronized (this) {
18408                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
18409            }
18410        }
18411        mUserSwitchObservers.finishBroadcast();
18412    }
18413
18414    void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
18415        synchronized (this) {
18416            Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
18417            sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
18418        }
18419    }
18420
18421    void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
18422        mCurUserSwitchCallback = null;
18423        mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
18424        mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
18425                oldUserId, newUserId, uss));
18426    }
18427
18428    void onUserInitialized(UserStartedState uss, boolean foreground, int oldUserId, int newUserId) {
18429        synchronized (this) {
18430            if (foreground) {
18431                moveUserToForeground(uss, oldUserId, newUserId);
18432            }
18433        }
18434
18435        completeSwitchAndInitalize(uss, newUserId, true, false);
18436    }
18437
18438    void moveUserToForeground(UserStartedState uss, int oldUserId, int newUserId) {
18439        boolean homeInFront = mStackSupervisor.switchUserLocked(newUserId, uss);
18440        if (homeInFront) {
18441            startHomeActivityLocked(newUserId);
18442        } else {
18443            mStackSupervisor.resumeTopActivitiesLocked();
18444        }
18445        EventLogTags.writeAmSwitchUser(newUserId);
18446        getUserManagerLocked().userForeground(newUserId);
18447        sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
18448    }
18449
18450    void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
18451        completeSwitchAndInitalize(uss, newUserId, false, true);
18452    }
18453
18454    void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
18455            boolean clearInitializing, boolean clearSwitching) {
18456        boolean unfrozen = false;
18457        synchronized (this) {
18458            if (clearInitializing) {
18459                uss.initializing = false;
18460                getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
18461            }
18462            if (clearSwitching) {
18463                uss.switching = false;
18464            }
18465            if (!uss.switching && !uss.initializing) {
18466                mWindowManager.stopFreezingScreen();
18467                unfrozen = true;
18468            }
18469        }
18470        if (unfrozen) {
18471            final int N = mUserSwitchObservers.beginBroadcast();
18472            for (int i=0; i<N; i++) {
18473                try {
18474                    mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
18475                } catch (RemoteException e) {
18476                }
18477            }
18478            mUserSwitchObservers.finishBroadcast();
18479        }
18480    }
18481
18482    void scheduleStartProfilesLocked() {
18483        if (!mHandler.hasMessages(START_PROFILES_MSG)) {
18484            mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG),
18485                    DateUtils.SECOND_IN_MILLIS);
18486        }
18487    }
18488
18489    void startProfilesLocked() {
18490        if (DEBUG_MU) Slog.i(TAG_MU, "startProfilesLocked");
18491        List<UserInfo> profiles = getUserManagerLocked().getProfiles(
18492                mCurrentUserId, false /* enabledOnly */);
18493        List<UserInfo> toStart = new ArrayList<UserInfo>(profiles.size());
18494        for (UserInfo user : profiles) {
18495            if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
18496                    && user.id != mCurrentUserId) {
18497                toStart.add(user);
18498            }
18499        }
18500        final int n = toStart.size();
18501        int i = 0;
18502        for (; i < n && i < (MAX_RUNNING_USERS - 1); ++i) {
18503            startUserInBackground(toStart.get(i).id);
18504        }
18505        if (i < n) {
18506            Slog.w(TAG_MU, "More profiles than MAX_RUNNING_USERS");
18507        }
18508    }
18509
18510    void finishUserBoot(UserStartedState uss) {
18511        synchronized (this) {
18512            if (uss.mState == UserStartedState.STATE_BOOTING
18513                    && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
18514                uss.mState = UserStartedState.STATE_RUNNING;
18515                final int userId = uss.mHandle.getIdentifier();
18516                Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
18517                intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18518                intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
18519                broadcastIntentLocked(null, null, intent,
18520                        null, null, 0, null, null,
18521                        android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
18522                        true, false, MY_PID, Process.SYSTEM_UID, userId);
18523            }
18524        }
18525    }
18526
18527    void finishUserSwitch(UserStartedState uss) {
18528        synchronized (this) {
18529            finishUserBoot(uss);
18530
18531            startProfilesLocked();
18532
18533            int num = mUserLru.size();
18534            int i = 0;
18535            while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
18536                Integer oldUserId = mUserLru.get(i);
18537                UserStartedState oldUss = mStartedUsers.get(oldUserId);
18538                if (oldUss == null) {
18539                    // Shouldn't happen, but be sane if it does.
18540                    mUserLru.remove(i);
18541                    num--;
18542                    continue;
18543                }
18544                if (oldUss.mState == UserStartedState.STATE_STOPPING
18545                        || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
18546                    // This user is already stopping, doesn't count.
18547                    num--;
18548                    i++;
18549                    continue;
18550                }
18551                if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
18552                    // Owner and current can't be stopped, but count as running.
18553                    i++;
18554                    continue;
18555                }
18556                // This is a user to be stopped.
18557                stopUserLocked(oldUserId, null);
18558                num--;
18559                i++;
18560            }
18561        }
18562    }
18563
18564    @Override
18565    public int stopUser(final int userId, final IStopUserCallback callback) {
18566        if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
18567                != PackageManager.PERMISSION_GRANTED) {
18568            String msg = "Permission Denial: switchUser() from pid="
18569                    + Binder.getCallingPid()
18570                    + ", uid=" + Binder.getCallingUid()
18571                    + " requires " + INTERACT_ACROSS_USERS_FULL;
18572            Slog.w(TAG, msg);
18573            throw new SecurityException(msg);
18574        }
18575        if (userId <= 0) {
18576            throw new IllegalArgumentException("Can't stop primary user " + userId);
18577        }
18578        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
18579        synchronized (this) {
18580            return stopUserLocked(userId, callback);
18581        }
18582    }
18583
18584    private int stopUserLocked(final int userId, final IStopUserCallback callback) {
18585        if (DEBUG_MU) Slog.i(TAG_MU, "stopUserLocked userId=" + userId);
18586        if (mCurrentUserId == userId && mTargetUserId == UserHandle.USER_NULL) {
18587            return ActivityManager.USER_OP_IS_CURRENT;
18588        }
18589
18590        final UserStartedState uss = mStartedUsers.get(userId);
18591        if (uss == null) {
18592            // User is not started, nothing to do...  but we do need to
18593            // callback if requested.
18594            if (callback != null) {
18595                mHandler.post(new Runnable() {
18596                    @Override
18597                    public void run() {
18598                        try {
18599                            callback.userStopped(userId);
18600                        } catch (RemoteException e) {
18601                        }
18602                    }
18603                });
18604            }
18605            return ActivityManager.USER_OP_SUCCESS;
18606        }
18607
18608        if (callback != null) {
18609            uss.mStopCallbacks.add(callback);
18610        }
18611
18612        if (uss.mState != UserStartedState.STATE_STOPPING
18613                && uss.mState != UserStartedState.STATE_SHUTDOWN) {
18614            uss.mState = UserStartedState.STATE_STOPPING;
18615            updateStartedUserArrayLocked();
18616
18617            long ident = Binder.clearCallingIdentity();
18618            try {
18619                // We are going to broadcast ACTION_USER_STOPPING and then
18620                // once that is done send a final ACTION_SHUTDOWN and then
18621                // stop the user.
18622                final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
18623                stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
18624                stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18625                stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
18626                final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
18627                // This is the result receiver for the final shutdown broadcast.
18628                final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
18629                    @Override
18630                    public void performReceive(Intent intent, int resultCode, String data,
18631                            Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
18632                        finishUserStop(uss);
18633                    }
18634                };
18635                // This is the result receiver for the initial stopping broadcast.
18636                final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
18637                    @Override
18638                    public void performReceive(Intent intent, int resultCode, String data,
18639                            Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
18640                        // On to the next.
18641                        synchronized (ActivityManagerService.this) {
18642                            if (uss.mState != UserStartedState.STATE_STOPPING) {
18643                                // Whoops, we are being started back up.  Abort, abort!
18644                                return;
18645                            }
18646                            uss.mState = UserStartedState.STATE_SHUTDOWN;
18647                        }
18648                        mBatteryStatsService.noteEvent(
18649                                BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
18650                                Integer.toString(userId), userId);
18651                        mSystemServiceManager.stopUser(userId);
18652                        broadcastIntentLocked(null, null, shutdownIntent,
18653                                null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
18654                                true, false, MY_PID, Process.SYSTEM_UID, userId);
18655                    }
18656                };
18657                // Kick things off.
18658                broadcastIntentLocked(null, null, stoppingIntent,
18659                        null, stoppingReceiver, 0, null, null,
18660                        INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
18661                        true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
18662            } finally {
18663                Binder.restoreCallingIdentity(ident);
18664            }
18665        }
18666
18667        return ActivityManager.USER_OP_SUCCESS;
18668    }
18669
18670    void finishUserStop(UserStartedState uss) {
18671        final int userId = uss.mHandle.getIdentifier();
18672        boolean stopped;
18673        ArrayList<IStopUserCallback> callbacks;
18674        synchronized (this) {
18675            callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
18676            if (mStartedUsers.get(userId) != uss) {
18677                stopped = false;
18678            } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
18679                stopped = false;
18680            } else {
18681                stopped = true;
18682                // User can no longer run.
18683                mStartedUsers.remove(userId);
18684                mUserLru.remove(Integer.valueOf(userId));
18685                updateStartedUserArrayLocked();
18686
18687                // Clean up all state and processes associated with the user.
18688                // Kill all the processes for the user.
18689                forceStopUserLocked(userId, "finish user");
18690            }
18691
18692            // Explicitly remove the old information in mRecentTasks.
18693            removeRecentTasksForUserLocked(userId);
18694        }
18695
18696        for (int i=0; i<callbacks.size(); i++) {
18697            try {
18698                if (stopped) callbacks.get(i).userStopped(userId);
18699                else callbacks.get(i).userStopAborted(userId);
18700            } catch (RemoteException e) {
18701            }
18702        }
18703
18704        if (stopped) {
18705            mSystemServiceManager.cleanupUser(userId);
18706            synchronized (this) {
18707                mStackSupervisor.removeUserLocked(userId);
18708            }
18709        }
18710    }
18711
18712    @Override
18713    public UserInfo getCurrentUser() {
18714        if ((checkCallingPermission(INTERACT_ACROSS_USERS)
18715                != PackageManager.PERMISSION_GRANTED) && (
18716                checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
18717                != PackageManager.PERMISSION_GRANTED)) {
18718            String msg = "Permission Denial: getCurrentUser() from pid="
18719                    + Binder.getCallingPid()
18720                    + ", uid=" + Binder.getCallingUid()
18721                    + " requires " + INTERACT_ACROSS_USERS;
18722            Slog.w(TAG, msg);
18723            throw new SecurityException(msg);
18724        }
18725        synchronized (this) {
18726            int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
18727            return getUserManagerLocked().getUserInfo(userId);
18728        }
18729    }
18730
18731    int getCurrentUserIdLocked() {
18732        return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
18733    }
18734
18735    @Override
18736    public boolean isUserRunning(int userId, boolean orStopped) {
18737        if (checkCallingPermission(INTERACT_ACROSS_USERS)
18738                != PackageManager.PERMISSION_GRANTED) {
18739            String msg = "Permission Denial: isUserRunning() from pid="
18740                    + Binder.getCallingPid()
18741                    + ", uid=" + Binder.getCallingUid()
18742                    + " requires " + INTERACT_ACROSS_USERS;
18743            Slog.w(TAG, msg);
18744            throw new SecurityException(msg);
18745        }
18746        synchronized (this) {
18747            return isUserRunningLocked(userId, orStopped);
18748        }
18749    }
18750
18751    boolean isUserRunningLocked(int userId, boolean orStopped) {
18752        UserStartedState state = mStartedUsers.get(userId);
18753        if (state == null) {
18754            return false;
18755        }
18756        if (orStopped) {
18757            return true;
18758        }
18759        return state.mState != UserStartedState.STATE_STOPPING
18760                && state.mState != UserStartedState.STATE_SHUTDOWN;
18761    }
18762
18763    @Override
18764    public int[] getRunningUserIds() {
18765        if (checkCallingPermission(INTERACT_ACROSS_USERS)
18766                != PackageManager.PERMISSION_GRANTED) {
18767            String msg = "Permission Denial: isUserRunning() from pid="
18768                    + Binder.getCallingPid()
18769                    + ", uid=" + Binder.getCallingUid()
18770                    + " requires " + INTERACT_ACROSS_USERS;
18771            Slog.w(TAG, msg);
18772            throw new SecurityException(msg);
18773        }
18774        synchronized (this) {
18775            return mStartedUserArray;
18776        }
18777    }
18778
18779    private void updateStartedUserArrayLocked() {
18780        int num = 0;
18781        for (int i=0; i<mStartedUsers.size();  i++) {
18782            UserStartedState uss = mStartedUsers.valueAt(i);
18783            // This list does not include stopping users.
18784            if (uss.mState != UserStartedState.STATE_STOPPING
18785                    && uss.mState != UserStartedState.STATE_SHUTDOWN) {
18786                num++;
18787            }
18788        }
18789        mStartedUserArray = new int[num];
18790        num = 0;
18791        for (int i=0; i<mStartedUsers.size();  i++) {
18792            UserStartedState uss = mStartedUsers.valueAt(i);
18793            if (uss.mState != UserStartedState.STATE_STOPPING
18794                    && uss.mState != UserStartedState.STATE_SHUTDOWN) {
18795                mStartedUserArray[num] = mStartedUsers.keyAt(i);
18796                num++;
18797            }
18798        }
18799    }
18800
18801    @Override
18802    public void registerUserSwitchObserver(IUserSwitchObserver observer) {
18803        if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
18804                != PackageManager.PERMISSION_GRANTED) {
18805            String msg = "Permission Denial: registerUserSwitchObserver() from pid="
18806                    + Binder.getCallingPid()
18807                    + ", uid=" + Binder.getCallingUid()
18808                    + " requires " + INTERACT_ACROSS_USERS_FULL;
18809            Slog.w(TAG, msg);
18810            throw new SecurityException(msg);
18811        }
18812
18813        mUserSwitchObservers.register(observer);
18814    }
18815
18816    @Override
18817    public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
18818        mUserSwitchObservers.unregister(observer);
18819    }
18820
18821    private boolean userExists(int userId) {
18822        if (userId == 0) {
18823            return true;
18824        }
18825        UserManagerService ums = getUserManagerLocked();
18826        return ums != null ? (ums.getUserInfo(userId) != null) : false;
18827    }
18828
18829    int[] getUsersLocked() {
18830        UserManagerService ums = getUserManagerLocked();
18831        return ums != null ? ums.getUserIds() : new int[] { 0 };
18832    }
18833
18834    UserManagerService getUserManagerLocked() {
18835        if (mUserManager == null) {
18836            IBinder b = ServiceManager.getService(Context.USER_SERVICE);
18837            mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
18838        }
18839        return mUserManager;
18840    }
18841
18842    private int applyUserId(int uid, int userId) {
18843        return UserHandle.getUid(userId, uid);
18844    }
18845
18846    ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
18847        if (info == null) return null;
18848        ApplicationInfo newInfo = new ApplicationInfo(info);
18849        newInfo.uid = applyUserId(info.uid, userId);
18850        newInfo.dataDir = USER_DATA_DIR + userId + "/"
18851                + info.packageName;
18852        return newInfo;
18853    }
18854
18855    ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
18856        if (aInfo == null
18857                || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
18858            return aInfo;
18859        }
18860
18861        ActivityInfo info = new ActivityInfo(aInfo);
18862        info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
18863        return info;
18864    }
18865
18866    private final class LocalService extends ActivityManagerInternal {
18867        @Override
18868        public void goingToSleep() {
18869            ActivityManagerService.this.goingToSleep();
18870        }
18871
18872        @Override
18873        public void wakingUp() {
18874            ActivityManagerService.this.wakingUp();
18875        }
18876
18877        @Override
18878        public int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
18879                String processName, String abiOverride, int uid, Runnable crashHandler) {
18880            return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
18881                    processName, abiOverride, uid, crashHandler);
18882        }
18883    }
18884
18885    /**
18886     * An implementation of IAppTask, that allows an app to manage its own tasks via
18887     * {@link android.app.ActivityManager.AppTask}.  We keep track of the callingUid to ensure that
18888     * only the process that calls getAppTasks() can call the AppTask methods.
18889     */
18890    class AppTaskImpl extends IAppTask.Stub {
18891        private int mTaskId;
18892        private int mCallingUid;
18893
18894        public AppTaskImpl(int taskId, int callingUid) {
18895            mTaskId = taskId;
18896            mCallingUid = callingUid;
18897        }
18898
18899        private void checkCaller() {
18900            if (mCallingUid != Binder.getCallingUid()) {
18901                throw new SecurityException("Caller " + mCallingUid
18902                        + " does not match caller of getAppTasks(): " + Binder.getCallingUid());
18903            }
18904        }
18905
18906        @Override
18907        public void finishAndRemoveTask() {
18908            checkCaller();
18909
18910            synchronized (ActivityManagerService.this) {
18911                long origId = Binder.clearCallingIdentity();
18912                try {
18913                    TaskRecord tr = recentTaskForIdLocked(mTaskId);
18914                    if (tr == null) {
18915                        throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
18916                    }
18917                    // Only kill the process if we are not a new document
18918                    int flags = tr.getBaseIntent().getFlags();
18919                    boolean isDocument = (flags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) ==
18920                            Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
18921                    removeTaskByIdLocked(mTaskId,
18922                            !isDocument ? ActivityManager.REMOVE_TASK_KILL_PROCESS : 0);
18923                } finally {
18924                    Binder.restoreCallingIdentity(origId);
18925                }
18926            }
18927        }
18928
18929        @Override
18930        public ActivityManager.RecentTaskInfo getTaskInfo() {
18931            checkCaller();
18932
18933            synchronized (ActivityManagerService.this) {
18934                long origId = Binder.clearCallingIdentity();
18935                try {
18936                    TaskRecord tr = recentTaskForIdLocked(mTaskId);
18937                    if (tr == null) {
18938                        throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
18939                    }
18940                    return createRecentTaskInfoFromTaskRecord(tr);
18941                } finally {
18942                    Binder.restoreCallingIdentity(origId);
18943                }
18944            }
18945        }
18946
18947        @Override
18948        public void moveToFront() {
18949            checkCaller();
18950
18951            final TaskRecord tr;
18952            synchronized (ActivityManagerService.this) {
18953                tr = recentTaskForIdLocked(mTaskId);
18954                if (tr == null) {
18955                    throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
18956                }
18957                if (tr.getRootActivity() != null) {
18958                    moveTaskToFrontLocked(tr.taskId, 0, null);
18959                }
18960            }
18961
18962            startActivityFromRecentsInner(tr.taskId, null);
18963        }
18964
18965        @Override
18966        public int startActivity(IBinder whoThread, String callingPackage,
18967                Intent intent, String resolvedType, Bundle options) {
18968            checkCaller();
18969
18970            int callingUser = UserHandle.getCallingUserId();
18971            TaskRecord tr;
18972            IApplicationThread appThread;
18973            synchronized (ActivityManagerService.this) {
18974                tr = recentTaskForIdLocked(mTaskId);
18975                if (tr == null) {
18976                    throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
18977                }
18978                appThread = ApplicationThreadNative.asInterface(whoThread);
18979                if (appThread == null) {
18980                    throw new IllegalArgumentException("Bad app thread " + appThread);
18981                }
18982            }
18983            return mStackSupervisor.startActivityMayWait(appThread, -1, callingPackage, intent,
18984                    resolvedType, null, null, null, null, 0, 0, null, null,
18985                    null, options, callingUser, null, tr);
18986        }
18987
18988        @Override
18989        public void setExcludeFromRecents(boolean exclude) {
18990            checkCaller();
18991
18992            synchronized (ActivityManagerService.this) {
18993                long origId = Binder.clearCallingIdentity();
18994                try {
18995                    TaskRecord tr = recentTaskForIdLocked(mTaskId);
18996                    if (tr == null) {
18997                        throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
18998                    }
18999                    Intent intent = tr.getBaseIntent();
19000                    if (exclude) {
19001                        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
19002                    } else {
19003                        intent.setFlags(intent.getFlags()
19004                                & ~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
19005                    }
19006                } finally {
19007                    Binder.restoreCallingIdentity(origId);
19008                }
19009            }
19010        }
19011    }
19012}
19013