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 com.android.server.am.ActivityManagerDebugConfig.*;
31import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID;
32import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
33import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
34import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
35import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
36import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
37import static org.xmlpull.v1.XmlPullParser.START_TAG;
38
39import android.Manifest;
40import android.app.AppOpsManager;
41import android.app.ApplicationThreadNative;
42import android.app.BroadcastOptions;
43import android.app.IActivityContainer;
44import android.app.IActivityContainerCallback;
45import android.app.IAppTask;
46import android.app.ITaskStackListener;
47import android.app.ProfilerInfo;
48import android.app.assist.AssistContent;
49import android.app.assist.AssistStructure;
50import android.app.usage.UsageEvents;
51import android.app.usage.UsageStatsManagerInternal;
52import android.appwidget.AppWidgetManager;
53import android.content.pm.PermissionInfo;
54import android.content.res.Resources;
55import android.graphics.Bitmap;
56import android.graphics.Point;
57import android.graphics.Rect;
58import android.os.BatteryStats;
59import android.os.PersistableBundle;
60import android.os.PowerManager;
61import android.os.Trace;
62import android.os.TransactionTooLargeException;
63import android.os.WorkSource;
64import android.os.storage.IMountService;
65import android.os.storage.MountServiceInternal;
66import android.os.storage.StorageManager;
67import android.service.voice.IVoiceInteractionSession;
68import android.service.voice.VoiceInteractionSession;
69import android.util.ArrayMap;
70import android.util.ArraySet;
71import android.util.DebugUtils;
72import android.util.SparseIntArray;
73import android.view.Display;
74
75import com.android.internal.R;
76import com.android.internal.annotations.GuardedBy;
77import com.android.internal.app.AssistUtils;
78import com.android.internal.app.DumpHeapActivity;
79import com.android.internal.app.IAppOpsService;
80import com.android.internal.app.IVoiceInteractor;
81import com.android.internal.app.ProcessMap;
82import com.android.internal.app.ProcessStats;
83import com.android.internal.os.BackgroundThread;
84import com.android.internal.os.BatteryStatsImpl;
85import com.android.internal.os.IResultReceiver;
86import com.android.internal.os.ProcessCpuTracker;
87import com.android.internal.os.TransferPipe;
88import com.android.internal.os.Zygote;
89import com.android.internal.util.ArrayUtils;
90import com.android.internal.util.FastPrintWriter;
91import com.android.internal.util.FastXmlSerializer;
92import com.android.internal.util.MemInfoReader;
93import com.android.internal.util.Preconditions;
94import com.android.server.AppOpsService;
95import com.android.server.AttributeCache;
96import com.android.server.DeviceIdleController;
97import com.android.server.IntentResolver;
98import com.android.server.LocalServices;
99import com.android.server.ServiceThread;
100import com.android.server.SystemService;
101import com.android.server.SystemServiceManager;
102import com.android.server.Watchdog;
103import com.android.server.am.ActivityStack.ActivityState;
104import com.android.server.firewall.IntentFirewall;
105import com.android.server.pm.Installer;
106import com.android.server.pm.UserManagerService;
107import com.android.server.statusbar.StatusBarManagerInternal;
108import com.android.server.wm.AppTransition;
109import com.android.server.wm.WindowManagerService;
110import com.google.android.collect.Lists;
111import com.google.android.collect.Maps;
112
113import libcore.io.IoUtils;
114import libcore.util.EmptyArray;
115
116import org.xmlpull.v1.XmlPullParser;
117import org.xmlpull.v1.XmlPullParserException;
118import org.xmlpull.v1.XmlSerializer;
119
120import android.app.Activity;
121import android.app.ActivityManager;
122import android.app.ActivityManager.RunningTaskInfo;
123import android.app.ActivityManager.StackInfo;
124import android.app.ActivityManagerInternal;
125import android.app.ActivityManagerInternal.SleepToken;
126import android.app.ActivityManagerNative;
127import android.app.ActivityOptions;
128import android.app.ActivityThread;
129import android.app.AlertDialog;
130import android.app.AppGlobals;
131import android.app.ApplicationErrorReport;
132import android.app.Dialog;
133import android.app.IActivityController;
134import android.app.IApplicationThread;
135import android.app.IInstrumentationWatcher;
136import android.app.INotificationManager;
137import android.app.IProcessObserver;
138import android.app.IServiceConnection;
139import android.app.IStopUserCallback;
140import android.app.IUidObserver;
141import android.app.IUiAutomationConnection;
142import android.app.IUserSwitchObserver;
143import android.app.Instrumentation;
144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
147import android.app.backup.IBackupManager;
148import android.app.admin.DevicePolicyManager;
149import android.content.ActivityNotFoundException;
150import android.content.BroadcastReceiver;
151import android.content.ClipData;
152import android.content.ComponentCallbacks2;
153import android.content.ComponentName;
154import android.content.ContentProvider;
155import android.content.ContentResolver;
156import android.content.Context;
157import android.content.DialogInterface;
158import android.content.IContentProvider;
159import android.content.IIntentReceiver;
160import android.content.IIntentSender;
161import android.content.Intent;
162import android.content.IntentFilter;
163import android.content.IntentSender;
164import android.content.pm.ActivityInfo;
165import android.content.pm.ApplicationInfo;
166import android.content.pm.ConfigurationInfo;
167import android.content.pm.IPackageDataObserver;
168import android.content.pm.IPackageManager;
169import android.content.pm.InstrumentationInfo;
170import android.content.pm.PackageInfo;
171import android.content.pm.PackageManager;
172import android.content.pm.ParceledListSlice;
173import android.content.pm.UserInfo;
174import android.content.pm.PackageManager.NameNotFoundException;
175import android.content.pm.PathPermission;
176import android.content.pm.ProviderInfo;
177import android.content.pm.ResolveInfo;
178import android.content.pm.ServiceInfo;
179import android.content.res.CompatibilityInfo;
180import android.content.res.Configuration;
181import android.net.Proxy;
182import android.net.ProxyInfo;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.DropBoxManager;
189import android.os.Environment;
190import android.os.FactoryTest;
191import android.os.FileObserver;
192import android.os.FileUtils;
193import android.os.Handler;
194import android.os.IBinder;
195import android.os.IPermissionController;
196import android.os.IProcessInfoService;
197import android.os.IRemoteCallback;
198import android.os.IUserManager;
199import android.os.Looper;
200import android.os.Message;
201import android.os.Parcel;
202import android.os.ParcelFileDescriptor;
203import android.os.PowerManagerInternal;
204import android.os.Process;
205import android.os.RemoteCallbackList;
206import android.os.RemoteException;
207import android.os.SELinux;
208import android.os.ServiceManager;
209import android.os.StrictMode;
210import android.os.SystemClock;
211import android.os.SystemProperties;
212import android.os.UpdateLock;
213import android.os.UserHandle;
214import android.os.UserManager;
215import android.provider.Settings;
216import android.text.format.DateUtils;
217import android.text.format.Time;
218import android.util.AtomicFile;
219import android.util.EventLog;
220import android.util.Log;
221import android.util.Pair;
222import android.util.PrintWriterPrinter;
223import android.util.Slog;
224import android.util.SparseArray;
225import android.util.TimeUtils;
226import android.util.Xml;
227import android.view.Gravity;
228import android.view.LayoutInflater;
229import android.view.View;
230import android.view.WindowManager;
231
232import dalvik.system.VMRuntime;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.DataInputStream;
237import java.io.DataOutputStream;
238import java.io.File;
239import java.io.FileDescriptor;
240import java.io.FileInputStream;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.IOException;
244import java.io.InputStreamReader;
245import java.io.PrintWriter;
246import java.io.StringWriter;
247import java.lang.ref.WeakReference;
248import java.nio.charset.StandardCharsets;
249import java.util.ArrayList;
250import java.util.Arrays;
251import java.util.Collections;
252import java.util.Comparator;
253import java.util.HashMap;
254import java.util.HashSet;
255import java.util.Iterator;
256import java.util.List;
257import java.util.Locale;
258import java.util.Map;
259import java.util.Set;
260import java.util.concurrent.atomic.AtomicBoolean;
261import java.util.concurrent.atomic.AtomicLong;
262
263public final class ActivityManagerService extends ActivityManagerNative
264        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
265
266    // File that stores last updated system version and called preboot receivers
267    static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat";
268
269    private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
270    private static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
271    private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
272    private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
273    private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
274    private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
275    private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
276    private static final String TAG_LOCKSCREEN = TAG + POSTFIX_LOCKSCREEN;
277    private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
278    private static final String TAG_LRU = TAG + POSTFIX_LRU;
279    private static final String TAG_MU = TAG + POSTFIX_MU;
280    private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
281    private static final String TAG_POWER = TAG + POSTFIX_POWER;
282    private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
283    private static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
284    private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER;
285    private static final String TAG_PSS = TAG + POSTFIX_PSS;
286    private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
287    private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
288    private static final String TAG_STACK = TAG + POSTFIX_STACK;
289    private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
290    private static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
291    private static final String TAG_URI_PERMISSION = TAG + POSTFIX_URI_PERMISSION;
292    private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
293    private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;
294
295    /** Control over CPU and battery monitoring */
296    // write battery stats every 30 minutes.
297    static final long BATTERY_STATS_TIME = 30 * 60 * 1000;
298    static final boolean MONITOR_CPU_USAGE = true;
299    // don't sample cpu less than every 5 seconds.
300    static final long MONITOR_CPU_MIN_TIME = 5 * 1000;
301    // wait possibly forever for next cpu sample.
302    static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;
303    static final boolean MONITOR_THREAD_CPU_USAGE = false;
304
305    // The flags that are set for all calls we make to the package manager.
306    static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
307
308    private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
309
310    static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
311
312    // Amount of time after a call to stopAppSwitches() during which we will
313    // prevent further untrusted switches from happening.
314    static final long APP_SWITCH_DELAY_TIME = 5*1000;
315
316    // How long we wait for a launched process to attach to the activity manager
317    // before we decide it's never going to come up for real.
318    static final int PROC_START_TIMEOUT = 10*1000;
319    // How long we wait for an attached process to publish its content providers
320    // before we decide it must be hung.
321    static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000;
322
323    // How long we wait for a launched process to attach to the activity manager
324    // before we decide it's never going to come up for real, when the process was
325    // started with a wrapper for instrumentation (such as Valgrind) because it
326    // could take much longer than usual.
327    static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
328
329    // How long to wait after going idle before forcing apps to GC.
330    static final int GC_TIMEOUT = 5*1000;
331
332    // The minimum amount of time between successive GC requests for a process.
333    static final int GC_MIN_INTERVAL = 60*1000;
334
335    // The minimum amount of time between successive PSS requests for a process.
336    static final int FULL_PSS_MIN_INTERVAL = 10*60*1000;
337
338    // The minimum amount of time between successive PSS requests for a process
339    // when the request is due to the memory state being lowered.
340    static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000;
341
342    // The rate at which we check for apps using excessive power -- 15 mins.
343    static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
344
345    // The minimum sample duration we will allow before deciding we have
346    // enough data on wake locks to start killing things.
347    static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
348
349    // The minimum sample duration we will allow before deciding we have
350    // enough data on CPU usage to start killing things.
351    static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
352
353    // How long we allow a receiver to run before giving up on it.
354    static final int BROADCAST_FG_TIMEOUT = 10*1000;
355    static final int BROADCAST_BG_TIMEOUT = 60*1000;
356
357    // How long we wait until we timeout on key dispatching.
358    static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
359
360    // How long we wait until we timeout on key dispatching during instrumentation.
361    static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
362
363    // Amount of time we wait for observers to handle a user switch before
364    // giving up on them and unfreezing the screen.
365    static final int USER_SWITCH_TIMEOUT = 2*1000;
366
367    // This is the amount of time an app needs to be running a foreground service before
368    // we will consider it to be doing interaction for usage stats.
369    static final int SERVICE_USAGE_INTERACTION_TIME = 30*60*1000;
370
371    // Maximum amount of time we will allow to elapse before re-reporting usage stats
372    // interaction with foreground processes.
373    static final long USAGE_STATS_INTERACTION_INTERVAL = 24*60*60*1000L;
374
375    // Maximum number of users we allow to be running at a time.
376    static final int MAX_RUNNING_USERS = 3;
377
378    // How long to wait in getAssistContextExtras for the activity and foreground services
379    // to respond with the result.
380    static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
381
382    // How long top wait when going through the modern assist (which doesn't need to block
383    // on getting this result before starting to launch its UI).
384    static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
385
386    // Maximum number of persisted Uri grants a package is allowed
387    static final int MAX_PERSISTED_URI_GRANTS = 128;
388
389    static final int MY_PID = Process.myPid();
390
391    static final String[] EMPTY_STRING_ARRAY = new String[0];
392
393    // How many bytes to write into the dropbox log before truncating
394    static final int DROPBOX_MAX_SIZE = 256 * 1024;
395
396    // Access modes for handleIncomingUser.
397    static final int ALLOW_NON_FULL = 0;
398    static final int ALLOW_NON_FULL_IN_PROFILE = 1;
399    static final int ALLOW_FULL_ONLY = 2;
400
401    static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000;
402
403    // Delay in notifying task stack change listeners (in millis)
404    static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 1000;
405
406    // Necessary ApplicationInfo flags to mark an app as persistent
407    private static final int PERSISTENT_MASK =
408            ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
409
410
411    // Delay to disable app launch boost
412    static final int APP_BOOST_MESSAGE_DELAY = 3000;
413    // Lower delay than APP_BOOST_MESSAGE_DELAY to disable the boost
414    static final int APP_BOOST_TIMEOUT = 2500;
415
416    private static native int nativeMigrateToBoost();
417    private static native int nativeMigrateFromBoost();
418    private boolean mIsBoosted = false;
419    private long mBoostStartTime = 0;
420
421    /** All system services */
422    SystemServiceManager mSystemServiceManager;
423
424    private Installer mInstaller;
425
426    /** Run all ActivityStacks through this */
427    ActivityStackSupervisor mStackSupervisor;
428
429    /** Task stack change listeners. */
430    private RemoteCallbackList<ITaskStackListener> mTaskStackListeners =
431            new RemoteCallbackList<ITaskStackListener>();
432
433    public IntentFirewall mIntentFirewall;
434
435    // Whether we should show our dialogs (ANR, crash, etc) or just perform their
436    // default actuion automatically.  Important for devices without direct input
437    // devices.
438    private boolean mShowDialogs = true;
439
440    BroadcastQueue mFgBroadcastQueue;
441    BroadcastQueue mBgBroadcastQueue;
442    // Convenient for easy iteration over the queues. Foreground is first
443    // so that dispatch of foreground broadcasts gets precedence.
444    final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
445
446    BroadcastQueue broadcastQueueForIntent(Intent intent) {
447        final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
448        if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
449                "Broadcast intent " + intent + " on "
450                + (isFg ? "foreground" : "background") + " queue");
451        return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
452    }
453
454    /**
455     * Activity we have told the window manager to have key focus.
456     */
457    ActivityRecord mFocusedActivity = null;
458
459    /**
460     * User id of the last activity mFocusedActivity was set to.
461     */
462    private int mLastFocusedUserId;
463
464    /**
465     * If non-null, we are tracking the time the user spends in the currently focused app.
466     */
467    private AppTimeTracker mCurAppTimeTracker;
468
469    /**
470     * List of intents that were used to start the most recent tasks.
471     */
472    private final RecentTasks mRecentTasks;
473
474    /**
475     * For addAppTask: cached of the last activity component that was added.
476     */
477    ComponentName mLastAddedTaskComponent;
478
479    /**
480     * For addAppTask: cached of the last activity uid that was added.
481     */
482    int mLastAddedTaskUid;
483
484    /**
485     * For addAppTask: cached of the last ActivityInfo that was added.
486     */
487    ActivityInfo mLastAddedTaskActivity;
488
489    /**
490     * List of packages whitelisted by DevicePolicyManager for locktask. Indexed by userId.
491     */
492    SparseArray<String[]> mLockTaskPackages = new SparseArray<>();
493
494    /**
495     * The package name of the DeviceOwner. This package is not permitted to have its data cleared.
496     */
497    String mDeviceOwnerName;
498
499    public class PendingAssistExtras extends Binder implements Runnable {
500        public final ActivityRecord activity;
501        public final Bundle extras;
502        public final Intent intent;
503        public final String hint;
504        public final IResultReceiver receiver;
505        public final int userHandle;
506        public boolean haveResult = false;
507        public Bundle result = null;
508        public AssistStructure structure = null;
509        public AssistContent content = null;
510        public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
511                String _hint, IResultReceiver _receiver, int _userHandle) {
512            activity = _activity;
513            extras = _extras;
514            intent = _intent;
515            hint = _hint;
516            receiver = _receiver;
517            userHandle = _userHandle;
518        }
519        @Override
520        public void run() {
521            Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
522            synchronized (this) {
523                haveResult = true;
524                notifyAll();
525            }
526            pendingAssistExtrasTimedOut(this);
527        }
528    }
529
530    final ArrayList<PendingAssistExtras> mPendingAssistExtras
531            = new ArrayList<PendingAssistExtras>();
532
533    /**
534     * Process management.
535     */
536    final ProcessList mProcessList = new ProcessList();
537
538    /**
539     * All of the applications we currently have running organized by name.
540     * The keys are strings of the application package name (as
541     * returned by the package manager), and the keys are ApplicationRecord
542     * objects.
543     */
544    final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
545
546    /**
547     * Tracking long-term execution of processes to look for abuse and other
548     * bad app behavior.
549     */
550    final ProcessStatsService mProcessStats;
551
552    /**
553     * The currently running isolated processes.
554     */
555    final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
556
557    /**
558     * Counter for assigning isolated process uids, to avoid frequently reusing the
559     * same ones.
560     */
561    int mNextIsolatedProcessUid = 0;
562
563    /**
564     * The currently running heavy-weight process, if any.
565     */
566    ProcessRecord mHeavyWeightProcess = null;
567
568    /**
569     * The last time that various processes have crashed.
570     */
571    final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
572
573    /**
574     * Information about a process that is currently marked as bad.
575     */
576    static final class BadProcessInfo {
577        BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
578            this.time = time;
579            this.shortMsg = shortMsg;
580            this.longMsg = longMsg;
581            this.stack = stack;
582        }
583
584        final long time;
585        final String shortMsg;
586        final String longMsg;
587        final String stack;
588    }
589
590    /**
591     * Set of applications that we consider to be bad, and will reject
592     * incoming broadcasts from (which the user has no control over).
593     * Processes are added to this set when they have crashed twice within
594     * a minimum amount of time; they are removed from it when they are
595     * later restarted (hopefully due to some user action).  The value is the
596     * time it was added to the list.
597     */
598    final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>();
599
600    /**
601     * All of the processes we currently have running organized by pid.
602     * The keys are the pid running the application.
603     *
604     * <p>NOTE: This object is protected by its own lock, NOT the global
605     * activity manager lock!
606     */
607    final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
608
609    /**
610     * All of the processes that have been forced to be foreground.  The key
611     * is the pid of the caller who requested it (we hold a death
612     * link on it).
613     */
614    abstract class ForegroundToken implements IBinder.DeathRecipient {
615        int pid;
616        IBinder token;
617    }
618    final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>();
619
620    /**
621     * List of records for processes that someone had tried to start before the
622     * system was ready.  We don't start them at that point, but ensure they
623     * are started by the time booting is complete.
624     */
625    final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
626
627    /**
628     * List of persistent applications that are in the process
629     * of being started.
630     */
631    final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
632
633    /**
634     * Processes that are being forcibly torn down.
635     */
636    final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>();
637
638    /**
639     * List of running applications, sorted by recent usage.
640     * The first entry in the list is the least recently used.
641     */
642    final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();
643
644    /**
645     * Where in mLruProcesses that the processes hosting activities start.
646     */
647    int mLruProcessActivityStart = 0;
648
649    /**
650     * Where in mLruProcesses that the processes hosting services start.
651     * This is after (lower index) than mLruProcessesActivityStart.
652     */
653    int mLruProcessServiceStart = 0;
654
655    /**
656     * List of processes that should gc as soon as things are idle.
657     */
658    final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
659
660    /**
661     * Processes we want to collect PSS data from.
662     */
663    final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
664
665    /**
666     * Last time we requested PSS data of all processes.
667     */
668    long mLastFullPssTime = SystemClock.uptimeMillis();
669
670    /**
671     * If set, the next time we collect PSS data we should do a full collection
672     * with data from native processes and the kernel.
673     */
674    boolean mFullPssPending = false;
675
676    /**
677     * This is the process holding what we currently consider to be
678     * the "home" activity.
679     */
680    ProcessRecord mHomeProcess;
681
682    /**
683     * This is the process holding the activity the user last visited that
684     * is in a different process from the one they are currently in.
685     */
686    ProcessRecord mPreviousProcess;
687
688    /**
689     * The time at which the previous process was last visible.
690     */
691    long mPreviousProcessVisibleTime;
692
693    /**
694     * Track all uids that have actively running processes.
695     */
696    final SparseArray<UidRecord> mActiveUids = new SparseArray<>();
697
698    /**
699     * Which users have been started, so are allowed to run code.
700     */
701    final SparseArray<UserState> mStartedUsers = new SparseArray<>();
702
703    /**
704     * LRU list of history of current users.  Most recently current is at the end.
705     */
706    final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
707
708    /**
709     * Constant array of the users that are currently started.
710     */
711    int[] mStartedUserArray = new int[] { 0 };
712
713    /**
714     * Registered observers of the user switching mechanics.
715     */
716    final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
717            = new RemoteCallbackList<IUserSwitchObserver>();
718
719    /**
720     * Currently active user switch.
721     */
722    Object mCurUserSwitchCallback;
723
724    /**
725     * Packages that the user has asked to have run in screen size
726     * compatibility mode instead of filling the screen.
727     */
728    final CompatModePackages mCompatModePackages;
729
730    /**
731     * Set of IntentSenderRecord objects that are currently active.
732     */
733    final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
734            = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
735
736    /**
737     * Fingerprints (hashCode()) of stack traces that we've
738     * already logged DropBox entries for.  Guarded by itself.  If
739     * something (rogue user app) forces this over
740     * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
741     */
742    private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
743    private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
744
745    /**
746     * Strict Mode background batched logging state.
747     *
748     * The string buffer is guarded by itself, and its lock is also
749     * used to determine if another batched write is already
750     * in-flight.
751     */
752    private final StringBuilder mStrictModeBuffer = new StringBuilder();
753
754    /**
755     * Keeps track of all IIntentReceivers that have been registered for broadcasts.
756     * Hash keys are the receiver IBinder, hash value is a ReceiverList.
757     */
758    final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
759
760    /**
761     * Resolver for broadcast intents to registered receivers.
762     * Holds BroadcastFilter (subclass of IntentFilter).
763     */
764    final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
765            = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
766        @Override
767        protected boolean allowFilterResult(
768                BroadcastFilter filter, List<BroadcastFilter> dest) {
769            IBinder target = filter.receiverList.receiver.asBinder();
770            for (int i = dest.size() - 1; i >= 0; i--) {
771                if (dest.get(i).receiverList.receiver.asBinder() == target) {
772                    return false;
773                }
774            }
775            return true;
776        }
777
778        @Override
779        protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
780            if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
781                    || userId == filter.owningUserId) {
782                return super.newResult(filter, match, userId);
783            }
784            return null;
785        }
786
787        @Override
788        protected BroadcastFilter[] newArray(int size) {
789            return new BroadcastFilter[size];
790        }
791
792        @Override
793        protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
794            return packageName.equals(filter.packageName);
795        }
796    };
797
798    /**
799     * State of all active sticky broadcasts per user.  Keys are the action of the
800     * sticky Intent, values are an ArrayList of all broadcasted intents with
801     * that action (which should usually be one).  The SparseArray is keyed
802     * by the user ID the sticky is for, and can include UserHandle.USER_ALL
803     * for stickies that are sent to all users.
804     */
805    final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
806            new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
807
808    final ActiveServices mServices;
809
810    final static class Association {
811        final int mSourceUid;
812        final String mSourceProcess;
813        final int mTargetUid;
814        final ComponentName mTargetComponent;
815        final String mTargetProcess;
816
817        int mCount;
818        long mTime;
819
820        int mNesting;
821        long mStartTime;
822
823        Association(int sourceUid, String sourceProcess, int targetUid,
824                ComponentName targetComponent, String targetProcess) {
825            mSourceUid = sourceUid;
826            mSourceProcess = sourceProcess;
827            mTargetUid = targetUid;
828            mTargetComponent = targetComponent;
829            mTargetProcess = targetProcess;
830        }
831    }
832
833    /**
834     * When service association tracking is enabled, this is all of the associations we
835     * have seen.  Mapping is target uid -> target component -> source uid -> source process name
836     * -> association data.
837     */
838    final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
839            mAssociations = new SparseArray<>();
840    boolean mTrackingAssociations;
841
842    /**
843     * Backup/restore process management
844     */
845    String mBackupAppName = null;
846    BackupRecord mBackupTarget = null;
847
848    final ProviderMap mProviderMap;
849
850    /**
851     * List of content providers who have clients waiting for them.  The
852     * application is currently being launched and the provider will be
853     * removed from this list once it is published.
854     */
855    final ArrayList<ContentProviderRecord> mLaunchingProviders
856            = new ArrayList<ContentProviderRecord>();
857
858    /**
859     * File storing persisted {@link #mGrantedUriPermissions}.
860     */
861    private final AtomicFile mGrantFile;
862
863    /** XML constants used in {@link #mGrantFile} */
864    private static final String TAG_URI_GRANTS = "uri-grants";
865    private static final String TAG_URI_GRANT = "uri-grant";
866    private static final String ATTR_USER_HANDLE = "userHandle";
867    private static final String ATTR_SOURCE_USER_ID = "sourceUserId";
868    private static final String ATTR_TARGET_USER_ID = "targetUserId";
869    private static final String ATTR_SOURCE_PKG = "sourcePkg";
870    private static final String ATTR_TARGET_PKG = "targetPkg";
871    private static final String ATTR_URI = "uri";
872    private static final String ATTR_MODE_FLAGS = "modeFlags";
873    private static final String ATTR_CREATED_TIME = "createdTime";
874    private static final String ATTR_PREFIX = "prefix";
875
876    /**
877     * Global set of specific {@link Uri} permissions that have been granted.
878     * This optimized lookup structure maps from {@link UriPermission#targetUid}
879     * to {@link UriPermission#uri} to {@link UriPermission}.
880     */
881    @GuardedBy("this")
882    private final SparseArray<ArrayMap<GrantUri, UriPermission>>
883            mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>();
884
885    public static class GrantUri {
886        public final int sourceUserId;
887        public final Uri uri;
888        public boolean prefix;
889
890        public GrantUri(int sourceUserId, Uri uri, boolean prefix) {
891            this.sourceUserId = sourceUserId;
892            this.uri = uri;
893            this.prefix = prefix;
894        }
895
896        @Override
897        public int hashCode() {
898            int hashCode = 1;
899            hashCode = 31 * hashCode + sourceUserId;
900            hashCode = 31 * hashCode + uri.hashCode();
901            hashCode = 31 * hashCode + (prefix ? 1231 : 1237);
902            return hashCode;
903        }
904
905        @Override
906        public boolean equals(Object o) {
907            if (o instanceof GrantUri) {
908                GrantUri other = (GrantUri) o;
909                return uri.equals(other.uri) && (sourceUserId == other.sourceUserId)
910                        && prefix == other.prefix;
911            }
912            return false;
913        }
914
915        @Override
916        public String toString() {
917            String result = Integer.toString(sourceUserId) + " @ " + uri.toString();
918            if (prefix) result += " [prefix]";
919            return result;
920        }
921
922        public String toSafeString() {
923            String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString();
924            if (prefix) result += " [prefix]";
925            return result;
926        }
927
928        public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) {
929            return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle),
930                    ContentProvider.getUriWithoutUserId(uri), false);
931        }
932    }
933
934    CoreSettingsObserver mCoreSettingsObserver;
935
936    /**
937     * Thread-local storage used to carry caller permissions over through
938     * indirect content-provider access.
939     */
940    private class Identity {
941        public final IBinder token;
942        public final int pid;
943        public final int uid;
944
945        Identity(IBinder _token, int _pid, int _uid) {
946            token = _token;
947            pid = _pid;
948            uid = _uid;
949        }
950    }
951
952    private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
953
954    /**
955     * All information we have collected about the runtime performance of
956     * any user id that can impact battery performance.
957     */
958    final BatteryStatsService mBatteryStatsService;
959
960    /**
961     * Information about component usage
962     */
963    UsageStatsManagerInternal mUsageStatsService;
964
965    /**
966     * Access to DeviceIdleController service.
967     */
968    DeviceIdleController.LocalService mLocalDeviceIdleController;
969
970    /**
971     * Information about and control over application operations
972     */
973    final AppOpsService mAppOpsService;
974
975    /**
976     * Save recent tasks information across reboots.
977     */
978    final TaskPersister mTaskPersister;
979
980    /**
981     * Current configuration information.  HistoryRecord objects are given
982     * a reference to this object to indicate which configuration they are
983     * currently running in, so this object must be kept immutable.
984     */
985    Configuration mConfiguration = new Configuration();
986
987    /**
988     * Current sequencing integer of the configuration, for skipping old
989     * configurations.
990     */
991    int mConfigurationSeq = 0;
992
993    /**
994     * Hardware-reported OpenGLES version.
995     */
996    final int GL_ES_VERSION;
997
998    /**
999     * List of initialization arguments to pass to all processes when binding applications to them.
1000     * For example, references to the commonly used services.
1001     */
1002    HashMap<String, IBinder> mAppBindArgs;
1003
1004    /**
1005     * Temporary to avoid allocations.  Protected by main lock.
1006     */
1007    final StringBuilder mStringBuilder = new StringBuilder(256);
1008
1009    /**
1010     * Used to control how we initialize the service.
1011     */
1012    ComponentName mTopComponent;
1013    String mTopAction = Intent.ACTION_MAIN;
1014    String mTopData;
1015    boolean mProcessesReady = false;
1016    boolean mSystemReady = false;
1017    boolean mBooting = false;
1018    boolean mCallFinishBooting = false;
1019    boolean mBootAnimationComplete = false;
1020    boolean mWaitingUpdate = false;
1021    boolean mDidUpdate = false;
1022    boolean mOnBattery = false;
1023    boolean mLaunchWarningShown = false;
1024
1025    Context mContext;
1026
1027    int mFactoryTest;
1028
1029    boolean mCheckedForSetup;
1030
1031    /**
1032     * The time at which we will allow normal application switches again,
1033     * after a call to {@link #stopAppSwitches()}.
1034     */
1035    long mAppSwitchesAllowedTime;
1036
1037    /**
1038     * This is set to true after the first switch after mAppSwitchesAllowedTime
1039     * is set; any switches after that will clear the time.
1040     */
1041    boolean mDidAppSwitch;
1042
1043    /**
1044     * Last time (in realtime) at which we checked for power usage.
1045     */
1046    long mLastPowerCheckRealtime;
1047
1048    /**
1049     * Last time (in uptime) at which we checked for power usage.
1050     */
1051    long mLastPowerCheckUptime;
1052
1053    /**
1054     * Set while we are wanting to sleep, to prevent any
1055     * activities from being started/resumed.
1056     */
1057    private boolean mSleeping = false;
1058
1059    /**
1060     * The process state used for processes that are running the top activities.
1061     * This changes between TOP and TOP_SLEEPING to following mSleeping.
1062     */
1063    int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
1064
1065    /**
1066     * Set while we are running a voice interaction.  This overrides
1067     * sleeping while it is active.
1068     */
1069    private IVoiceInteractionSession mRunningVoice;
1070
1071    /**
1072     * For some direct access we need to power manager.
1073     */
1074    PowerManagerInternal mLocalPowerManager;
1075
1076    /**
1077     * We want to hold a wake lock while running a voice interaction session, since
1078     * this may happen with the screen off and we need to keep the CPU running to
1079     * be able to continue to interact with the user.
1080     */
1081    PowerManager.WakeLock mVoiceWakeLock;
1082
1083    /**
1084     * State of external calls telling us if the device is awake or asleep.
1085     */
1086    private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
1087
1088    /**
1089     * A list of tokens that cause the top activity to be put to sleep.
1090     * They are used by components that may hide and block interaction with underlying
1091     * activities.
1092     */
1093    final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>();
1094
1095    static final int LOCK_SCREEN_HIDDEN = 0;
1096    static final int LOCK_SCREEN_LEAVING = 1;
1097    static final int LOCK_SCREEN_SHOWN = 2;
1098    /**
1099     * State of external call telling us if the lock screen is shown.
1100     */
1101    int mLockScreenShown = LOCK_SCREEN_HIDDEN;
1102
1103    /**
1104     * Set if we are shutting down the system, similar to sleeping.
1105     */
1106    boolean mShuttingDown = false;
1107
1108    /**
1109     * Current sequence id for oom_adj computation traversal.
1110     */
1111    int mAdjSeq = 0;
1112
1113    /**
1114     * Current sequence id for process LRU updating.
1115     */
1116    int mLruSeq = 0;
1117
1118    /**
1119     * Keep track of the non-cached/empty process we last found, to help
1120     * determine how to distribute cached/empty processes next time.
1121     */
1122    int mNumNonCachedProcs = 0;
1123
1124    /**
1125     * Keep track of the number of cached hidden procs, to balance oom adj
1126     * distribution between those and empty procs.
1127     */
1128    int mNumCachedHiddenProcs = 0;
1129
1130    /**
1131     * Keep track of the number of service processes we last found, to
1132     * determine on the next iteration which should be B services.
1133     */
1134    int mNumServiceProcs = 0;
1135    int mNewNumAServiceProcs = 0;
1136    int mNewNumServiceProcs = 0;
1137
1138    /**
1139     * Allow the current computed overall memory level of the system to go down?
1140     * This is set to false when we are killing processes for reasons other than
1141     * memory management, so that the now smaller process list will not be taken as
1142     * an indication that memory is tighter.
1143     */
1144    boolean mAllowLowerMemLevel = false;
1145
1146    /**
1147     * The last computed memory level, for holding when we are in a state that
1148     * processes are going away for other reasons.
1149     */
1150    int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1151
1152    /**
1153     * The last total number of process we have, to determine if changes actually look
1154     * like a shrinking number of process due to lower RAM.
1155     */
1156    int mLastNumProcesses;
1157
1158    /**
1159     * The uptime of the last time we performed idle maintenance.
1160     */
1161    long mLastIdleTime = SystemClock.uptimeMillis();
1162
1163    /**
1164     * Total time spent with RAM that has been added in the past since the last idle time.
1165     */
1166    long mLowRamTimeSinceLastIdle = 0;
1167
1168    /**
1169     * If RAM is currently low, when that horrible situation started.
1170     */
1171    long mLowRamStartTime = 0;
1172
1173    /**
1174     * For reporting to battery stats the current top application.
1175     */
1176    private String mCurResumedPackage = null;
1177    private int mCurResumedUid = -1;
1178
1179    /**
1180     * For reporting to battery stats the apps currently running foreground
1181     * service.  The ProcessMap is package/uid tuples; each of these contain
1182     * an array of the currently foreground processes.
1183     */
1184    final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1185            = new ProcessMap<ArrayList<ProcessRecord>>();
1186
1187    /**
1188     * This is set if we had to do a delayed dexopt of an app before launching
1189     * it, to increase the ANR timeouts in that case.
1190     */
1191    boolean mDidDexOpt;
1192
1193    /**
1194     * Set if the systemServer made a call to enterSafeMode.
1195     */
1196    boolean mSafeMode;
1197
1198    /**
1199     * If true, we are running under a test environment so will sample PSS from processes
1200     * much more rapidly to try to collect better data when the tests are rapidly
1201     * running through apps.
1202     */
1203    boolean mTestPssMode = false;
1204
1205    String mDebugApp = null;
1206    boolean mWaitForDebugger = false;
1207    boolean mDebugTransient = false;
1208    String mOrigDebugApp = null;
1209    boolean mOrigWaitForDebugger = false;
1210    boolean mAlwaysFinishActivities = false;
1211    IActivityController mController = null;
1212    String mProfileApp = null;
1213    ProcessRecord mProfileProc = null;
1214    String mProfileFile;
1215    ParcelFileDescriptor mProfileFd;
1216    int mSamplingInterval = 0;
1217    boolean mAutoStopProfiler = false;
1218    int mProfileType = 0;
1219    String mOpenGlTraceApp = null;
1220    final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>();
1221    String mMemWatchDumpProcName;
1222    String mMemWatchDumpFile;
1223    int mMemWatchDumpPid;
1224    int mMemWatchDumpUid;
1225
1226    final long[] mTmpLong = new long[1];
1227
1228    static final class ProcessChangeItem {
1229        static final int CHANGE_ACTIVITIES = 1<<0;
1230        static final int CHANGE_PROCESS_STATE = 1<<1;
1231        int changes;
1232        int uid;
1233        int pid;
1234        int processState;
1235        boolean foregroundActivities;
1236    }
1237
1238    final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>();
1239    ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
1240
1241    final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>();
1242    final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>();
1243
1244    final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>();
1245    UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5];
1246
1247    final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>();
1248    final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>();
1249
1250    /**
1251     * Runtime CPU use collection thread.  This object's lock is used to
1252     * perform synchronization with the thread (notifying it to run).
1253     */
1254    final Thread mProcessCpuThread;
1255
1256    /**
1257     * Used to collect per-process CPU use for ANRs, battery stats, etc.
1258     * Must acquire this object's lock when accessing it.
1259     * NOTE: this lock will be held while doing long operations (trawling
1260     * through all processes in /proc), so it should never be acquired by
1261     * any critical paths such as when holding the main activity manager lock.
1262     */
1263    final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
1264            MONITOR_THREAD_CPU_USAGE);
1265    final AtomicLong mLastCpuTime = new AtomicLong(0);
1266    final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
1267
1268    long mLastWriteTime = 0;
1269
1270    /**
1271     * Used to retain an update lock when the foreground activity is in
1272     * immersive mode.
1273     */
1274    final UpdateLock mUpdateLock = new UpdateLock("immersive");
1275
1276    /**
1277     * Set to true after the system has finished booting.
1278     */
1279    boolean mBooted = false;
1280
1281    int mProcessLimit = ProcessList.MAX_CACHED_APPS;
1282    int mProcessLimitOverride = -1;
1283
1284    WindowManagerService mWindowManager;
1285
1286    final ActivityThread mSystemThread;
1287
1288    // Holds the current foreground user's id
1289    int mCurrentUserId = 0;
1290    // Holds the target user's id during a user switch
1291    int mTargetUserId = UserHandle.USER_NULL;
1292    // If there are multiple profiles for the current user, their ids are here
1293    // Currently only the primary user can have managed profiles
1294    int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack
1295
1296    /**
1297     * Mapping from each known user ID to the profile group ID it is associated with.
1298     */
1299    SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
1300
1301    private UserManagerService mUserManager;
1302
1303    private final class AppDeathRecipient implements IBinder.DeathRecipient {
1304        final ProcessRecord mApp;
1305        final int mPid;
1306        final IApplicationThread mAppThread;
1307
1308        AppDeathRecipient(ProcessRecord app, int pid,
1309                IApplicationThread thread) {
1310            if (DEBUG_ALL) Slog.v(
1311                TAG, "New death recipient " + this
1312                + " for thread " + thread.asBinder());
1313            mApp = app;
1314            mPid = pid;
1315            mAppThread = thread;
1316        }
1317
1318        @Override
1319        public void binderDied() {
1320            if (DEBUG_ALL) Slog.v(
1321                TAG, "Death received in " + this
1322                + " for thread " + mAppThread.asBinder());
1323            synchronized(ActivityManagerService.this) {
1324                appDiedLocked(mApp, mPid, mAppThread, true);
1325            }
1326        }
1327    }
1328
1329    static final int SHOW_ERROR_MSG = 1;
1330    static final int SHOW_NOT_RESPONDING_MSG = 2;
1331    static final int SHOW_FACTORY_ERROR_MSG = 3;
1332    static final int UPDATE_CONFIGURATION_MSG = 4;
1333    static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1334    static final int WAIT_FOR_DEBUGGER_MSG = 6;
1335    static final int SERVICE_TIMEOUT_MSG = 12;
1336    static final int UPDATE_TIME_ZONE = 13;
1337    static final int SHOW_UID_ERROR_MSG = 14;
1338    static final int SHOW_FINGERPRINT_ERROR_MSG = 15;
1339    static final int PROC_START_TIMEOUT_MSG = 20;
1340    static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
1341    static final int KILL_APPLICATION_MSG = 22;
1342    static final int FINALIZE_PENDING_INTENT_MSG = 23;
1343    static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1344    static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
1345    static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
1346    static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
1347    static final int CLEAR_DNS_CACHE_MSG = 28;
1348    static final int UPDATE_HTTP_PROXY_MSG = 29;
1349    static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
1350    static final int DISPATCH_PROCESSES_CHANGED = 31;
1351    static final int DISPATCH_PROCESS_DIED = 32;
1352    static final int REPORT_MEM_USAGE_MSG = 33;
1353    static final int REPORT_USER_SWITCH_MSG = 34;
1354    static final int CONTINUE_USER_SWITCH_MSG = 35;
1355    static final int USER_SWITCH_TIMEOUT_MSG = 36;
1356    static final int IMMERSIVE_MODE_LOCK_MSG = 37;
1357    static final int PERSIST_URI_GRANTS_MSG = 38;
1358    static final int REQUEST_ALL_PSS_MSG = 39;
1359    static final int START_PROFILES_MSG = 40;
1360    static final int UPDATE_TIME = 41;
1361    static final int SYSTEM_USER_START_MSG = 42;
1362    static final int SYSTEM_USER_CURRENT_MSG = 43;
1363    static final int ENTER_ANIMATION_COMPLETE_MSG = 44;
1364    static final int FINISH_BOOTING_MSG = 45;
1365    static final int START_USER_SWITCH_MSG = 46;
1366    static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47;
1367    static final int DISMISS_DIALOG_MSG = 48;
1368    static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG = 49;
1369    static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 50;
1370    static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 51;
1371    static final int DELETE_DUMPHEAP_MSG = 52;
1372    static final int FOREGROUND_PROFILE_CHANGED_MSG = 53;
1373    static final int DISPATCH_UIDS_CHANGED_MSG = 54;
1374    static final int REPORT_TIME_TRACKER_MSG = 55;
1375    static final int REPORT_USER_SWITCH_COMPLETE_MSG = 56;
1376    static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 57;
1377    static final int APP_BOOST_DEACTIVATE_MSG = 58;
1378    static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 59;
1379
1380    static final int FIRST_ACTIVITY_STACK_MSG = 100;
1381    static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1382    static final int FIRST_COMPAT_MODE_MSG = 300;
1383    static final int FIRST_SUPERVISOR_STACK_MSG = 100;
1384
1385    CompatModeDialog mCompatModeDialog;
1386    long mLastMemUsageReportTime = 0;
1387
1388    /**
1389     * Flag whether the current user is a "monkey", i.e. whether
1390     * the UI is driven by a UI automation tool.
1391     */
1392    private boolean mUserIsMonkey;
1393
1394    /** Flag whether the device has a Recents UI */
1395    boolean mHasRecents;
1396
1397    /** The dimensions of the thumbnails in the Recents UI. */
1398    int mThumbnailWidth;
1399    int mThumbnailHeight;
1400
1401    final ServiceThread mHandlerThread;
1402    final MainHandler mHandler;
1403    final UiHandler mUiHandler;
1404
1405    final class UiHandler extends Handler {
1406        public UiHandler() {
1407            super(com.android.server.UiThread.get().getLooper(), null, true);
1408        }
1409
1410        @Override
1411        public void handleMessage(Message msg) {
1412            switch (msg.what) {
1413            case SHOW_ERROR_MSG: {
1414                HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1415                boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
1416                        Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
1417                synchronized (ActivityManagerService.this) {
1418                    ProcessRecord proc = (ProcessRecord)data.get("app");
1419                    AppErrorResult res = (AppErrorResult) data.get("result");
1420                    if (proc != null && proc.crashDialog != null) {
1421                        Slog.e(TAG, "App already has crash dialog: " + proc);
1422                        if (res != null) {
1423                            res.set(0);
1424                        }
1425                        return;
1426                    }
1427                    boolean isBackground = (UserHandle.getAppId(proc.uid)
1428                            >= Process.FIRST_APPLICATION_UID
1429                            && proc.pid != MY_PID);
1430                    for (int userId : mCurrentProfileIds) {
1431                        isBackground &= (proc.userId != userId);
1432                    }
1433                    if (isBackground && !showBackground) {
1434                        Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
1435                        if (res != null) {
1436                            res.set(0);
1437                        }
1438                        return;
1439                    }
1440                    if (mShowDialogs && !mSleeping && !mShuttingDown) {
1441                        Dialog d = new AppErrorDialog(mContext,
1442                                ActivityManagerService.this, res, proc);
1443                        d.show();
1444                        proc.crashDialog = d;
1445                    } else {
1446                        // The device is asleep, so just pretend that the user
1447                        // saw a crash dialog and hit "force quit".
1448                        if (res != null) {
1449                            res.set(0);
1450                        }
1451                    }
1452                }
1453
1454                ensureBootCompleted();
1455            } break;
1456            case SHOW_NOT_RESPONDING_MSG: {
1457                synchronized (ActivityManagerService.this) {
1458                    HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1459                    ProcessRecord proc = (ProcessRecord)data.get("app");
1460                    if (proc != null && proc.anrDialog != null) {
1461                        Slog.e(TAG, "App already has anr dialog: " + proc);
1462                        return;
1463                    }
1464
1465                    Intent intent = new Intent("android.intent.action.ANR");
1466                    if (!mProcessesReady) {
1467                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1468                                | Intent.FLAG_RECEIVER_FOREGROUND);
1469                    }
1470                    broadcastIntentLocked(null, null, intent,
1471                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1472                            null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
1473
1474                    if (mShowDialogs) {
1475                        Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
1476                                mContext, proc, (ActivityRecord)data.get("activity"),
1477                                msg.arg1 != 0);
1478                        d.show();
1479                        proc.anrDialog = d;
1480                    } else {
1481                        // Just kill the app if there is no dialog to be shown.
1482                        killAppAtUsersRequest(proc, null);
1483                    }
1484                }
1485
1486                ensureBootCompleted();
1487            } break;
1488            case SHOW_STRICT_MODE_VIOLATION_MSG: {
1489                HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1490                synchronized (ActivityManagerService.this) {
1491                    ProcessRecord proc = (ProcessRecord) data.get("app");
1492                    if (proc == null) {
1493                        Slog.e(TAG, "App not found when showing strict mode dialog.");
1494                        break;
1495                    }
1496                    if (proc.crashDialog != null) {
1497                        Slog.e(TAG, "App already has strict mode dialog: " + proc);
1498                        return;
1499                    }
1500                    AppErrorResult res = (AppErrorResult) data.get("result");
1501                    if (mShowDialogs && !mSleeping && !mShuttingDown) {
1502                        Dialog d = new StrictModeViolationDialog(mContext,
1503                                ActivityManagerService.this, res, proc);
1504                        d.show();
1505                        proc.crashDialog = d;
1506                    } else {
1507                        // The device is asleep, so just pretend that the user
1508                        // saw a crash dialog and hit "force quit".
1509                        res.set(0);
1510                    }
1511                }
1512                ensureBootCompleted();
1513            } break;
1514            case SHOW_FACTORY_ERROR_MSG: {
1515                Dialog d = new FactoryErrorDialog(
1516                    mContext, msg.getData().getCharSequence("msg"));
1517                d.show();
1518                ensureBootCompleted();
1519            } break;
1520            case WAIT_FOR_DEBUGGER_MSG: {
1521                synchronized (ActivityManagerService.this) {
1522                    ProcessRecord app = (ProcessRecord)msg.obj;
1523                    if (msg.arg1 != 0) {
1524                        if (!app.waitedForDebugger) {
1525                            Dialog d = new AppWaitingForDebuggerDialog(
1526                                    ActivityManagerService.this,
1527                                    mContext, app);
1528                            app.waitDialog = d;
1529                            app.waitedForDebugger = true;
1530                            d.show();
1531                        }
1532                    } else {
1533                        if (app.waitDialog != null) {
1534                            app.waitDialog.dismiss();
1535                            app.waitDialog = null;
1536                        }
1537                    }
1538                }
1539            } break;
1540            case SHOW_UID_ERROR_MSG: {
1541                if (mShowDialogs) {
1542                    AlertDialog d = new BaseErrorDialog(mContext);
1543                    d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1544                    d.setCancelable(false);
1545                    d.setTitle(mContext.getText(R.string.android_system_label));
1546                    d.setMessage(mContext.getText(R.string.system_error_wipe_data));
1547                    d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
1548                            obtainMessage(DISMISS_DIALOG_MSG, d));
1549                    d.show();
1550                }
1551            } break;
1552            case SHOW_FINGERPRINT_ERROR_MSG: {
1553                if (mShowDialogs) {
1554                    AlertDialog d = new BaseErrorDialog(mContext);
1555                    d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1556                    d.setCancelable(false);
1557                    d.setTitle(mContext.getText(R.string.android_system_label));
1558                    d.setMessage(mContext.getText(R.string.system_error_manufacturer));
1559                    d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
1560                            obtainMessage(DISMISS_DIALOG_MSG, d));
1561                    d.show();
1562                }
1563            } break;
1564            case SHOW_COMPAT_MODE_DIALOG_MSG: {
1565                synchronized (ActivityManagerService.this) {
1566                    ActivityRecord ar = (ActivityRecord) msg.obj;
1567                    if (mCompatModeDialog != null) {
1568                        if (mCompatModeDialog.mAppInfo.packageName.equals(
1569                                ar.info.applicationInfo.packageName)) {
1570                            return;
1571                        }
1572                        mCompatModeDialog.dismiss();
1573                        mCompatModeDialog = null;
1574                    }
1575                    if (ar != null && false) {
1576                        if (mCompatModePackages.getPackageAskCompatModeLocked(
1577                                ar.packageName)) {
1578                            int mode = mCompatModePackages.computeCompatModeLocked(
1579                                    ar.info.applicationInfo);
1580                            if (mode == ActivityManager.COMPAT_MODE_DISABLED
1581                                    || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1582                                mCompatModeDialog = new CompatModeDialog(
1583                                        ActivityManagerService.this, mContext,
1584                                        ar.info.applicationInfo);
1585                                mCompatModeDialog.show();
1586                            }
1587                        }
1588                    }
1589                }
1590                break;
1591            }
1592            case START_USER_SWITCH_MSG: {
1593                showUserSwitchDialog(msg.arg1, (String) msg.obj);
1594                break;
1595            }
1596            case DISMISS_DIALOG_MSG: {
1597                final Dialog d = (Dialog) msg.obj;
1598                d.dismiss();
1599                break;
1600            }
1601            case DISPATCH_PROCESSES_CHANGED: {
1602                dispatchProcessesChanged();
1603                break;
1604            }
1605            case DISPATCH_PROCESS_DIED: {
1606                final int pid = msg.arg1;
1607                final int uid = msg.arg2;
1608                dispatchProcessDied(pid, uid);
1609                break;
1610            }
1611            case DISPATCH_UIDS_CHANGED_MSG: {
1612                dispatchUidsChanged();
1613            } break;
1614            }
1615        }
1616    }
1617
1618    final class MainHandler extends Handler {
1619        public MainHandler(Looper looper) {
1620            super(looper, null, true);
1621        }
1622
1623        @Override
1624        public void handleMessage(Message msg) {
1625            switch (msg.what) {
1626            case UPDATE_CONFIGURATION_MSG: {
1627                final ContentResolver resolver = mContext.getContentResolver();
1628                Settings.System.putConfiguration(resolver, (Configuration) msg.obj);
1629            } break;
1630            case GC_BACKGROUND_PROCESSES_MSG: {
1631                synchronized (ActivityManagerService.this) {
1632                    performAppGcsIfAppropriateLocked();
1633                }
1634            } break;
1635            case SERVICE_TIMEOUT_MSG: {
1636                if (mDidDexOpt) {
1637                    mDidDexOpt = false;
1638                    Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1639                    nmsg.obj = msg.obj;
1640                    mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
1641                    return;
1642                }
1643                mServices.serviceTimeout((ProcessRecord)msg.obj);
1644            } break;
1645            case UPDATE_TIME_ZONE: {
1646                synchronized (ActivityManagerService.this) {
1647                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1648                        ProcessRecord r = mLruProcesses.get(i);
1649                        if (r.thread != null) {
1650                            try {
1651                                r.thread.updateTimeZone();
1652                            } catch (RemoteException ex) {
1653                                Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
1654                            }
1655                        }
1656                    }
1657                }
1658            } break;
1659            case CLEAR_DNS_CACHE_MSG: {
1660                synchronized (ActivityManagerService.this) {
1661                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1662                        ProcessRecord r = mLruProcesses.get(i);
1663                        if (r.thread != null) {
1664                            try {
1665                                r.thread.clearDnsCache();
1666                            } catch (RemoteException ex) {
1667                                Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1668                            }
1669                        }
1670                    }
1671                }
1672            } break;
1673            case UPDATE_HTTP_PROXY_MSG: {
1674                ProxyInfo proxy = (ProxyInfo)msg.obj;
1675                String host = "";
1676                String port = "";
1677                String exclList = "";
1678                Uri pacFileUrl = Uri.EMPTY;
1679                if (proxy != null) {
1680                    host = proxy.getHost();
1681                    port = Integer.toString(proxy.getPort());
1682                    exclList = proxy.getExclusionListAsString();
1683                    pacFileUrl = proxy.getPacFileUrl();
1684                }
1685                synchronized (ActivityManagerService.this) {
1686                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1687                        ProcessRecord r = mLruProcesses.get(i);
1688                        if (r.thread != null) {
1689                            try {
1690                                r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
1691                            } catch (RemoteException ex) {
1692                                Slog.w(TAG, "Failed to update http proxy for: " +
1693                                        r.info.processName);
1694                            }
1695                        }
1696                    }
1697                }
1698            } break;
1699            case PROC_START_TIMEOUT_MSG: {
1700                if (mDidDexOpt) {
1701                    mDidDexOpt = false;
1702                    Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1703                    nmsg.obj = msg.obj;
1704                    mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1705                    return;
1706                }
1707                ProcessRecord app = (ProcessRecord)msg.obj;
1708                synchronized (ActivityManagerService.this) {
1709                    processStartTimedOutLocked(app);
1710                }
1711            } break;
1712            case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
1713                ProcessRecord app = (ProcessRecord)msg.obj;
1714                synchronized (ActivityManagerService.this) {
1715                    processContentProviderPublishTimedOutLocked(app);
1716                }
1717            } break;
1718            case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1719                synchronized (ActivityManagerService.this) {
1720                    mStackSupervisor.doPendingActivityLaunchesLocked(true);
1721                }
1722            } break;
1723            case KILL_APPLICATION_MSG: {
1724                synchronized (ActivityManagerService.this) {
1725                    int appid = msg.arg1;
1726                    boolean restart = (msg.arg2 == 1);
1727                    Bundle bundle = (Bundle)msg.obj;
1728                    String pkg = bundle.getString("pkg");
1729                    String reason = bundle.getString("reason");
1730                    forceStopPackageLocked(pkg, appid, restart, false, true, false,
1731                            false, UserHandle.USER_ALL, reason);
1732                }
1733            } break;
1734            case FINALIZE_PENDING_INTENT_MSG: {
1735                ((PendingIntentRecord)msg.obj).completeFinalize();
1736            } break;
1737            case POST_HEAVY_NOTIFICATION_MSG: {
1738                INotificationManager inm = NotificationManager.getService();
1739                if (inm == null) {
1740                    return;
1741                }
1742
1743                ActivityRecord root = (ActivityRecord)msg.obj;
1744                ProcessRecord process = root.app;
1745                if (process == null) {
1746                    return;
1747                }
1748
1749                try {
1750                    Context context = mContext.createPackageContext(process.info.packageName, 0);
1751                    String text = mContext.getString(R.string.heavy_weight_notification,
1752                            context.getApplicationInfo().loadLabel(context.getPackageManager()));
1753                    Notification notification = new Notification.Builder(context)
1754                            .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
1755                            .setWhen(0)
1756                            .setOngoing(true)
1757                            .setTicker(text)
1758                            .setColor(mContext.getColor(
1759                                    com.android.internal.R.color.system_notification_accent_color))
1760                            .setContentTitle(text)
1761                            .setContentText(
1762                                    mContext.getText(R.string.heavy_weight_notification_detail))
1763                            .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
1764                                    root.intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
1765                                    new UserHandle(root.userId)))
1766                            .build();
1767                    try {
1768                        int[] outId = new int[1];
1769                        inm.enqueueNotificationWithTag("android", "android", null,
1770                                R.string.heavy_weight_notification,
1771                                notification, outId, root.userId);
1772                    } catch (RuntimeException e) {
1773                        Slog.w(ActivityManagerService.TAG,
1774                                "Error showing notification for heavy-weight app", e);
1775                    } catch (RemoteException e) {
1776                    }
1777                } catch (NameNotFoundException e) {
1778                    Slog.w(TAG, "Unable to create context for heavy notification", e);
1779                }
1780            } break;
1781            case CANCEL_HEAVY_NOTIFICATION_MSG: {
1782                INotificationManager inm = NotificationManager.getService();
1783                if (inm == null) {
1784                    return;
1785                }
1786                try {
1787                    inm.cancelNotificationWithTag("android", null,
1788                            R.string.heavy_weight_notification,  msg.arg1);
1789                } catch (RuntimeException e) {
1790                    Slog.w(ActivityManagerService.TAG,
1791                            "Error canceling notification for service", e);
1792                } catch (RemoteException e) {
1793                }
1794            } break;
1795            case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1796                synchronized (ActivityManagerService.this) {
1797                    checkExcessivePowerUsageLocked(true);
1798                    removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1799                    Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1800                    sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
1801                }
1802            } break;
1803            case REPORT_MEM_USAGE_MSG: {
1804                final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
1805                Thread thread = new Thread() {
1806                    @Override public void run() {
1807                        reportMemUsage(memInfos);
1808                    }
1809                };
1810                thread.start();
1811                break;
1812            }
1813            case REPORT_USER_SWITCH_MSG: {
1814                dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
1815                break;
1816            }
1817            case CONTINUE_USER_SWITCH_MSG: {
1818                continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
1819                break;
1820            }
1821            case USER_SWITCH_TIMEOUT_MSG: {
1822                timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
1823                break;
1824            }
1825            case IMMERSIVE_MODE_LOCK_MSG: {
1826                final boolean nextState = (msg.arg1 != 0);
1827                if (mUpdateLock.isHeld() != nextState) {
1828                    if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1829                            "Applying new update lock state '" + nextState
1830                            + "' for " + (ActivityRecord)msg.obj);
1831                    if (nextState) {
1832                        mUpdateLock.acquire();
1833                    } else {
1834                        mUpdateLock.release();
1835                    }
1836                }
1837                break;
1838            }
1839            case PERSIST_URI_GRANTS_MSG: {
1840                writeGrantedUriPermissions();
1841                break;
1842            }
1843            case REQUEST_ALL_PSS_MSG: {
1844                synchronized (ActivityManagerService.this) {
1845                    requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
1846                }
1847                break;
1848            }
1849            case START_PROFILES_MSG: {
1850                synchronized (ActivityManagerService.this) {
1851                    startProfilesLocked();
1852                }
1853                break;
1854            }
1855            case UPDATE_TIME: {
1856                synchronized (ActivityManagerService.this) {
1857                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1858                        ProcessRecord r = mLruProcesses.get(i);
1859                        if (r.thread != null) {
1860                            try {
1861                                r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true);
1862                            } catch (RemoteException ex) {
1863                                Slog.w(TAG, "Failed to update preferences for: " + r.info.processName);
1864                            }
1865                        }
1866                    }
1867                }
1868                break;
1869            }
1870            case SYSTEM_USER_START_MSG: {
1871                mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
1872                        Integer.toString(msg.arg1), msg.arg1);
1873                mSystemServiceManager.startUser(msg.arg1);
1874                break;
1875            }
1876            case SYSTEM_USER_CURRENT_MSG: {
1877                mBatteryStatsService.noteEvent(
1878                        BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
1879                        Integer.toString(msg.arg2), msg.arg2);
1880                mBatteryStatsService.noteEvent(
1881                        BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
1882                        Integer.toString(msg.arg1), msg.arg1);
1883                mSystemServiceManager.switchUser(msg.arg1);
1884                break;
1885            }
1886            case ENTER_ANIMATION_COMPLETE_MSG: {
1887                synchronized (ActivityManagerService.this) {
1888                    ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
1889                    if (r != null && r.app != null && r.app.thread != null) {
1890                        try {
1891                            r.app.thread.scheduleEnterAnimationComplete(r.appToken);
1892                        } catch (RemoteException e) {
1893                        }
1894                    }
1895                }
1896                break;
1897            }
1898            case FINISH_BOOTING_MSG: {
1899                if (msg.arg1 != 0) {
1900                    finishBooting();
1901                }
1902                if (msg.arg2 != 0) {
1903                    enableScreenAfterBoot();
1904                }
1905                break;
1906            }
1907            case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: {
1908                try {
1909                    Locale l = (Locale) msg.obj;
1910                    IBinder service = ServiceManager.getService("mount");
1911                    IMountService mountService = IMountService.Stub.asInterface(service);
1912                    Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
1913                    mountService.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
1914                } catch (RemoteException e) {
1915                    Log.e(TAG, "Error storing locale for decryption UI", e);
1916                }
1917                break;
1918            }
1919            case NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG: {
1920                synchronized (ActivityManagerService.this) {
1921                    int i = mTaskStackListeners.beginBroadcast();
1922                    while (i > 0) {
1923                        i--;
1924                        try {
1925                            // Make a one-way callback to the listener
1926                            mTaskStackListeners.getBroadcastItem(i).onTaskStackChanged();
1927                        } catch (RemoteException e){
1928                            // Handled by the RemoteCallbackList
1929                        }
1930                    }
1931                    mTaskStackListeners.finishBroadcast();
1932                }
1933                break;
1934            }
1935            case NOTIFY_CLEARTEXT_NETWORK_MSG: {
1936                final int uid = msg.arg1;
1937                final byte[] firstPacket = (byte[]) msg.obj;
1938
1939                synchronized (mPidsSelfLocked) {
1940                    for (int i = 0; i < mPidsSelfLocked.size(); i++) {
1941                        final ProcessRecord p = mPidsSelfLocked.valueAt(i);
1942                        if (p.uid == uid) {
1943                            try {
1944                                p.thread.notifyCleartextNetwork(firstPacket);
1945                            } catch (RemoteException ignored) {
1946                            }
1947                        }
1948                    }
1949                }
1950                break;
1951            }
1952            case POST_DUMP_HEAP_NOTIFICATION_MSG: {
1953                final String procName;
1954                final int uid;
1955                final long memLimit;
1956                final String reportPackage;
1957                synchronized (ActivityManagerService.this) {
1958                    procName = mMemWatchDumpProcName;
1959                    uid = mMemWatchDumpUid;
1960                    Pair<Long, String> val = mMemWatchProcesses.get(procName, uid);
1961                    if (val == null) {
1962                        val = mMemWatchProcesses.get(procName, 0);
1963                    }
1964                    if (val != null) {
1965                        memLimit = val.first;
1966                        reportPackage = val.second;
1967                    } else {
1968                        memLimit = 0;
1969                        reportPackage = null;
1970                    }
1971                }
1972                if (procName == null) {
1973                    return;
1974                }
1975
1976                if (DEBUG_PSS) Slog.d(TAG_PSS,
1977                        "Showing dump heap notification from " + procName + "/" + uid);
1978
1979                INotificationManager inm = NotificationManager.getService();
1980                if (inm == null) {
1981                    return;
1982                }
1983
1984                String text = mContext.getString(R.string.dump_heap_notification, procName);
1985
1986
1987                Intent deleteIntent = new Intent();
1988                deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
1989                Intent intent = new Intent();
1990                intent.setClassName("android", DumpHeapActivity.class.getName());
1991                intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName);
1992                intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit);
1993                if (reportPackage != null) {
1994                    intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage);
1995                }
1996                int userId = UserHandle.getUserId(uid);
1997                Notification notification = new Notification.Builder(mContext)
1998                        .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
1999                        .setWhen(0)
2000                        .setOngoing(true)
2001                        .setAutoCancel(true)
2002                        .setTicker(text)
2003                        .setColor(mContext.getColor(
2004                                com.android.internal.R.color.system_notification_accent_color))
2005                        .setContentTitle(text)
2006                        .setContentText(
2007                                mContext.getText(R.string.dump_heap_notification_detail))
2008                        .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
2009                                intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
2010                                new UserHandle(userId)))
2011                        .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0,
2012                                deleteIntent, 0, UserHandle.OWNER))
2013                        .build();
2014
2015                try {
2016                    int[] outId = new int[1];
2017                    inm.enqueueNotificationWithTag("android", "android", null,
2018                            R.string.dump_heap_notification,
2019                            notification, outId, userId);
2020                } catch (RuntimeException e) {
2021                    Slog.w(ActivityManagerService.TAG,
2022                            "Error showing notification for dump heap", e);
2023                } catch (RemoteException e) {
2024                }
2025            } break;
2026            case DELETE_DUMPHEAP_MSG: {
2027                revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(),
2028                        DumpHeapActivity.JAVA_URI,
2029                        Intent.FLAG_GRANT_READ_URI_PERMISSION
2030                                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
2031                        UserHandle.myUserId());
2032                synchronized (ActivityManagerService.this) {
2033                    mMemWatchDumpFile = null;
2034                    mMemWatchDumpProcName = null;
2035                    mMemWatchDumpPid = -1;
2036                    mMemWatchDumpUid = -1;
2037                }
2038            } break;
2039            case FOREGROUND_PROFILE_CHANGED_MSG: {
2040                dispatchForegroundProfileChanged(msg.arg1);
2041            } break;
2042            case REPORT_TIME_TRACKER_MSG: {
2043                AppTimeTracker tracker = (AppTimeTracker)msg.obj;
2044                tracker.deliverResult(mContext);
2045            } break;
2046            case REPORT_USER_SWITCH_COMPLETE_MSG: {
2047                dispatchUserSwitchComplete(msg.arg1);
2048            } break;
2049            case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
2050                IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
2051                try {
2052                    connection.shutdown();
2053                } catch (RemoteException e) {
2054                    Slog.w(TAG, "Error shutting down UiAutomationConnection");
2055                }
2056                // Only a UiAutomation can set this flag and now that
2057                // it is finished we make sure it is reset to its default.
2058                mUserIsMonkey = false;
2059            } break;
2060            case APP_BOOST_DEACTIVATE_MSG : {
2061                synchronized(ActivityManagerService.this) {
2062                    if (mIsBoosted) {
2063                        if (mBoostStartTime < (SystemClock.uptimeMillis() - APP_BOOST_TIMEOUT)) {
2064                            nativeMigrateFromBoost();
2065                            mIsBoosted = false;
2066                            mBoostStartTime = 0;
2067                        } else {
2068                            Message newmsg = mHandler.obtainMessage(APP_BOOST_DEACTIVATE_MSG);
2069                            mHandler.sendMessageDelayed(newmsg, APP_BOOST_TIMEOUT);
2070                        }
2071                    }
2072                }
2073            } break;
2074            }
2075        }
2076    };
2077
2078    static final int COLLECT_PSS_BG_MSG = 1;
2079
2080    final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
2081        @Override
2082        public void handleMessage(Message msg) {
2083            switch (msg.what) {
2084            case COLLECT_PSS_BG_MSG: {
2085                long start = SystemClock.uptimeMillis();
2086                MemInfoReader memInfo = null;
2087                synchronized (ActivityManagerService.this) {
2088                    if (mFullPssPending) {
2089                        mFullPssPending = false;
2090                        memInfo = new MemInfoReader();
2091                    }
2092                }
2093                if (memInfo != null) {
2094                    updateCpuStatsNow();
2095                    long nativeTotalPss = 0;
2096                    synchronized (mProcessCpuTracker) {
2097                        final int N = mProcessCpuTracker.countStats();
2098                        for (int j=0; j<N; j++) {
2099                            ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j);
2100                            if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) {
2101                                // This is definitely an application process; skip it.
2102                                continue;
2103                            }
2104                            synchronized (mPidsSelfLocked) {
2105                                if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) {
2106                                    // This is one of our own processes; skip it.
2107                                    continue;
2108                                }
2109                            }
2110                            nativeTotalPss += Debug.getPss(st.pid, null, null);
2111                        }
2112                    }
2113                    memInfo.readMemInfo();
2114                    synchronized (ActivityManagerService.this) {
2115                        if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in "
2116                                + (SystemClock.uptimeMillis()-start) + "ms");
2117                        final long cachedKb = memInfo.getCachedSizeKb();
2118                        final long freeKb = memInfo.getFreeSizeKb();
2119                        final long zramKb = memInfo.getZramTotalSizeKb();
2120                        final long kernelKb = memInfo.getKernelUsedSizeKb();
2121                        EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
2122                                kernelKb*1024, nativeTotalPss*1024);
2123                        mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
2124                                nativeTotalPss);
2125                    }
2126                }
2127
2128                int num = 0;
2129                long[] tmp = new long[1];
2130                do {
2131                    ProcessRecord proc;
2132                    int procState;
2133                    int pid;
2134                    long lastPssTime;
2135                    synchronized (ActivityManagerService.this) {
2136                        if (mPendingPssProcesses.size() <= 0) {
2137                            if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS,
2138                                    "Collected PSS of " + num + " processes in "
2139                                    + (SystemClock.uptimeMillis() - start) + "ms");
2140                            mPendingPssProcesses.clear();
2141                            return;
2142                        }
2143                        proc = mPendingPssProcesses.remove(0);
2144                        procState = proc.pssProcState;
2145                        lastPssTime = proc.lastPssTime;
2146                        if (proc.thread != null && procState == proc.setProcState
2147                                && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
2148                                        < SystemClock.uptimeMillis()) {
2149                            pid = proc.pid;
2150                        } else {
2151                            proc = null;
2152                            pid = 0;
2153                        }
2154                    }
2155                    if (proc != null) {
2156                        long pss = Debug.getPss(pid, tmp, null);
2157                        synchronized (ActivityManagerService.this) {
2158                            if (pss != 0 && proc.thread != null && proc.setProcState == procState
2159                                    && proc.pid == pid && proc.lastPssTime == lastPssTime) {
2160                                num++;
2161                                recordPssSampleLocked(proc, procState, pss, tmp[0],
2162                                        SystemClock.uptimeMillis());
2163                            }
2164                        }
2165                    }
2166                } while (true);
2167            }
2168            }
2169        }
2170    };
2171
2172    public void setSystemProcess() {
2173        try {
2174            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
2175            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2176            ServiceManager.addService("meminfo", new MemBinder(this));
2177            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2178            ServiceManager.addService("dbinfo", new DbBinder(this));
2179            if (MONITOR_CPU_USAGE) {
2180                ServiceManager.addService("cpuinfo", new CpuBinder(this));
2181            }
2182            ServiceManager.addService("permission", new PermissionController(this));
2183            ServiceManager.addService("processinfo", new ProcessInfoService(this));
2184
2185            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2186                    "android", STOCK_PM_FLAGS);
2187            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2188
2189            synchronized (this) {
2190                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2191                app.persistent = true;
2192                app.pid = MY_PID;
2193                app.maxAdj = ProcessList.SYSTEM_ADJ;
2194                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2195                synchronized (mPidsSelfLocked) {
2196                    mPidsSelfLocked.put(app.pid, app);
2197                }
2198                updateLruProcessLocked(app, false, null);
2199                updateOomAdjLocked();
2200            }
2201        } catch (PackageManager.NameNotFoundException e) {
2202            throw new RuntimeException(
2203                    "Unable to find android system package", e);
2204        }
2205    }
2206
2207    public void setWindowManager(WindowManagerService wm) {
2208        mWindowManager = wm;
2209        mStackSupervisor.setWindowManager(wm);
2210    }
2211
2212    public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
2213        mUsageStatsService = usageStatsManager;
2214    }
2215
2216    public void startObservingNativeCrashes() {
2217        final NativeCrashListener ncl = new NativeCrashListener(this);
2218        ncl.start();
2219    }
2220
2221    public IAppOpsService getAppOpsService() {
2222        return mAppOpsService;
2223    }
2224
2225    static class MemBinder extends Binder {
2226        ActivityManagerService mActivityManagerService;
2227        MemBinder(ActivityManagerService activityManagerService) {
2228            mActivityManagerService = activityManagerService;
2229        }
2230
2231        @Override
2232        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2233            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2234                    != PackageManager.PERMISSION_GRANTED) {
2235                pw.println("Permission Denial: can't dump meminfo from from pid="
2236                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2237                        + " without permission " + android.Manifest.permission.DUMP);
2238                return;
2239            }
2240
2241            mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, "  ", args, false, null);
2242        }
2243    }
2244
2245    static class GraphicsBinder extends Binder {
2246        ActivityManagerService mActivityManagerService;
2247        GraphicsBinder(ActivityManagerService activityManagerService) {
2248            mActivityManagerService = activityManagerService;
2249        }
2250
2251        @Override
2252        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2253            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2254                    != PackageManager.PERMISSION_GRANTED) {
2255                pw.println("Permission Denial: can't dump gfxinfo from from pid="
2256                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2257                        + " without permission " + android.Manifest.permission.DUMP);
2258                return;
2259            }
2260
2261            mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2262        }
2263    }
2264
2265    static class DbBinder extends Binder {
2266        ActivityManagerService mActivityManagerService;
2267        DbBinder(ActivityManagerService activityManagerService) {
2268            mActivityManagerService = activityManagerService;
2269        }
2270
2271        @Override
2272        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2273            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2274                    != PackageManager.PERMISSION_GRANTED) {
2275                pw.println("Permission Denial: can't dump dbinfo from from pid="
2276                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2277                        + " without permission " + android.Manifest.permission.DUMP);
2278                return;
2279            }
2280
2281            mActivityManagerService.dumpDbInfo(fd, pw, args);
2282        }
2283    }
2284
2285    static class CpuBinder extends Binder {
2286        ActivityManagerService mActivityManagerService;
2287        CpuBinder(ActivityManagerService activityManagerService) {
2288            mActivityManagerService = activityManagerService;
2289        }
2290
2291        @Override
2292        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2293            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2294                    != PackageManager.PERMISSION_GRANTED) {
2295                pw.println("Permission Denial: can't dump cpuinfo from from pid="
2296                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2297                        + " without permission " + android.Manifest.permission.DUMP);
2298                return;
2299            }
2300
2301            synchronized (mActivityManagerService.mProcessCpuTracker) {
2302                pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
2303                pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
2304                        SystemClock.uptimeMillis()));
2305            }
2306        }
2307    }
2308
2309    public static final class Lifecycle extends SystemService {
2310        private final ActivityManagerService mService;
2311
2312        public Lifecycle(Context context) {
2313            super(context);
2314            mService = new ActivityManagerService(context);
2315        }
2316
2317        @Override
2318        public void onStart() {
2319            mService.start();
2320        }
2321
2322        public ActivityManagerService getService() {
2323            return mService;
2324        }
2325    }
2326
2327    // Note: This method is invoked on the main thread but may need to attach various
2328    // handlers to other threads.  So take care to be explicit about the looper.
2329    public ActivityManagerService(Context systemContext) {
2330        mContext = systemContext;
2331        mFactoryTest = FactoryTest.getMode();
2332        mSystemThread = ActivityThread.currentActivityThread();
2333
2334        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2335
2336        mHandlerThread = new ServiceThread(TAG,
2337                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2338        mHandlerThread.start();
2339        mHandler = new MainHandler(mHandlerThread.getLooper());
2340        mUiHandler = new UiHandler();
2341
2342        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2343                "foreground", BROADCAST_FG_TIMEOUT, false);
2344        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2345                "background", BROADCAST_BG_TIMEOUT, true);
2346        mBroadcastQueues[0] = mFgBroadcastQueue;
2347        mBroadcastQueues[1] = mBgBroadcastQueue;
2348
2349        mServices = new ActiveServices(this);
2350        mProviderMap = new ProviderMap(this);
2351
2352        // TODO: Move creation of battery stats service outside of activity manager service.
2353        File dataDir = Environment.getDataDirectory();
2354        File systemDir = new File(dataDir, "system");
2355        systemDir.mkdirs();
2356        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
2357        mBatteryStatsService.getActiveStatistics().readLocked();
2358        mBatteryStatsService.scheduleWriteToDisk();
2359        mOnBattery = DEBUG_POWER ? true
2360                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2361        mBatteryStatsService.getActiveStatistics().setCallback(this);
2362
2363        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2364
2365        mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
2366
2367        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
2368
2369        // User 0 is the first and only user that runs at boot.
2370        mStartedUsers.put(UserHandle.USER_OWNER, new UserState(UserHandle.OWNER, true));
2371        mUserLru.add(UserHandle.USER_OWNER);
2372        updateStartedUserArrayLocked();
2373
2374        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2375            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2376
2377        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2378
2379        mConfiguration.setToDefaults();
2380        mConfiguration.setLocale(Locale.getDefault());
2381
2382        mConfigurationSeq = mConfiguration.seq = 1;
2383        mProcessCpuTracker.init();
2384
2385        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
2386        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2387        mRecentTasks = new RecentTasks(this);
2388        mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks);
2389        mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks);
2390
2391        mProcessCpuThread = new Thread("CpuTracker") {
2392            @Override
2393            public void run() {
2394                while (true) {
2395                    try {
2396                        try {
2397                            synchronized(this) {
2398                                final long now = SystemClock.uptimeMillis();
2399                                long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2400                                long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2401                                //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2402                                //        + ", write delay=" + nextWriteDelay);
2403                                if (nextWriteDelay < nextCpuDelay) {
2404                                    nextCpuDelay = nextWriteDelay;
2405                                }
2406                                if (nextCpuDelay > 0) {
2407                                    mProcessCpuMutexFree.set(true);
2408                                    this.wait(nextCpuDelay);
2409                                }
2410                            }
2411                        } catch (InterruptedException e) {
2412                        }
2413                        updateCpuStatsNow();
2414                    } catch (Exception e) {
2415                        Slog.e(TAG, "Unexpected exception collecting process stats", e);
2416                    }
2417                }
2418            }
2419        };
2420
2421        Watchdog.getInstance().addMonitor(this);
2422        Watchdog.getInstance().addThread(mHandler);
2423    }
2424
2425    public void setSystemServiceManager(SystemServiceManager mgr) {
2426        mSystemServiceManager = mgr;
2427    }
2428
2429    public void setInstaller(Installer installer) {
2430        mInstaller = installer;
2431    }
2432
2433    private void start() {
2434        Process.removeAllProcessGroups();
2435        mProcessCpuThread.start();
2436
2437        mBatteryStatsService.publish(mContext);
2438        mAppOpsService.publish(mContext);
2439        Slog.d("AppOps", "AppOpsService published");
2440        LocalServices.addService(ActivityManagerInternal.class, new LocalService());
2441    }
2442
2443    public void initPowerManagement() {
2444        mStackSupervisor.initPowerManagement();
2445        mBatteryStatsService.initPowerManagement();
2446        mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2447        PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
2448        mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
2449        mVoiceWakeLock.setReferenceCounted(false);
2450    }
2451
2452    @Override
2453    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2454            throws RemoteException {
2455        if (code == SYSPROPS_TRANSACTION) {
2456            // We need to tell all apps about the system property change.
2457            ArrayList<IBinder> procs = new ArrayList<IBinder>();
2458            synchronized(this) {
2459                final int NP = mProcessNames.getMap().size();
2460                for (int ip=0; ip<NP; ip++) {
2461                    SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
2462                    final int NA = apps.size();
2463                    for (int ia=0; ia<NA; ia++) {
2464                        ProcessRecord app = apps.valueAt(ia);
2465                        if (app.thread != null) {
2466                            procs.add(app.thread.asBinder());
2467                        }
2468                    }
2469                }
2470            }
2471
2472            int N = procs.size();
2473            for (int i=0; i<N; i++) {
2474                Parcel data2 = Parcel.obtain();
2475                try {
2476                    procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
2477                } catch (RemoteException e) {
2478                }
2479                data2.recycle();
2480            }
2481        }
2482        try {
2483            return super.onTransact(code, data, reply, flags);
2484        } catch (RuntimeException e) {
2485            // The activity manager only throws security exceptions, so let's
2486            // log all others.
2487            if (!(e instanceof SecurityException)) {
2488                Slog.wtf(TAG, "Activity Manager Crash", e);
2489            }
2490            throw e;
2491        }
2492    }
2493
2494    void updateCpuStats() {
2495        final long now = SystemClock.uptimeMillis();
2496        if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2497            return;
2498        }
2499        if (mProcessCpuMutexFree.compareAndSet(true, false)) {
2500            synchronized (mProcessCpuThread) {
2501                mProcessCpuThread.notify();
2502            }
2503        }
2504    }
2505
2506    void updateCpuStatsNow() {
2507        synchronized (mProcessCpuTracker) {
2508            mProcessCpuMutexFree.set(false);
2509            final long now = SystemClock.uptimeMillis();
2510            boolean haveNewCpuStats = false;
2511
2512            if (MONITOR_CPU_USAGE &&
2513                    mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2514                mLastCpuTime.set(now);
2515                mProcessCpuTracker.update();
2516                if (mProcessCpuTracker.hasGoodLastStats()) {
2517                    haveNewCpuStats = true;
2518                    //Slog.i(TAG, mProcessCpu.printCurrentState());
2519                    //Slog.i(TAG, "Total CPU usage: "
2520                    //        + mProcessCpu.getTotalCpuPercent() + "%");
2521
2522                    // Slog the cpu usage if the property is set.
2523                    if ("true".equals(SystemProperties.get("events.cpu"))) {
2524                        int user = mProcessCpuTracker.getLastUserTime();
2525                        int system = mProcessCpuTracker.getLastSystemTime();
2526                        int iowait = mProcessCpuTracker.getLastIoWaitTime();
2527                        int irq = mProcessCpuTracker.getLastIrqTime();
2528                        int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
2529                        int idle = mProcessCpuTracker.getLastIdleTime();
2530
2531                        int total = user + system + iowait + irq + softIrq + idle;
2532                        if (total == 0) total = 1;
2533
2534                        EventLog.writeEvent(EventLogTags.CPU,
2535                                ((user+system+iowait+irq+softIrq) * 100) / total,
2536                                (user * 100) / total,
2537                                (system * 100) / total,
2538                                (iowait * 100) / total,
2539                                (irq * 100) / total,
2540                                (softIrq * 100) / total);
2541                    }
2542                }
2543            }
2544
2545            final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
2546            synchronized(bstats) {
2547                synchronized(mPidsSelfLocked) {
2548                    if (haveNewCpuStats) {
2549                        if (bstats.startAddingCpuLocked()) {
2550                            int totalUTime = 0;
2551                            int totalSTime = 0;
2552                            final int N = mProcessCpuTracker.countStats();
2553                            for (int i=0; i<N; i++) {
2554                                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
2555                                if (!st.working) {
2556                                    continue;
2557                                }
2558                                ProcessRecord pr = mPidsSelfLocked.get(st.pid);
2559                                totalUTime += st.rel_utime;
2560                                totalSTime += st.rel_stime;
2561                                if (pr != null) {
2562                                    BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
2563                                    if (ps == null || !ps.isActive()) {
2564                                        pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
2565                                                pr.info.uid, pr.processName);
2566                                    }
2567                                    ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2568                                    pr.curCpuTime += st.rel_utime + st.rel_stime;
2569                                } else {
2570                                    BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
2571                                    if (ps == null || !ps.isActive()) {
2572                                        st.batteryStats = ps = bstats.getProcessStatsLocked(
2573                                                bstats.mapUid(st.uid), st.name);
2574                                    }
2575                                    ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2576                                }
2577                            }
2578                            final int userTime = mProcessCpuTracker.getLastUserTime();
2579                            final int systemTime = mProcessCpuTracker.getLastSystemTime();
2580                            final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime();
2581                            final int irqTime = mProcessCpuTracker.getLastIrqTime();
2582                            final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime();
2583                            final int idleTime = mProcessCpuTracker.getLastIdleTime();
2584                            bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime,
2585                                    systemTime, iowaitTime, irqTime, softIrqTime, idleTime);
2586                        }
2587                    }
2588                }
2589
2590                if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2591                    mLastWriteTime = now;
2592                    mBatteryStatsService.scheduleWriteToDisk();
2593                }
2594            }
2595        }
2596    }
2597
2598    @Override
2599    public void batteryNeedsCpuUpdate() {
2600        updateCpuStatsNow();
2601    }
2602
2603    @Override
2604    public void batteryPowerChanged(boolean onBattery) {
2605        // When plugging in, update the CPU stats first before changing
2606        // the plug state.
2607        updateCpuStatsNow();
2608        synchronized (this) {
2609            synchronized(mPidsSelfLocked) {
2610                mOnBattery = DEBUG_POWER ? true : onBattery;
2611            }
2612        }
2613    }
2614
2615    @Override
2616    public void batterySendBroadcast(Intent intent) {
2617        broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
2618                AppOpsManager.OP_NONE, null, false, false,
2619                -1, Process.SYSTEM_UID, UserHandle.USER_ALL);
2620    }
2621
2622    /**
2623     * Initialize the application bind args. These are passed to each
2624     * process when the bindApplication() IPC is sent to the process. They're
2625     * lazily setup to make sure the services are running when they're asked for.
2626     */
2627    private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
2628        if (mAppBindArgs == null) {
2629            mAppBindArgs = new HashMap<>();
2630
2631            // Isolated processes won't get this optimization, so that we don't
2632            // violate the rules about which services they have access to.
2633            if (!isolated) {
2634                // Setup the application init args
2635                mAppBindArgs.put("package", ServiceManager.getService("package"));
2636                mAppBindArgs.put("window", ServiceManager.getService("window"));
2637                mAppBindArgs.put(Context.ALARM_SERVICE,
2638                        ServiceManager.getService(Context.ALARM_SERVICE));
2639            }
2640        }
2641        return mAppBindArgs;
2642    }
2643
2644    final void setFocusedActivityLocked(ActivityRecord r, String reason) {
2645        if (r != null && mFocusedActivity != r) {
2646            if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedActivityLocked: r=" + r);
2647            ActivityRecord last = mFocusedActivity;
2648            mFocusedActivity = r;
2649            if (r.task.taskType != ActivityRecord.HOME_ACTIVITY_TYPE
2650                    && r.task.taskType != ActivityRecord.RECENTS_ACTIVITY_TYPE) {
2651                if (mCurAppTimeTracker != r.appTimeTracker) {
2652                    // We are switching app tracking.  Complete the current one.
2653                    if (mCurAppTimeTracker != null) {
2654                        mCurAppTimeTracker.stop();
2655                        mHandler.obtainMessage(REPORT_TIME_TRACKER_MSG,
2656                                mCurAppTimeTracker).sendToTarget();
2657                        mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
2658                        mCurAppTimeTracker = null;
2659                    }
2660                    if (r.appTimeTracker != null) {
2661                        mCurAppTimeTracker = r.appTimeTracker;
2662                        startTimeTrackingFocusedActivityLocked();
2663                    }
2664                } else {
2665                    startTimeTrackingFocusedActivityLocked();
2666                }
2667            } else {
2668                r.appTimeTracker = null;
2669            }
2670            if (r.task != null && r.task.voiceInteractor != null) {
2671                startRunningVoiceLocked(r.task.voiceSession, r.info.applicationInfo.uid);
2672            } else {
2673                finishRunningVoiceLocked();
2674                if (last != null && last.task.voiceSession != null) {
2675                    // We had been in a voice interaction session, but now focused has
2676                    // move to something different.  Just finish the session, we can't
2677                    // return to it and retain the proper state and synchronization with
2678                    // the voice interaction service.
2679                    finishVoiceTask(last.task.voiceSession);
2680                }
2681            }
2682            if (mStackSupervisor.setFocusedStack(r, reason + " setFocusedActivity")) {
2683                mWindowManager.setFocusedApp(r.appToken, true);
2684            }
2685            applyUpdateLockStateLocked(r);
2686            if (mFocusedActivity.userId != mLastFocusedUserId) {
2687                mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG);
2688                mHandler.sendMessage(mHandler.obtainMessage(FOREGROUND_PROFILE_CHANGED_MSG,
2689                        mFocusedActivity.userId, 0));
2690                mLastFocusedUserId = mFocusedActivity.userId;
2691            }
2692        }
2693        EventLog.writeEvent(EventLogTags.AM_FOCUSED_ACTIVITY,
2694                mFocusedActivity == null ? -1 : mFocusedActivity.userId,
2695                mFocusedActivity == null ? "NULL" : mFocusedActivity.shortComponentName);
2696    }
2697
2698    final void clearFocusedActivity(ActivityRecord r) {
2699        if (mFocusedActivity == r) {
2700            ActivityStack stack = mStackSupervisor.getFocusedStack();
2701            if (stack != null) {
2702                ActivityRecord top = stack.topActivity();
2703                if (top != null && top.userId != mLastFocusedUserId) {
2704                    mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG);
2705                    mHandler.sendMessage(mHandler.obtainMessage(FOREGROUND_PROFILE_CHANGED_MSG,
2706                                    top.userId, 0));
2707                    mLastFocusedUserId = top.userId;
2708                }
2709            }
2710            mFocusedActivity = null;
2711            EventLog.writeEvent(EventLogTags.AM_FOCUSED_ACTIVITY, -1, "NULL");
2712        }
2713    }
2714
2715    @Override
2716    public void setFocusedStack(int stackId) {
2717        if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2718        synchronized (ActivityManagerService.this) {
2719            ActivityStack stack = mStackSupervisor.getStack(stackId);
2720            if (stack != null) {
2721                ActivityRecord r = stack.topRunningActivityLocked(null);
2722                if (r != null) {
2723                    setFocusedActivityLocked(r, "setFocusedStack");
2724                    mStackSupervisor.resumeTopActivitiesLocked(stack, null, null);
2725                }
2726            }
2727        }
2728    }
2729
2730    /** Sets the task stack listener that gets callbacks when a task stack changes. */
2731    @Override
2732    public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException {
2733        synchronized (ActivityManagerService.this) {
2734            if (listener != null) {
2735                mTaskStackListeners.register(listener);
2736            }
2737        }
2738    }
2739
2740    @Override
2741    public void notifyActivityDrawn(IBinder token) {
2742        if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2743        synchronized (this) {
2744            ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
2745            if (r != null) {
2746                r.task.stack.notifyActivityDrawnLocked(r);
2747            }
2748        }
2749    }
2750
2751    final void applyUpdateLockStateLocked(ActivityRecord r) {
2752        // Modifications to the UpdateLock state are done on our handler, outside
2753        // the activity manager's locks.  The new state is determined based on the
2754        // state *now* of the relevant activity record.  The object is passed to
2755        // the handler solely for logging detail, not to be consulted/modified.
2756        final boolean nextState = r != null && r.immersive;
2757        mHandler.sendMessage(
2758                mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
2759    }
2760
2761    final void showAskCompatModeDialogLocked(ActivityRecord r) {
2762        Message msg = Message.obtain();
2763        msg.what = SHOW_COMPAT_MODE_DIALOG_MSG;
2764        msg.obj = r.task.askedCompatMode ? null : r;
2765        mUiHandler.sendMessage(msg);
2766    }
2767
2768    private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index,
2769            String what, Object obj, ProcessRecord srcApp) {
2770        app.lastActivityTime = now;
2771
2772        if (app.activities.size() > 0) {
2773            // Don't want to touch dependent processes that are hosting activities.
2774            return index;
2775        }
2776
2777        int lrui = mLruProcesses.lastIndexOf(app);
2778        if (lrui < 0) {
2779            Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: "
2780                    + what + " " + obj + " from " + srcApp);
2781            return index;
2782        }
2783
2784        if (lrui >= index) {
2785            // Don't want to cause this to move dependent processes *back* in the
2786            // list as if they were less frequently used.
2787            return index;
2788        }
2789
2790        if (lrui >= mLruProcessActivityStart) {
2791            // Don't want to touch dependent processes that are hosting activities.
2792            return index;
2793        }
2794
2795        mLruProcesses.remove(lrui);
2796        if (index > 0) {
2797            index--;
2798        }
2799        if (DEBUG_LRU) Slog.d(TAG_LRU, "Moving dep from " + lrui + " to " + index
2800                + " in LRU list: " + app);
2801        mLruProcesses.add(index, app);
2802        return index;
2803    }
2804
2805    private static void killProcessGroup(int uid, int pid) {
2806        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup");
2807        Process.killProcessGroup(uid, pid);
2808        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2809    }
2810
2811    final void removeLruProcessLocked(ProcessRecord app) {
2812        int lrui = mLruProcesses.lastIndexOf(app);
2813        if (lrui >= 0) {
2814            if (!app.killed) {
2815                Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app);
2816                Process.killProcessQuiet(app.pid);
2817                killProcessGroup(app.info.uid, app.pid);
2818            }
2819            if (lrui <= mLruProcessActivityStart) {
2820                mLruProcessActivityStart--;
2821            }
2822            if (lrui <= mLruProcessServiceStart) {
2823                mLruProcessServiceStart--;
2824            }
2825            mLruProcesses.remove(lrui);
2826        }
2827    }
2828
2829    final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2830            ProcessRecord client) {
2831        final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities
2832                || app.treatLikeActivity;
2833        final boolean hasService = false; // not impl yet. app.services.size() > 0;
2834        if (!activityChange && hasActivity) {
2835            // The process has activities, so we are only allowing activity-based adjustments
2836            // to move it.  It should be kept in the front of the list with other
2837            // processes that have activities, and we don't want those to change their
2838            // order except due to activity operations.
2839            return;
2840        }
2841
2842        mLruSeq++;
2843        final long now = SystemClock.uptimeMillis();
2844        app.lastActivityTime = now;
2845
2846        // First a quick reject: if the app is already at the position we will
2847        // put it, then there is nothing to do.
2848        if (hasActivity) {
2849            final int N = mLruProcesses.size();
2850            if (N > 0 && mLruProcesses.get(N-1) == app) {
2851                if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top activity: " + app);
2852                return;
2853            }
2854        } else {
2855            if (mLruProcessServiceStart > 0
2856                    && mLruProcesses.get(mLruProcessServiceStart-1) == app) {
2857                if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top other: " + app);
2858                return;
2859            }
2860        }
2861
2862        int lrui = mLruProcesses.lastIndexOf(app);
2863
2864        if (app.persistent && lrui >= 0) {
2865            // We don't care about the position of persistent processes, as long as
2866            // they are in the list.
2867            if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, persistent: " + app);
2868            return;
2869        }
2870
2871        /* In progress: compute new position first, so we can avoid doing work
2872           if the process is not actually going to move.  Not yet working.
2873        int addIndex;
2874        int nextIndex;
2875        boolean inActivity = false, inService = false;
2876        if (hasActivity) {
2877            // Process has activities, put it at the very tipsy-top.
2878            addIndex = mLruProcesses.size();
2879            nextIndex = mLruProcessServiceStart;
2880            inActivity = true;
2881        } else if (hasService) {
2882            // Process has services, put it at the top of the service list.
2883            addIndex = mLruProcessActivityStart;
2884            nextIndex = mLruProcessServiceStart;
2885            inActivity = true;
2886            inService = true;
2887        } else  {
2888            // Process not otherwise of interest, it goes to the top of the non-service area.
2889            addIndex = mLruProcessServiceStart;
2890            if (client != null) {
2891                int clientIndex = mLruProcesses.lastIndexOf(client);
2892                if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating "
2893                        + app);
2894                if (clientIndex >= 0 && addIndex > clientIndex) {
2895                    addIndex = clientIndex;
2896                }
2897            }
2898            nextIndex = addIndex > 0 ? addIndex-1 : addIndex;
2899        }
2900
2901        Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act="
2902                + mLruProcessActivityStart + "): " + app);
2903        */
2904
2905        if (lrui >= 0) {
2906            if (lrui < mLruProcessActivityStart) {
2907                mLruProcessActivityStart--;
2908            }
2909            if (lrui < mLruProcessServiceStart) {
2910                mLruProcessServiceStart--;
2911            }
2912            /*
2913            if (addIndex > lrui) {
2914                addIndex--;
2915            }
2916            if (nextIndex > lrui) {
2917                nextIndex--;
2918            }
2919            */
2920            mLruProcesses.remove(lrui);
2921        }
2922
2923        /*
2924        mLruProcesses.add(addIndex, app);
2925        if (inActivity) {
2926            mLruProcessActivityStart++;
2927        }
2928        if (inService) {
2929            mLruProcessActivityStart++;
2930        }
2931        */
2932
2933        int nextIndex;
2934        if (hasActivity) {
2935            final int N = mLruProcesses.size();
2936            if (app.activities.size() == 0 && mLruProcessActivityStart < (N - 1)) {
2937                // Process doesn't have activities, but has clients with
2938                // activities...  move it up, but one below the top (the top
2939                // should always have a real activity).
2940                if (DEBUG_LRU) Slog.d(TAG_LRU,
2941                        "Adding to second-top of LRU activity list: " + app);
2942                mLruProcesses.add(N - 1, app);
2943                // To keep it from spamming the LRU list (by making a bunch of clients),
2944                // we will push down any other entries owned by the app.
2945                final int uid = app.info.uid;
2946                for (int i = N - 2; i > mLruProcessActivityStart; i--) {
2947                    ProcessRecord subProc = mLruProcesses.get(i);
2948                    if (subProc.info.uid == uid) {
2949                        // We want to push this one down the list.  If the process after
2950                        // it is for the same uid, however, don't do so, because we don't
2951                        // want them internally to be re-ordered.
2952                        if (mLruProcesses.get(i - 1).info.uid != uid) {
2953                            if (DEBUG_LRU) Slog.d(TAG_LRU,
2954                                    "Pushing uid " + uid + " swapping at " + i + ": "
2955                                    + mLruProcesses.get(i) + " : " + mLruProcesses.get(i - 1));
2956                            ProcessRecord tmp = mLruProcesses.get(i);
2957                            mLruProcesses.set(i, mLruProcesses.get(i - 1));
2958                            mLruProcesses.set(i - 1, tmp);
2959                            i--;
2960                        }
2961                    } else {
2962                        // A gap, we can stop here.
2963                        break;
2964                    }
2965                }
2966            } else {
2967                // Process has activities, put it at the very tipsy-top.
2968                if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU activity list: " + app);
2969                mLruProcesses.add(app);
2970            }
2971            nextIndex = mLruProcessServiceStart;
2972        } else if (hasService) {
2973            // Process has services, put it at the top of the service list.
2974            if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU service list: " + app);
2975            mLruProcesses.add(mLruProcessActivityStart, app);
2976            nextIndex = mLruProcessServiceStart;
2977            mLruProcessActivityStart++;
2978        } else  {
2979            // Process not otherwise of interest, it goes to the top of the non-service area.
2980            int index = mLruProcessServiceStart;
2981            if (client != null) {
2982                // If there is a client, don't allow the process to be moved up higher
2983                // in the list than that client.
2984                int clientIndex = mLruProcesses.lastIndexOf(client);
2985                if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG_LRU, "Unknown client " + client
2986                        + " when updating " + app);
2987                if (clientIndex <= lrui) {
2988                    // Don't allow the client index restriction to push it down farther in the
2989                    // list than it already is.
2990                    clientIndex = lrui;
2991                }
2992                if (clientIndex >= 0 && index > clientIndex) {
2993                    index = clientIndex;
2994                }
2995            }
2996            if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding at " + index + " of LRU list: " + app);
2997            mLruProcesses.add(index, app);
2998            nextIndex = index-1;
2999            mLruProcessActivityStart++;
3000            mLruProcessServiceStart++;
3001        }
3002
3003        // If the app is currently using a content provider or service,
3004        // bump those processes as well.
3005        for (int j=app.connections.size()-1; j>=0; j--) {
3006            ConnectionRecord cr = app.connections.valueAt(j);
3007            if (cr.binding != null && !cr.serviceDead && cr.binding.service != null
3008                    && cr.binding.service.app != null
3009                    && cr.binding.service.app.lruSeq != mLruSeq
3010                    && !cr.binding.service.app.persistent) {
3011                nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex,
3012                        "service connection", cr, app);
3013            }
3014        }
3015        for (int j=app.conProviders.size()-1; j>=0; j--) {
3016            ContentProviderRecord cpr = app.conProviders.get(j).provider;
3017            if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) {
3018                nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex,
3019                        "provider reference", cpr, app);
3020            }
3021        }
3022    }
3023
3024    final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
3025        if (uid == Process.SYSTEM_UID) {
3026            // The system gets to run in any process.  If there are multiple
3027            // processes with the same uid, just pick the first (this
3028            // should never happen).
3029            SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName);
3030            if (procs == null) return null;
3031            final int procCount = procs.size();
3032            for (int i = 0; i < procCount; i++) {
3033                final int procUid = procs.keyAt(i);
3034                if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
3035                    // Don't use an app process or different user process for system component.
3036                    continue;
3037                }
3038                return procs.valueAt(i);
3039            }
3040        }
3041        ProcessRecord proc = mProcessNames.get(processName, uid);
3042        if (false && proc != null && !keepIfLarge
3043                && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY
3044                && proc.lastCachedPss >= 4000) {
3045            // Turn this condition on to cause killing to happen regularly, for testing.
3046            if (proc.baseProcessTracker != null) {
3047                proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
3048            }
3049            proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
3050        } else if (proc != null && !keepIfLarge
3051                && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
3052                && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
3053            if (DEBUG_PSS) Slog.d(TAG_PSS, "May not keep " + proc + ": pss=" + proc.lastCachedPss);
3054            if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) {
3055                if (proc.baseProcessTracker != null) {
3056                    proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
3057                }
3058                proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
3059            }
3060        }
3061        return proc;
3062    }
3063
3064    void ensurePackageDexOpt(String packageName) {
3065        IPackageManager pm = AppGlobals.getPackageManager();
3066        try {
3067            if (pm.performDexOptIfNeeded(packageName, null /* instruction set */)) {
3068                mDidDexOpt = true;
3069            }
3070        } catch (RemoteException e) {
3071        }
3072    }
3073
3074    boolean isNextTransitionForward() {
3075        int transit = mWindowManager.getPendingAppTransition();
3076        return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
3077                || transit == AppTransition.TRANSIT_TASK_OPEN
3078                || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
3079    }
3080
3081    int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
3082            String processName, String abiOverride, int uid, Runnable crashHandler) {
3083        synchronized(this) {
3084            ApplicationInfo info = new ApplicationInfo();
3085            // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
3086            // For isolated processes, the former contains the parent's uid and the latter the
3087            // actual uid of the isolated process.
3088            // In the special case introduced by this method (which is, starting an isolated
3089            // process directly from the SystemServer without an actual parent app process) the
3090            // closest thing to a parent's uid is SYSTEM_UID.
3091            // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
3092            // the |isolated| logic in the ProcessRecord constructor.
3093            info.uid = Process.SYSTEM_UID;
3094            info.processName = processName;
3095            info.className = entryPoint;
3096            info.packageName = "android";
3097            ProcessRecord proc = startProcessLocked(processName, info /* info */,
3098                    false /* knownToBeDead */, 0 /* intentFlags */, ""  /* hostingType */,
3099                    null /* hostingName */, true /* allowWhileBooting */, true /* isolated */,
3100                    uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
3101                    crashHandler);
3102            return proc != null ? proc.pid : 0;
3103        }
3104    }
3105
3106    final ProcessRecord startProcessLocked(String processName,
3107            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
3108            String hostingType, ComponentName hostingName, boolean allowWhileBooting,
3109            boolean isolated, boolean keepIfLarge) {
3110        return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
3111                hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
3112                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
3113                null /* crashHandler */);
3114    }
3115
3116    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
3117            boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
3118            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
3119            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
3120        long startTime = SystemClock.elapsedRealtime();
3121        ProcessRecord app;
3122        if (!isolated) {
3123            app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
3124            checkTime(startTime, "startProcess: after getProcessRecord");
3125
3126            if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) {
3127                // If we are in the background, then check to see if this process
3128                // is bad.  If so, we will just silently fail.
3129                if (mBadProcesses.get(info.processName, info.uid) != null) {
3130                    if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
3131                            + "/" + info.processName);
3132                    return null;
3133                }
3134            } else {
3135                // When the user is explicitly starting a process, then clear its
3136                // crash count so that we won't make it bad until they see at
3137                // least one crash dialog again, and make the process good again
3138                // if it had been bad.
3139                if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
3140                        + "/" + info.processName);
3141                mProcessCrashTimes.remove(info.processName, info.uid);
3142                if (mBadProcesses.get(info.processName, info.uid) != null) {
3143                    EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
3144                            UserHandle.getUserId(info.uid), info.uid,
3145                            info.processName);
3146                    mBadProcesses.remove(info.processName, info.uid);
3147                    if (app != null) {
3148                        app.bad = false;
3149                    }
3150                }
3151            }
3152        } else {
3153            // If this is an isolated process, it can't re-use an existing process.
3154            app = null;
3155        }
3156
3157        // app launch boost for big.little configurations
3158        // use cpusets to migrate freshly launched tasks to big cores
3159        synchronized(ActivityManagerService.this) {
3160            nativeMigrateToBoost();
3161            mIsBoosted = true;
3162            mBoostStartTime = SystemClock.uptimeMillis();
3163            Message msg = mHandler.obtainMessage(APP_BOOST_DEACTIVATE_MSG);
3164            mHandler.sendMessageDelayed(msg, APP_BOOST_MESSAGE_DELAY);
3165        }
3166
3167        // We don't have to do anything more if:
3168        // (1) There is an existing application record; and
3169        // (2) The caller doesn't think it is dead, OR there is no thread
3170        //     object attached to it so we know it couldn't have crashed; and
3171        // (3) There is a pid assigned to it, so it is either starting or
3172        //     already running.
3173        if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName
3174                + " app=" + app + " knownToBeDead=" + knownToBeDead
3175                + " thread=" + (app != null ? app.thread : null)
3176                + " pid=" + (app != null ? app.pid : -1));
3177        if (app != null && app.pid > 0) {
3178            if (!knownToBeDead || app.thread == null) {
3179                // We already have the app running, or are waiting for it to
3180                // come up (we have a pid but not yet its thread), so keep it.
3181                if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app);
3182                // If this is a new package in the process, add the package to the list
3183                app.addPackage(info.packageName, info.versionCode, mProcessStats);
3184                checkTime(startTime, "startProcess: done, added package to proc");
3185                return app;
3186            }
3187
3188            // An application record is attached to a previous process,
3189            // clean it up now.
3190            if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_PROCESSES, "App died: " + app);
3191            checkTime(startTime, "startProcess: bad proc running, killing");
3192            killProcessGroup(app.info.uid, app.pid);
3193            handleAppDiedLocked(app, true, true);
3194            checkTime(startTime, "startProcess: done killing old proc");
3195        }
3196
3197        String hostingNameStr = hostingName != null
3198                ? hostingName.flattenToShortString() : null;
3199
3200        if (app == null) {
3201            checkTime(startTime, "startProcess: creating new process record");
3202            app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
3203            if (app == null) {
3204                Slog.w(TAG, "Failed making new process record for "
3205                        + processName + "/" + info.uid + " isolated=" + isolated);
3206                return null;
3207            }
3208            app.crashHandler = crashHandler;
3209            checkTime(startTime, "startProcess: done creating new process record");
3210        } else {
3211            // If this is a new package in the process, add the package to the list
3212            app.addPackage(info.packageName, info.versionCode, mProcessStats);
3213            checkTime(startTime, "startProcess: added package to existing proc");
3214        }
3215
3216        // If the system is not ready yet, then hold off on starting this
3217        // process until it is.
3218        if (!mProcessesReady
3219                && !isAllowedWhileBooting(info)
3220                && !allowWhileBooting) {
3221            if (!mProcessesOnHold.contains(app)) {
3222                mProcessesOnHold.add(app);
3223            }
3224            if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES,
3225                    "System not ready, putting on hold: " + app);
3226            checkTime(startTime, "startProcess: returning with proc on hold");
3227            return app;
3228        }
3229
3230        checkTime(startTime, "startProcess: stepping in to startProcess");
3231        startProcessLocked(
3232                app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
3233        checkTime(startTime, "startProcess: done starting proc!");
3234        return (app.pid != 0) ? app : null;
3235    }
3236
3237    boolean isAllowedWhileBooting(ApplicationInfo ai) {
3238        return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
3239    }
3240
3241    private final void startProcessLocked(ProcessRecord app,
3242            String hostingType, String hostingNameStr) {
3243        startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */,
3244                null /* entryPoint */, null /* entryPointArgs */);
3245    }
3246
3247    private final void startProcessLocked(ProcessRecord app, String hostingType,
3248            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
3249        long startTime = SystemClock.elapsedRealtime();
3250        if (app.pid > 0 && app.pid != MY_PID) {
3251            checkTime(startTime, "startProcess: removing from pids map");
3252            synchronized (mPidsSelfLocked) {
3253                mPidsSelfLocked.remove(app.pid);
3254                mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3255            }
3256            checkTime(startTime, "startProcess: done removing from pids map");
3257            app.setPid(0);
3258        }
3259
3260        if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
3261                "startProcessLocked removing on hold: " + app);
3262        mProcessesOnHold.remove(app);
3263
3264        checkTime(startTime, "startProcess: starting to update cpu stats");
3265        updateCpuStats();
3266        checkTime(startTime, "startProcess: done updating cpu stats");
3267
3268        try {
3269            try {
3270                if (AppGlobals.getPackageManager().isPackageFrozen(app.info.packageName)) {
3271                    // This is caught below as if we had failed to fork zygote
3272                    throw new RuntimeException("Package " + app.info.packageName + " is frozen!");
3273                }
3274            } catch (RemoteException e) {
3275                throw e.rethrowAsRuntimeException();
3276            }
3277
3278            int uid = app.uid;
3279            int[] gids = null;
3280            int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
3281            if (!app.isolated) {
3282                int[] permGids = null;
3283                try {
3284                    checkTime(startTime, "startProcess: getting gids from package manager");
3285                    final IPackageManager pm = AppGlobals.getPackageManager();
3286                    permGids = pm.getPackageGids(app.info.packageName, app.userId);
3287                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3288                            MountServiceInternal.class);
3289                    mountExternal = mountServiceInternal.getExternalStorageMountMode(uid,
3290                            app.info.packageName);
3291                } catch (RemoteException e) {
3292                    throw e.rethrowAsRuntimeException();
3293                }
3294
3295                /*
3296                 * Add shared application and profile GIDs so applications can share some
3297                 * resources like shared libraries and access user-wide resources
3298                 */
3299                if (ArrayUtils.isEmpty(permGids)) {
3300                    gids = new int[2];
3301                } else {
3302                    gids = new int[permGids.length + 2];
3303                    System.arraycopy(permGids, 0, gids, 2, permGids.length);
3304                }
3305                gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
3306                gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));
3307            }
3308            checkTime(startTime, "startProcess: building args");
3309            if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) {
3310                if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3311                        && mTopComponent != null
3312                        && app.processName.equals(mTopComponent.getPackageName())) {
3313                    uid = 0;
3314                }
3315                if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL
3316                        && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
3317                    uid = 0;
3318                }
3319            }
3320            int debugFlags = 0;
3321            if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3322                debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
3323                // Also turn on CheckJNI for debuggable apps. It's quite
3324                // awkward to turn on otherwise.
3325                debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3326            }
3327            // Run the app in safe mode if its manifest requests so or the
3328            // system is booted in safe mode.
3329            if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
3330                mSafeMode == true) {
3331                debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
3332            }
3333            if ("1".equals(SystemProperties.get("debug.checkjni"))) {
3334                debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3335            }
3336            String jitDebugProperty = SystemProperties.get("debug.usejit");
3337            if ("true".equals(jitDebugProperty)) {
3338                debugFlags |= Zygote.DEBUG_ENABLE_JIT;
3339            } else if (!"false".equals(jitDebugProperty)) {
3340                // If we didn't force disable by setting false, defer to the dalvik vm options.
3341                if ("true".equals(SystemProperties.get("dalvik.vm.usejit"))) {
3342                    debugFlags |= Zygote.DEBUG_ENABLE_JIT;
3343                }
3344            }
3345            String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info");
3346            if ("true".equals(genDebugInfoProperty)) {
3347                debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO;
3348            }
3349            if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
3350                debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
3351            }
3352            if ("1".equals(SystemProperties.get("debug.assert"))) {
3353                debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
3354            }
3355
3356            String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
3357            if (requiredAbi == null) {
3358                requiredAbi = Build.SUPPORTED_ABIS[0];
3359            }
3360
3361            String instructionSet = null;
3362            if (app.info.primaryCpuAbi != null) {
3363                instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
3364            }
3365
3366            app.gids = gids;
3367            app.requiredAbi = requiredAbi;
3368            app.instructionSet = instructionSet;
3369
3370            // Start the process.  It will either succeed and return a result containing
3371            // the PID of the new process, or else throw a RuntimeException.
3372            boolean isActivityProcess = (entryPoint == null);
3373            if (entryPoint == null) entryPoint = "android.app.ActivityThread";
3374            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
3375                    app.processName);
3376            checkTime(startTime, "startProcess: asking zygote to start proc");
3377            Process.ProcessStartResult startResult = Process.start(entryPoint,
3378                    app.processName, uid, uid, gids, debugFlags, mountExternal,
3379                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
3380                    app.info.dataDir, entryPointArgs);
3381            checkTime(startTime, "startProcess: returned from zygote!");
3382            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
3383
3384            if (app.isolated) {
3385                mBatteryStatsService.addIsolatedUid(app.uid, app.info.uid);
3386            }
3387            mBatteryStatsService.noteProcessStart(app.processName, app.info.uid);
3388            checkTime(startTime, "startProcess: done updating battery stats");
3389
3390            EventLog.writeEvent(EventLogTags.AM_PROC_START,
3391                    UserHandle.getUserId(uid), startResult.pid, uid,
3392                    app.processName, hostingType,
3393                    hostingNameStr != null ? hostingNameStr : "");
3394
3395            if (app.persistent) {
3396                Watchdog.getInstance().processStarted(app.processName, startResult.pid);
3397            }
3398
3399            checkTime(startTime, "startProcess: building log message");
3400            StringBuilder buf = mStringBuilder;
3401            buf.setLength(0);
3402            buf.append("Start proc ");
3403            buf.append(startResult.pid);
3404            buf.append(':');
3405            buf.append(app.processName);
3406            buf.append('/');
3407            UserHandle.formatUid(buf, uid);
3408            if (!isActivityProcess) {
3409                buf.append(" [");
3410                buf.append(entryPoint);
3411                buf.append("]");
3412            }
3413            buf.append(" for ");
3414            buf.append(hostingType);
3415            if (hostingNameStr != null) {
3416                buf.append(" ");
3417                buf.append(hostingNameStr);
3418            }
3419            Slog.i(TAG, buf.toString());
3420            app.setPid(startResult.pid);
3421            app.usingWrapper = startResult.usingWrapper;
3422            app.removed = false;
3423            app.killed = false;
3424            app.killedByAm = false;
3425            checkTime(startTime, "startProcess: starting to update pids map");
3426            synchronized (mPidsSelfLocked) {
3427                this.mPidsSelfLocked.put(startResult.pid, app);
3428                if (isActivityProcess) {
3429                    Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
3430                    msg.obj = app;
3431                    mHandler.sendMessageDelayed(msg, startResult.usingWrapper
3432                            ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
3433                }
3434            }
3435            checkTime(startTime, "startProcess: done updating pids map");
3436        } catch (RuntimeException e) {
3437            // XXX do better error recovery.
3438            app.setPid(0);
3439            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
3440            if (app.isolated) {
3441                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
3442            }
3443            Slog.e(TAG, "Failure starting process " + app.processName, e);
3444        }
3445    }
3446
3447    void updateUsageStats(ActivityRecord component, boolean resumed) {
3448        if (DEBUG_SWITCH) Slog.d(TAG_SWITCH,
3449                "updateUsageStats: comp=" + component + "res=" + resumed);
3450        final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3451        if (resumed) {
3452            if (mUsageStatsService != null) {
3453                mUsageStatsService.reportEvent(component.realActivity, component.userId,
3454                        UsageEvents.Event.MOVE_TO_FOREGROUND);
3455            }
3456            synchronized (stats) {
3457                stats.noteActivityResumedLocked(component.app.uid);
3458            }
3459        } else {
3460            if (mUsageStatsService != null) {
3461                mUsageStatsService.reportEvent(component.realActivity, component.userId,
3462                        UsageEvents.Event.MOVE_TO_BACKGROUND);
3463            }
3464            synchronized (stats) {
3465                stats.noteActivityPausedLocked(component.app.uid);
3466            }
3467        }
3468    }
3469
3470    Intent getHomeIntent() {
3471        Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
3472        intent.setComponent(mTopComponent);
3473        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
3474            intent.addCategory(Intent.CATEGORY_HOME);
3475        }
3476        return intent;
3477    }
3478
3479    boolean startHomeActivityLocked(int userId, String reason) {
3480        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3481                && mTopAction == null) {
3482            // We are running in factory test mode, but unable to find
3483            // the factory test app, so just sit around displaying the
3484            // error message and don't try to start anything.
3485            return false;
3486        }
3487        Intent intent = getHomeIntent();
3488        ActivityInfo aInfo =
3489            resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
3490        if (aInfo != null) {
3491            intent.setComponent(new ComponentName(
3492                    aInfo.applicationInfo.packageName, aInfo.name));
3493            // Don't do this if the home app is currently being
3494            // instrumented.
3495            aInfo = new ActivityInfo(aInfo);
3496            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
3497            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
3498                    aInfo.applicationInfo.uid, true);
3499            if (app == null || app.instrumentationClass == null) {
3500                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
3501                mStackSupervisor.startHomeActivity(intent, aInfo, reason);
3502            }
3503        }
3504
3505        return true;
3506    }
3507
3508    private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
3509        ActivityInfo ai = null;
3510        ComponentName comp = intent.getComponent();
3511        try {
3512            if (comp != null) {
3513                // Factory test.
3514                ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
3515            } else {
3516                ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
3517                        intent,
3518                        intent.resolveTypeIfNeeded(mContext.getContentResolver()),
3519                        flags, userId);
3520
3521                if (info != null) {
3522                    ai = info.activityInfo;
3523                }
3524            }
3525        } catch (RemoteException e) {
3526            // ignore
3527        }
3528
3529        return ai;
3530    }
3531
3532    /**
3533     * Starts the "new version setup screen" if appropriate.
3534     */
3535    void startSetupActivityLocked() {
3536        // Only do this once per boot.
3537        if (mCheckedForSetup) {
3538            return;
3539        }
3540
3541        // We will show this screen if the current one is a different
3542        // version than the last one shown, and we are not running in
3543        // low-level factory test mode.
3544        final ContentResolver resolver = mContext.getContentResolver();
3545        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL &&
3546                Settings.Global.getInt(resolver,
3547                        Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
3548            mCheckedForSetup = true;
3549
3550            // See if we should be showing the platform update setup UI.
3551            Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
3552            List<ResolveInfo> ris = mContext.getPackageManager()
3553                    .queryIntentActivities(intent, PackageManager.GET_META_DATA);
3554
3555            // We don't allow third party apps to replace this.
3556            ResolveInfo ri = null;
3557            for (int i=0; ris != null && i<ris.size(); i++) {
3558                if ((ris.get(i).activityInfo.applicationInfo.flags
3559                        & ApplicationInfo.FLAG_SYSTEM) != 0) {
3560                    ri = ris.get(i);
3561                    break;
3562                }
3563            }
3564
3565            if (ri != null) {
3566                String vers = ri.activityInfo.metaData != null
3567                        ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
3568                        : null;
3569                if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
3570                    vers = ri.activityInfo.applicationInfo.metaData.getString(
3571                            Intent.METADATA_SETUP_VERSION);
3572                }
3573                String lastVers = Settings.Secure.getString(
3574                        resolver, Settings.Secure.LAST_SETUP_SHOWN);
3575                if (vers != null && !vers.equals(lastVers)) {
3576                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3577                    intent.setComponent(new ComponentName(
3578                            ri.activityInfo.packageName, ri.activityInfo.name));
3579                    mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo,
3580                            null, null, null, null, 0, 0, 0, null, 0, 0, 0, null, false, false,
3581                            null, null, null);
3582                }
3583            }
3584        }
3585    }
3586
3587    CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
3588        return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
3589    }
3590
3591    void enforceNotIsolatedCaller(String caller) {
3592        if (UserHandle.isIsolated(Binder.getCallingUid())) {
3593            throw new SecurityException("Isolated process not allowed to call " + caller);
3594        }
3595    }
3596
3597    void enforceShellRestriction(String restriction, int userHandle) {
3598        if (Binder.getCallingUid() == Process.SHELL_UID) {
3599            if (userHandle < 0
3600                    || mUserManager.hasUserRestriction(restriction, userHandle)) {
3601                throw new SecurityException("Shell does not have permission to access user "
3602                        + userHandle);
3603            }
3604        }
3605    }
3606
3607    @Override
3608    public int getFrontActivityScreenCompatMode() {
3609        enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
3610        synchronized (this) {
3611            return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
3612        }
3613    }
3614
3615    @Override
3616    public void setFrontActivityScreenCompatMode(int mode) {
3617        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3618                "setFrontActivityScreenCompatMode");
3619        synchronized (this) {
3620            mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
3621        }
3622    }
3623
3624    @Override
3625    public int getPackageScreenCompatMode(String packageName) {
3626        enforceNotIsolatedCaller("getPackageScreenCompatMode");
3627        synchronized (this) {
3628            return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
3629        }
3630    }
3631
3632    @Override
3633    public void setPackageScreenCompatMode(String packageName, int mode) {
3634        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3635                "setPackageScreenCompatMode");
3636        synchronized (this) {
3637            mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
3638        }
3639    }
3640
3641    @Override
3642    public boolean getPackageAskScreenCompat(String packageName) {
3643        enforceNotIsolatedCaller("getPackageAskScreenCompat");
3644        synchronized (this) {
3645            return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
3646        }
3647    }
3648
3649    @Override
3650    public void setPackageAskScreenCompat(String packageName, boolean ask) {
3651        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3652                "setPackageAskScreenCompat");
3653        synchronized (this) {
3654            mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
3655        }
3656    }
3657
3658    private boolean hasUsageStatsPermission(String callingPackage) {
3659        final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_GET_USAGE_STATS,
3660                Binder.getCallingUid(), callingPackage);
3661        if (mode == AppOpsManager.MODE_DEFAULT) {
3662            return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3663                    == PackageManager.PERMISSION_GRANTED;
3664        }
3665        return mode == AppOpsManager.MODE_ALLOWED;
3666    }
3667
3668    @Override
3669    public int getPackageProcessState(String packageName, String callingPackage) {
3670        if (!hasUsageStatsPermission(callingPackage)) {
3671            enforceCallingPermission(android.Manifest.permission.GET_PACKAGE_IMPORTANCE,
3672                    "getPackageProcessState");
3673        }
3674
3675        int procState = ActivityManager.PROCESS_STATE_NONEXISTENT;
3676        synchronized (this) {
3677            for (int i=mLruProcesses.size()-1; i>=0; i--) {
3678                final ProcessRecord proc = mLruProcesses.get(i);
3679                if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT
3680                        || procState > proc.setProcState) {
3681                    boolean found = false;
3682                    for (int j=proc.pkgList.size()-1; j>=0 && !found; j--) {
3683                        if (proc.pkgList.keyAt(j).equals(packageName)) {
3684                            procState = proc.setProcState;
3685                            found = true;
3686                        }
3687                    }
3688                    if (proc.pkgDeps != null && !found) {
3689                        for (int j=proc.pkgDeps.size()-1; j>=0; j--) {
3690                            if (proc.pkgDeps.valueAt(j).equals(packageName)) {
3691                                procState = proc.setProcState;
3692                                break;
3693                            }
3694                        }
3695                    }
3696                }
3697            }
3698        }
3699        return procState;
3700    }
3701
3702    @Override
3703    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
3704        synchronized (this) {
3705            final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel");
3706            if (app == null) {
3707                return false;
3708            }
3709            if (app.trimMemoryLevel < level && app.thread != null &&
3710                    (level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
3711                            app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND)) {
3712                try {
3713                    app.thread.scheduleTrimMemory(level);
3714                    app.trimMemoryLevel = level;
3715                    return true;
3716                } catch (RemoteException e) {
3717                    // Fallthrough to failure case.
3718                }
3719            }
3720        }
3721        return false;
3722    }
3723
3724    private void dispatchProcessesChanged() {
3725        int N;
3726        synchronized (this) {
3727            N = mPendingProcessChanges.size();
3728            if (mActiveProcessChanges.length < N) {
3729                mActiveProcessChanges = new ProcessChangeItem[N];
3730            }
3731            mPendingProcessChanges.toArray(mActiveProcessChanges);
3732            mPendingProcessChanges.clear();
3733            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3734                    "*** Delivering " + N + " process changes");
3735        }
3736
3737        int i = mProcessObservers.beginBroadcast();
3738        while (i > 0) {
3739            i--;
3740            final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3741            if (observer != null) {
3742                try {
3743                    for (int j=0; j<N; j++) {
3744                        ProcessChangeItem item = mActiveProcessChanges[j];
3745                        if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
3746                            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3747                                    "ACTIVITIES CHANGED pid=" + item.pid + " uid="
3748                                    + item.uid + ": " + item.foregroundActivities);
3749                            observer.onForegroundActivitiesChanged(item.pid, item.uid,
3750                                    item.foregroundActivities);
3751                        }
3752                        if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) {
3753                            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3754                                    "PROCSTATE CHANGED pid=" + item.pid + " uid=" + item.uid
3755                                    + ": " + item.processState);
3756                            observer.onProcessStateChanged(item.pid, item.uid, item.processState);
3757                        }
3758                    }
3759                } catch (RemoteException e) {
3760                }
3761            }
3762        }
3763        mProcessObservers.finishBroadcast();
3764
3765        synchronized (this) {
3766            for (int j=0; j<N; j++) {
3767                mAvailProcessChanges.add(mActiveProcessChanges[j]);
3768            }
3769        }
3770    }
3771
3772    private void dispatchProcessDied(int pid, int uid) {
3773        int i = mProcessObservers.beginBroadcast();
3774        while (i > 0) {
3775            i--;
3776            final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3777            if (observer != null) {
3778                try {
3779                    observer.onProcessDied(pid, uid);
3780                } catch (RemoteException e) {
3781                }
3782            }
3783        }
3784        mProcessObservers.finishBroadcast();
3785    }
3786
3787    private void dispatchUidsChanged() {
3788        int N;
3789        synchronized (this) {
3790            N = mPendingUidChanges.size();
3791            if (mActiveUidChanges.length < N) {
3792                mActiveUidChanges = new UidRecord.ChangeItem[N];
3793            }
3794            for (int i=0; i<N; i++) {
3795                final UidRecord.ChangeItem change = mPendingUidChanges.get(i);
3796                mActiveUidChanges[i] = change;
3797                change.uidRecord.pendingChange = null;
3798                change.uidRecord = null;
3799            }
3800            mPendingUidChanges.clear();
3801            if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3802                    "*** Delivering " + N + " uid changes");
3803        }
3804
3805        if (mLocalPowerManager != null) {
3806            for (int j=0; j<N; j++) {
3807                UidRecord.ChangeItem item = mActiveUidChanges[j];
3808                if (item.gone) {
3809                    mLocalPowerManager.uidGone(item.uid);
3810                } else {
3811                    mLocalPowerManager.updateUidProcState(item.uid, item.processState);
3812                }
3813            }
3814        }
3815
3816        int i = mUidObservers.beginBroadcast();
3817        while (i > 0) {
3818            i--;
3819            final IUidObserver observer = mUidObservers.getBroadcastItem(i);
3820            if (observer != null) {
3821                try {
3822                    for (int j=0; j<N; j++) {
3823                        UidRecord.ChangeItem item = mActiveUidChanges[j];
3824                        if (item.gone) {
3825                            if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3826                                    "UID gone uid=" + item.uid);
3827                            observer.onUidGone(item.uid);
3828                        } else {
3829                            if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3830                                    "UID CHANGED uid=" + item.uid
3831                                    + ": " + item.processState);
3832                            observer.onUidStateChanged(item.uid, item.processState);
3833                        }
3834                    }
3835                } catch (RemoteException e) {
3836                }
3837            }
3838        }
3839        mUidObservers.finishBroadcast();
3840
3841        synchronized (this) {
3842            for (int j=0; j<N; j++) {
3843                mAvailUidChanges.add(mActiveUidChanges[j]);
3844            }
3845        }
3846    }
3847
3848    @Override
3849    public final int startActivity(IApplicationThread caller, String callingPackage,
3850            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3851            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
3852        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
3853            resultWho, requestCode, startFlags, profilerInfo, options,
3854            UserHandle.getCallingUserId());
3855    }
3856
3857    @Override
3858    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3859            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3860            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
3861        enforceNotIsolatedCaller("startActivity");
3862        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3863                false, ALLOW_FULL_ONLY, "startActivity", null);
3864        // TODO: Switch to user app stacks here.
3865        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
3866                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
3867                profilerInfo, null, null, options, false, userId, null, null);
3868    }
3869
3870    @Override
3871    public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
3872            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3873            int startFlags, ProfilerInfo profilerInfo, Bundle options, boolean ignoreTargetSecurity,
3874            int userId) {
3875
3876        // This is very dangerous -- it allows you to perform a start activity (including
3877        // permission grants) as any app that may launch one of your own activities.  So
3878        // we will only allow this to be done from activities that are part of the core framework,
3879        // and then only when they are running as the system.
3880        final ActivityRecord sourceRecord;
3881        final int targetUid;
3882        final String targetPackage;
3883        synchronized (this) {
3884            if (resultTo == null) {
3885                throw new SecurityException("Must be called from an activity");
3886            }
3887            sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
3888            if (sourceRecord == null) {
3889                throw new SecurityException("Called with bad activity token: " + resultTo);
3890            }
3891            if (!sourceRecord.info.packageName.equals("android")) {
3892                throw new SecurityException(
3893                        "Must be called from an activity that is declared in the android package");
3894            }
3895            if (sourceRecord.app == null) {
3896                throw new SecurityException("Called without a process attached to activity");
3897            }
3898            if (UserHandle.getAppId(sourceRecord.app.uid) != Process.SYSTEM_UID) {
3899                // This is still okay, as long as this activity is running under the
3900                // uid of the original calling activity.
3901                if (sourceRecord.app.uid != sourceRecord.launchedFromUid) {
3902                    throw new SecurityException(
3903                            "Calling activity in uid " + sourceRecord.app.uid
3904                                    + " must be system uid or original calling uid "
3905                                    + sourceRecord.launchedFromUid);
3906                }
3907            }
3908            if (ignoreTargetSecurity) {
3909                if (intent.getComponent() == null) {
3910                    throw new SecurityException(
3911                            "Component must be specified with ignoreTargetSecurity");
3912                }
3913                if (intent.getSelector() != null) {
3914                    throw new SecurityException(
3915                            "Selector not allowed with ignoreTargetSecurity");
3916                }
3917            }
3918            targetUid = sourceRecord.launchedFromUid;
3919            targetPackage = sourceRecord.launchedFromPackage;
3920        }
3921
3922        if (userId == UserHandle.USER_NULL) {
3923            userId = UserHandle.getUserId(sourceRecord.app.uid);
3924        }
3925
3926        // TODO: Switch to user app stacks here.
3927        try {
3928            int ret = mStackSupervisor.startActivityMayWait(null, targetUid, targetPackage, intent,
3929                    resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null,
3930                    null, null, options, ignoreTargetSecurity, userId, null, null);
3931            return ret;
3932        } catch (SecurityException e) {
3933            // XXX need to figure out how to propagate to original app.
3934            // A SecurityException here is generally actually a fault of the original
3935            // calling activity (such as a fairly granting permissions), so propagate it
3936            // back to them.
3937            /*
3938            StringBuilder msg = new StringBuilder();
3939            msg.append("While launching");
3940            msg.append(intent.toString());
3941            msg.append(": ");
3942            msg.append(e.getMessage());
3943            */
3944            throw e;
3945        }
3946    }
3947
3948    @Override
3949    public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3950            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3951            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
3952        enforceNotIsolatedCaller("startActivityAndWait");
3953        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3954                false, ALLOW_FULL_ONLY, "startActivityAndWait", null);
3955        WaitResult res = new WaitResult();
3956        // TODO: Switch to user app stacks here.
3957        mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
3958                null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null,
3959                options, false, userId, null, null);
3960        return res;
3961    }
3962
3963    @Override
3964    public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
3965            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3966            int startFlags, Configuration config, Bundle options, int userId) {
3967        enforceNotIsolatedCaller("startActivityWithConfig");
3968        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3969                false, ALLOW_FULL_ONLY, "startActivityWithConfig", null);
3970        // TODO: Switch to user app stacks here.
3971        int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
3972                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
3973                null, null, config, options, false, userId, null, null);
3974        return ret;
3975    }
3976
3977    @Override
3978    public int startActivityIntentSender(IApplicationThread caller, IntentSender intent,
3979            Intent fillInIntent, String resolvedType, IBinder resultTo, String resultWho,
3980            int requestCode, int flagsMask, int flagsValues, Bundle options)
3981            throws TransactionTooLargeException {
3982        enforceNotIsolatedCaller("startActivityIntentSender");
3983        // Refuse possible leaked file descriptors
3984        if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3985            throw new IllegalArgumentException("File descriptors passed in Intent");
3986        }
3987
3988        IIntentSender sender = intent.getTarget();
3989        if (!(sender instanceof PendingIntentRecord)) {
3990            throw new IllegalArgumentException("Bad PendingIntent object");
3991        }
3992
3993        PendingIntentRecord pir = (PendingIntentRecord)sender;
3994
3995        synchronized (this) {
3996            // If this is coming from the currently resumed activity, it is
3997            // effectively saying that app switches are allowed at this point.
3998            final ActivityStack stack = getFocusedStack();
3999            if (stack.mResumedActivity != null &&
4000                    stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
4001                mAppSwitchesAllowedTime = 0;
4002            }
4003        }
4004        int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
4005                resultTo, resultWho, requestCode, flagsMask, flagsValues, options, null);
4006        return ret;
4007    }
4008
4009    @Override
4010    public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
4011            Intent intent, String resolvedType, IVoiceInteractionSession session,
4012            IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
4013            Bundle options, int userId) {
4014        if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION)
4015                != PackageManager.PERMISSION_GRANTED) {
4016            String msg = "Permission Denial: startVoiceActivity() from pid="
4017                    + Binder.getCallingPid()
4018                    + ", uid=" + Binder.getCallingUid()
4019                    + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION;
4020            Slog.w(TAG, msg);
4021            throw new SecurityException(msg);
4022        }
4023        if (session == null || interactor == null) {
4024            throw new NullPointerException("null session or interactor");
4025        }
4026        userId = handleIncomingUser(callingPid, callingUid, userId,
4027                false, ALLOW_FULL_ONLY, "startVoiceActivity", null);
4028        // TODO: Switch to user app stacks here.
4029        return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent,
4030                resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null,
4031                null, options, false, userId, null, null);
4032    }
4033
4034    @Override
4035    public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
4036        synchronized (this) {
4037            if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
4038                if (keepAwake) {
4039                    mVoiceWakeLock.acquire();
4040                } else {
4041                    mVoiceWakeLock.release();
4042                }
4043            }
4044        }
4045    }
4046
4047    @Override
4048    public boolean startNextMatchingActivity(IBinder callingActivity,
4049            Intent intent, Bundle options) {
4050        // Refuse possible leaked file descriptors
4051        if (intent != null && intent.hasFileDescriptors() == true) {
4052            throw new IllegalArgumentException("File descriptors passed in Intent");
4053        }
4054
4055        synchronized (this) {
4056            final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
4057            if (r == null) {
4058                ActivityOptions.abort(options);
4059                return false;
4060            }
4061            if (r.app == null || r.app.thread == null) {
4062                // The caller is not running...  d'oh!
4063                ActivityOptions.abort(options);
4064                return false;
4065            }
4066            intent = new Intent(intent);
4067            // The caller is not allowed to change the data.
4068            intent.setDataAndType(r.intent.getData(), r.intent.getType());
4069            // And we are resetting to find the next component...
4070            intent.setComponent(null);
4071
4072            final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4073
4074            ActivityInfo aInfo = null;
4075            try {
4076                List<ResolveInfo> resolves =
4077                    AppGlobals.getPackageManager().queryIntentActivities(
4078                            intent, r.resolvedType,
4079                            PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
4080                            UserHandle.getCallingUserId());
4081
4082                // Look for the original activity in the list...
4083                final int N = resolves != null ? resolves.size() : 0;
4084                for (int i=0; i<N; i++) {
4085                    ResolveInfo rInfo = resolves.get(i);
4086                    if (rInfo.activityInfo.packageName.equals(r.packageName)
4087                            && rInfo.activityInfo.name.equals(r.info.name)) {
4088                        // We found the current one...  the next matching is
4089                        // after it.
4090                        i++;
4091                        if (i<N) {
4092                            aInfo = resolves.get(i).activityInfo;
4093                        }
4094                        if (debug) {
4095                            Slog.v(TAG, "Next matching activity: found current " + r.packageName
4096                                    + "/" + r.info.name);
4097                            Slog.v(TAG, "Next matching activity: next is " + aInfo.packageName
4098                                    + "/" + aInfo.name);
4099                        }
4100                        break;
4101                    }
4102                }
4103            } catch (RemoteException e) {
4104            }
4105
4106            if (aInfo == null) {
4107                // Nobody who is next!
4108                ActivityOptions.abort(options);
4109                if (debug) Slog.d(TAG, "Next matching activity: nothing found");
4110                return false;
4111            }
4112
4113            intent.setComponent(new ComponentName(
4114                    aInfo.applicationInfo.packageName, aInfo.name));
4115            intent.setFlags(intent.getFlags()&~(
4116                    Intent.FLAG_ACTIVITY_FORWARD_RESULT|
4117                    Intent.FLAG_ACTIVITY_CLEAR_TOP|
4118                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
4119                    Intent.FLAG_ACTIVITY_NEW_TASK));
4120
4121            // Okay now we need to start the new activity, replacing the
4122            // currently running activity.  This is a little tricky because
4123            // we want to start the new one as if the current one is finished,
4124            // but not finish the current one first so that there is no flicker.
4125            // And thus...
4126            final boolean wasFinishing = r.finishing;
4127            r.finishing = true;
4128
4129            // Propagate reply information over to the new activity.
4130            final ActivityRecord resultTo = r.resultTo;
4131            final String resultWho = r.resultWho;
4132            final int requestCode = r.requestCode;
4133            r.resultTo = null;
4134            if (resultTo != null) {
4135                resultTo.removeResultsLocked(r, resultWho, requestCode);
4136            }
4137
4138            final long origId = Binder.clearCallingIdentity();
4139            int res = mStackSupervisor.startActivityLocked(r.app.thread, intent,
4140                    r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null,
4141                    resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage,
4142                    -1, r.launchedFromUid, 0, options, false, false, null, null, null);
4143            Binder.restoreCallingIdentity(origId);
4144
4145            r.finishing = wasFinishing;
4146            if (res != ActivityManager.START_SUCCESS) {
4147                return false;
4148            }
4149            return true;
4150        }
4151    }
4152
4153    @Override
4154    public final int startActivityFromRecents(int taskId, Bundle options) {
4155        if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) {
4156            String msg = "Permission Denial: startActivityFromRecents called without " +
4157                    START_TASKS_FROM_RECENTS;
4158            Slog.w(TAG, msg);
4159            throw new SecurityException(msg);
4160        }
4161        return startActivityFromRecentsInner(taskId, options);
4162    }
4163
4164    final int startActivityFromRecentsInner(int taskId, Bundle options) {
4165        final TaskRecord task;
4166        final int callingUid;
4167        final String callingPackage;
4168        final Intent intent;
4169        final int userId;
4170        synchronized (this) {
4171            task = mStackSupervisor.anyTaskForIdLocked(taskId);
4172            if (task == null) {
4173                throw new IllegalArgumentException("Task " + taskId + " not found.");
4174            }
4175            if (task.getRootActivity() != null) {
4176                moveTaskToFrontLocked(task.taskId, 0, null);
4177                return ActivityManager.START_TASK_TO_FRONT;
4178            }
4179            callingUid = task.mCallingUid;
4180            callingPackage = task.mCallingPackage;
4181            intent = task.intent;
4182            intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
4183            userId = task.userId;
4184        }
4185        return startActivityInPackage(callingUid, callingPackage, intent, null, null, null, 0, 0,
4186                options, userId, null, task);
4187    }
4188
4189    final int startActivityInPackage(int uid, String callingPackage,
4190            Intent intent, String resolvedType, IBinder resultTo,
4191            String resultWho, int requestCode, int startFlags, Bundle options, int userId,
4192            IActivityContainer container, TaskRecord inTask) {
4193
4194        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
4195                false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
4196
4197        // TODO: Switch to user app stacks here.
4198        int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent,
4199                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
4200                null, null, null, options, false, userId, container, inTask);
4201        return ret;
4202    }
4203
4204    @Override
4205    public final int startActivities(IApplicationThread caller, String callingPackage,
4206            Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
4207            int userId) {
4208        enforceNotIsolatedCaller("startActivities");
4209        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
4210                false, ALLOW_FULL_ONLY, "startActivity", null);
4211        // TODO: Switch to user app stacks here.
4212        int ret = mStackSupervisor.startActivities(caller, -1, callingPackage, intents,
4213                resolvedTypes, resultTo, options, userId);
4214        return ret;
4215    }
4216
4217    final int startActivitiesInPackage(int uid, String callingPackage,
4218            Intent[] intents, String[] resolvedTypes, IBinder resultTo,
4219            Bundle options, int userId) {
4220
4221        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
4222                false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
4223        // TODO: Switch to user app stacks here.
4224        int ret = mStackSupervisor.startActivities(null, uid, callingPackage, intents, resolvedTypes,
4225                resultTo, options, userId);
4226        return ret;
4227    }
4228
4229    @Override
4230    public void reportActivityFullyDrawn(IBinder token) {
4231        synchronized (this) {
4232            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4233            if (r == null) {
4234                return;
4235            }
4236            r.reportFullyDrawnLocked();
4237        }
4238    }
4239
4240    @Override
4241    public void setRequestedOrientation(IBinder token, int requestedOrientation) {
4242        synchronized (this) {
4243            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4244            if (r == null) {
4245                return;
4246            }
4247            if (r.task != null && r.task.mResizeable) {
4248                // Fixed screen orientation isn't supported with resizeable activities.
4249                return;
4250            }
4251            final long origId = Binder.clearCallingIdentity();
4252            mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
4253            Configuration config = mWindowManager.updateOrientationFromAppTokens(
4254                    mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
4255            if (config != null) {
4256                r.frozenBeforeDestroy = true;
4257                if (!updateConfigurationLocked(config, r, false, false)) {
4258                    mStackSupervisor.resumeTopActivitiesLocked();
4259                }
4260            }
4261            Binder.restoreCallingIdentity(origId);
4262        }
4263    }
4264
4265    @Override
4266    public int getRequestedOrientation(IBinder token) {
4267        synchronized (this) {
4268            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4269            if (r == null) {
4270                return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
4271            }
4272            return mWindowManager.getAppOrientation(r.appToken);
4273        }
4274    }
4275
4276    /**
4277     * This is the internal entry point for handling Activity.finish().
4278     *
4279     * @param token The Binder token referencing the Activity we want to finish.
4280     * @param resultCode Result code, if any, from this Activity.
4281     * @param resultData Result data (Intent), if any, from this Activity.
4282     * @param finishTask Whether to finish the task associated with this Activity.  Only applies to
4283     *            the root Activity in the task.
4284     *
4285     * @return Returns true if the activity successfully finished, or false if it is still running.
4286     */
4287    @Override
4288    public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
4289            boolean finishTask) {
4290        // Refuse possible leaked file descriptors
4291        if (resultData != null && resultData.hasFileDescriptors() == true) {
4292            throw new IllegalArgumentException("File descriptors passed in Intent");
4293        }
4294
4295        synchronized(this) {
4296            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4297            if (r == null) {
4298                return true;
4299            }
4300            // Keep track of the root activity of the task before we finish it
4301            TaskRecord tr = r.task;
4302            ActivityRecord rootR = tr.getRootActivity();
4303            if (rootR == null) {
4304                Slog.w(TAG, "Finishing task with all activities already finished");
4305            }
4306            // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
4307            // finish.
4308            if (tr.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && rootR == r &&
4309                    mStackSupervisor.isLastLockedTask(tr)) {
4310                Slog.i(TAG, "Not finishing task in lock task mode");
4311                mStackSupervisor.showLockTaskToast();
4312                return false;
4313            }
4314            if (mController != null) {
4315                // Find the first activity that is not finishing.
4316                ActivityRecord next = r.task.stack.topRunningActivityLocked(token, 0);
4317                if (next != null) {
4318                    // ask watcher if this is allowed
4319                    boolean resumeOK = true;
4320                    try {
4321                        resumeOK = mController.activityResuming(next.packageName);
4322                    } catch (RemoteException e) {
4323                        mController = null;
4324                        Watchdog.getInstance().setActivityController(null);
4325                    }
4326
4327                    if (!resumeOK) {
4328                        Slog.i(TAG, "Not finishing activity because controller resumed");
4329                        return false;
4330                    }
4331                }
4332            }
4333            final long origId = Binder.clearCallingIdentity();
4334            try {
4335                boolean res;
4336                if (finishTask && r == rootR) {
4337                    // If requested, remove the task that is associated to this activity only if it
4338                    // was the root activity in the task. The result code and data is ignored
4339                    // because we don't support returning them across task boundaries.
4340                    res = removeTaskByIdLocked(tr.taskId, false);
4341                    if (!res) {
4342                        Slog.i(TAG, "Removing task failed to finish activity");
4343                    }
4344                } else {
4345                    res = tr.stack.requestFinishActivityLocked(token, resultCode,
4346                            resultData, "app-request", true);
4347                    if (!res) {
4348                        Slog.i(TAG, "Failed to finish by app-request");
4349                    }
4350                }
4351                return res;
4352            } finally {
4353                Binder.restoreCallingIdentity(origId);
4354            }
4355        }
4356    }
4357
4358    @Override
4359    public final void finishHeavyWeightApp() {
4360        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4361                != PackageManager.PERMISSION_GRANTED) {
4362            String msg = "Permission Denial: finishHeavyWeightApp() from pid="
4363                    + Binder.getCallingPid()
4364                    + ", uid=" + Binder.getCallingUid()
4365                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4366            Slog.w(TAG, msg);
4367            throw new SecurityException(msg);
4368        }
4369
4370        synchronized(this) {
4371            if (mHeavyWeightProcess == null) {
4372                return;
4373            }
4374
4375            ArrayList<ActivityRecord> activities = new ArrayList<>(mHeavyWeightProcess.activities);
4376            for (int i = 0; i < activities.size(); i++) {
4377                ActivityRecord r = activities.get(i);
4378                if (!r.finishing && r.isInStackLocked()) {
4379                    r.task.stack.finishActivityLocked(r, Activity.RESULT_CANCELED,
4380                            null, "finish-heavy", true);
4381                }
4382            }
4383
4384            mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4385                    mHeavyWeightProcess.userId, 0));
4386            mHeavyWeightProcess = null;
4387        }
4388    }
4389
4390    @Override
4391    public void crashApplication(int uid, int initialPid, String packageName,
4392            String message) {
4393        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4394                != PackageManager.PERMISSION_GRANTED) {
4395            String msg = "Permission Denial: crashApplication() from pid="
4396                    + Binder.getCallingPid()
4397                    + ", uid=" + Binder.getCallingUid()
4398                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4399            Slog.w(TAG, msg);
4400            throw new SecurityException(msg);
4401        }
4402
4403        synchronized(this) {
4404            ProcessRecord proc = null;
4405
4406            // Figure out which process to kill.  We don't trust that initialPid
4407            // still has any relation to current pids, so must scan through the
4408            // list.
4409            synchronized (mPidsSelfLocked) {
4410                for (int i=0; i<mPidsSelfLocked.size(); i++) {
4411                    ProcessRecord p = mPidsSelfLocked.valueAt(i);
4412                    if (p.uid != uid) {
4413                        continue;
4414                    }
4415                    if (p.pid == initialPid) {
4416                        proc = p;
4417                        break;
4418                    }
4419                    if (p.pkgList.containsKey(packageName)) {
4420                        proc = p;
4421                    }
4422                }
4423            }
4424
4425            if (proc == null) {
4426                Slog.w(TAG, "crashApplication: nothing for uid=" + uid
4427                        + " initialPid=" + initialPid
4428                        + " packageName=" + packageName);
4429                return;
4430            }
4431
4432            if (proc.thread != null) {
4433                if (proc.pid == Process.myPid()) {
4434                    Log.w(TAG, "crashApplication: trying to crash self!");
4435                    return;
4436                }
4437                long ident = Binder.clearCallingIdentity();
4438                try {
4439                    proc.thread.scheduleCrash(message);
4440                } catch (RemoteException e) {
4441                }
4442                Binder.restoreCallingIdentity(ident);
4443            }
4444        }
4445    }
4446
4447    @Override
4448    public final void finishSubActivity(IBinder token, String resultWho,
4449            int requestCode) {
4450        synchronized(this) {
4451            final long origId = Binder.clearCallingIdentity();
4452            ActivityRecord r = ActivityRecord.isInStackLocked(token);
4453            if (r != null) {
4454                r.task.stack.finishSubActivityLocked(r, resultWho, requestCode);
4455            }
4456            Binder.restoreCallingIdentity(origId);
4457        }
4458    }
4459
4460    @Override
4461    public boolean finishActivityAffinity(IBinder token) {
4462        synchronized(this) {
4463            final long origId = Binder.clearCallingIdentity();
4464            try {
4465                ActivityRecord r = ActivityRecord.isInStackLocked(token);
4466                if (r == null) {
4467                    return false;
4468                }
4469
4470                // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
4471                // can finish.
4472                final TaskRecord task = r.task;
4473                if (task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV &&
4474                        mStackSupervisor.isLastLockedTask(task) && task.getRootActivity() == r) {
4475                    mStackSupervisor.showLockTaskToast();
4476                    return false;
4477                }
4478                return task.stack.finishActivityAffinityLocked(r);
4479            } finally {
4480                Binder.restoreCallingIdentity(origId);
4481            }
4482        }
4483    }
4484
4485    @Override
4486    public void finishVoiceTask(IVoiceInteractionSession session) {
4487        synchronized(this) {
4488            final long origId = Binder.clearCallingIdentity();
4489            try {
4490                mStackSupervisor.finishVoiceTask(session);
4491            } finally {
4492                Binder.restoreCallingIdentity(origId);
4493            }
4494        }
4495
4496    }
4497
4498    @Override
4499    public boolean releaseActivityInstance(IBinder token) {
4500        synchronized(this) {
4501            final long origId = Binder.clearCallingIdentity();
4502            try {
4503                ActivityRecord r = ActivityRecord.isInStackLocked(token);
4504                if (r == null) {
4505                    return false;
4506                }
4507                return r.task.stack.safelyDestroyActivityLocked(r, "app-req");
4508            } finally {
4509                Binder.restoreCallingIdentity(origId);
4510            }
4511        }
4512    }
4513
4514    @Override
4515    public void releaseSomeActivities(IApplicationThread appInt) {
4516        synchronized(this) {
4517            final long origId = Binder.clearCallingIdentity();
4518            try {
4519                ProcessRecord app = getRecordForAppLocked(appInt);
4520                mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
4521            } finally {
4522                Binder.restoreCallingIdentity(origId);
4523            }
4524        }
4525    }
4526
4527    @Override
4528    public boolean willActivityBeVisible(IBinder token) {
4529        synchronized(this) {
4530            ActivityStack stack = ActivityRecord.getStackLocked(token);
4531            if (stack != null) {
4532                return stack.willActivityBeVisibleLocked(token);
4533            }
4534            return false;
4535        }
4536    }
4537
4538    @Override
4539    public void overridePendingTransition(IBinder token, String packageName,
4540            int enterAnim, int exitAnim) {
4541        synchronized(this) {
4542            ActivityRecord self = ActivityRecord.isInStackLocked(token);
4543            if (self == null) {
4544                return;
4545            }
4546
4547            final long origId = Binder.clearCallingIdentity();
4548
4549            if (self.state == ActivityState.RESUMED
4550                    || self.state == ActivityState.PAUSING) {
4551                mWindowManager.overridePendingAppTransition(packageName,
4552                        enterAnim, exitAnim, null);
4553            }
4554
4555            Binder.restoreCallingIdentity(origId);
4556        }
4557    }
4558
4559    /**
4560     * Main function for removing an existing process from the activity manager
4561     * as a result of that process going away.  Clears out all connections
4562     * to the process.
4563     */
4564    private final void handleAppDiedLocked(ProcessRecord app,
4565            boolean restarting, boolean allowRestart) {
4566        int pid = app.pid;
4567        boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
4568        if (!kept && !restarting) {
4569            removeLruProcessLocked(app);
4570            if (pid > 0) {
4571                ProcessList.remove(pid);
4572            }
4573        }
4574
4575        if (mProfileProc == app) {
4576            clearProfilerLocked();
4577        }
4578
4579        // Remove this application's activities from active lists.
4580        boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app);
4581
4582        app.activities.clear();
4583
4584        if (app.instrumentationClass != null) {
4585            Slog.w(TAG, "Crash of app " + app.processName
4586                  + " running instrumentation " + app.instrumentationClass);
4587            Bundle info = new Bundle();
4588            info.putString("shortMsg", "Process crashed.");
4589            finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
4590        }
4591
4592        if (!restarting && hasVisibleActivities && !mStackSupervisor.resumeTopActivitiesLocked()) {
4593            // If there was nothing to resume, and we are not already
4594            // restarting this process, but there is a visible activity that
4595            // is hosted by the process...  then make sure all visible
4596            // activities are running, taking care of restarting this
4597            // process.
4598            mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
4599        }
4600    }
4601
4602    private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
4603        IBinder threadBinder = thread.asBinder();
4604        // Find the application record.
4605        for (int i=mLruProcesses.size()-1; i>=0; i--) {
4606            ProcessRecord rec = mLruProcesses.get(i);
4607            if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
4608                return i;
4609            }
4610        }
4611        return -1;
4612    }
4613
4614    final ProcessRecord getRecordForAppLocked(
4615            IApplicationThread thread) {
4616        if (thread == null) {
4617            return null;
4618        }
4619
4620        int appIndex = getLRURecordIndexForAppLocked(thread);
4621        return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
4622    }
4623
4624    final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
4625        // If there are no longer any background processes running,
4626        // and the app that died was not running instrumentation,
4627        // then tell everyone we are now low on memory.
4628        boolean haveBg = false;
4629        for (int i=mLruProcesses.size()-1; i>=0; i--) {
4630            ProcessRecord rec = mLruProcesses.get(i);
4631            if (rec.thread != null
4632                    && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
4633                haveBg = true;
4634                break;
4635            }
4636        }
4637
4638        if (!haveBg) {
4639            boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
4640            if (doReport) {
4641                long now = SystemClock.uptimeMillis();
4642                if (now < (mLastMemUsageReportTime+5*60*1000)) {
4643                    doReport = false;
4644                } else {
4645                    mLastMemUsageReportTime = now;
4646                }
4647            }
4648            final ArrayList<ProcessMemInfo> memInfos
4649                    = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null;
4650            EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
4651            long now = SystemClock.uptimeMillis();
4652            for (int i=mLruProcesses.size()-1; i>=0; i--) {
4653                ProcessRecord rec = mLruProcesses.get(i);
4654                if (rec == dyingProc || rec.thread == null) {
4655                    continue;
4656                }
4657                if (doReport) {
4658                    memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
4659                            rec.setProcState, rec.adjType, rec.makeAdjReason()));
4660                }
4661                if ((rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
4662                    // The low memory report is overriding any current
4663                    // state for a GC request.  Make sure to do
4664                    // heavy/important/visible/foreground processes first.
4665                    if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
4666                        rec.lastRequestedGc = 0;
4667                    } else {
4668                        rec.lastRequestedGc = rec.lastLowMemory;
4669                    }
4670                    rec.reportLowMemory = true;
4671                    rec.lastLowMemory = now;
4672                    mProcessesToGc.remove(rec);
4673                    addProcessToGcListLocked(rec);
4674                }
4675            }
4676            if (doReport) {
4677                Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
4678                mHandler.sendMessage(msg);
4679            }
4680            scheduleAppGcsLocked();
4681        }
4682    }
4683
4684    final void appDiedLocked(ProcessRecord app) {
4685       appDiedLocked(app, app.pid, app.thread, false);
4686    }
4687
4688    final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
4689            boolean fromBinderDied) {
4690        // First check if this ProcessRecord is actually active for the pid.
4691        synchronized (mPidsSelfLocked) {
4692            ProcessRecord curProc = mPidsSelfLocked.get(pid);
4693            if (curProc != app) {
4694                Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
4695                return;
4696            }
4697        }
4698
4699        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
4700        synchronized (stats) {
4701            stats.noteProcessDiedLocked(app.info.uid, pid);
4702        }
4703
4704        if (!app.killed) {
4705            if (!fromBinderDied) {
4706                Process.killProcessQuiet(pid);
4707            }
4708            killProcessGroup(app.info.uid, pid);
4709            app.killed = true;
4710        }
4711
4712        // Clean up already done if the process has been re-started.
4713        if (app.pid == pid && app.thread != null &&
4714                app.thread.asBinder() == thread.asBinder()) {
4715            boolean doLowMem = app.instrumentationClass == null;
4716            boolean doOomAdj = doLowMem;
4717            if (!app.killedByAm) {
4718                Slog.i(TAG, "Process " + app.processName + " (pid " + pid
4719                        + ") has died");
4720                mAllowLowerMemLevel = true;
4721            } else {
4722                // Note that we always want to do oom adj to update our state with the
4723                // new number of procs.
4724                mAllowLowerMemLevel = false;
4725                doLowMem = false;
4726            }
4727            EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
4728            if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
4729                "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
4730            handleAppDiedLocked(app, false, true);
4731
4732            if (doOomAdj) {
4733                updateOomAdjLocked();
4734            }
4735            if (doLowMem) {
4736                doLowMemReportIfNeededLocked(app);
4737            }
4738        } else if (app.pid != pid) {
4739            // A new process has already been started.
4740            Slog.i(TAG, "Process " + app.processName + " (pid " + pid
4741                    + ") has died and restarted (pid " + app.pid + ").");
4742            EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
4743        } else if (DEBUG_PROCESSES) {
4744            Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
4745                    + thread.asBinder());
4746        }
4747    }
4748
4749    /**
4750     * If a stack trace dump file is configured, dump process stack traces.
4751     * @param clearTraces causes the dump file to be erased prior to the new
4752     *    traces being written, if true; when false, the new traces will be
4753     *    appended to any existing file content.
4754     * @param firstPids of dalvik VM processes to dump stack traces for first
4755     * @param lastPids of dalvik VM processes to dump stack traces for last
4756     * @param nativeProcs optional list of native process names to dump stack crawls
4757     * @return file containing stack traces, or null if no dump file is configured
4758     */
4759    public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
4760            ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
4761        String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4762        if (tracesPath == null || tracesPath.length() == 0) {
4763            return null;
4764        }
4765
4766        File tracesFile = new File(tracesPath);
4767        try {
4768            File tracesDir = tracesFile.getParentFile();
4769            if (!tracesDir.exists()) {
4770                tracesDir.mkdirs();
4771                if (!SELinux.restorecon(tracesDir)) {
4772                    return null;
4773                }
4774            }
4775            FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
4776
4777            if (clearTraces && tracesFile.exists()) tracesFile.delete();
4778            tracesFile.createNewFile();
4779            FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4780        } catch (IOException e) {
4781            Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
4782            return null;
4783        }
4784
4785        dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativeProcs);
4786        return tracesFile;
4787    }
4788
4789    private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
4790            ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
4791        // Use a FileObserver to detect when traces finish writing.
4792        // The order of traces is considered important to maintain for legibility.
4793        FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
4794            @Override
4795            public synchronized void onEvent(int event, String path) { notify(); }
4796        };
4797
4798        try {
4799            observer.startWatching();
4800
4801            // First collect all of the stacks of the most important pids.
4802            if (firstPids != null) {
4803                try {
4804                    int num = firstPids.size();
4805                    for (int i = 0; i < num; i++) {
4806                        synchronized (observer) {
4807                            Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
4808                            observer.wait(200);  // Wait for write-close, give up after 200msec
4809                        }
4810                    }
4811                } catch (InterruptedException e) {
4812                    Slog.wtf(TAG, e);
4813                }
4814            }
4815
4816            // Next collect the stacks of the native pids
4817            if (nativeProcs != null) {
4818                int[] pids = Process.getPidsForCommands(nativeProcs);
4819                if (pids != null) {
4820                    for (int pid : pids) {
4821                        Debug.dumpNativeBacktraceToFile(pid, tracesPath);
4822                    }
4823                }
4824            }
4825
4826            // Lastly, measure CPU usage.
4827            if (processCpuTracker != null) {
4828                processCpuTracker.init();
4829                System.gc();
4830                processCpuTracker.update();
4831                try {
4832                    synchronized (processCpuTracker) {
4833                        processCpuTracker.wait(500); // measure over 1/2 second.
4834                    }
4835                } catch (InterruptedException e) {
4836                }
4837                processCpuTracker.update();
4838
4839                // We'll take the stack crawls of just the top apps using CPU.
4840                final int N = processCpuTracker.countWorkingStats();
4841                int numProcs = 0;
4842                for (int i=0; i<N && numProcs<5; i++) {
4843                    ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
4844                    if (lastPids.indexOfKey(stats.pid) >= 0) {
4845                        numProcs++;
4846                        try {
4847                            synchronized (observer) {
4848                                Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
4849                                observer.wait(200);  // Wait for write-close, give up after 200msec
4850                            }
4851                        } catch (InterruptedException e) {
4852                            Slog.wtf(TAG, e);
4853                        }
4854
4855                    }
4856                }
4857            }
4858        } finally {
4859            observer.stopWatching();
4860        }
4861    }
4862
4863    final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
4864        if (true || IS_USER_BUILD) {
4865            return;
4866        }
4867        String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4868        if (tracesPath == null || tracesPath.length() == 0) {
4869            return;
4870        }
4871
4872        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4873        StrictMode.allowThreadDiskWrites();
4874        try {
4875            final File tracesFile = new File(tracesPath);
4876            final File tracesDir = tracesFile.getParentFile();
4877            final File tracesTmp = new File(tracesDir, "__tmp__");
4878            try {
4879                if (!tracesDir.exists()) {
4880                    tracesDir.mkdirs();
4881                    if (!SELinux.restorecon(tracesDir.getPath())) {
4882                        return;
4883                    }
4884                }
4885                FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
4886
4887                if (tracesFile.exists()) {
4888                    tracesTmp.delete();
4889                    tracesFile.renameTo(tracesTmp);
4890                }
4891                StringBuilder sb = new StringBuilder();
4892                Time tobj = new Time();
4893                tobj.set(System.currentTimeMillis());
4894                sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
4895                sb.append(": ");
4896                TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
4897                sb.append(" since ");
4898                sb.append(msg);
4899                FileOutputStream fos = new FileOutputStream(tracesFile);
4900                fos.write(sb.toString().getBytes());
4901                if (app == null) {
4902                    fos.write("\n*** No application process!".getBytes());
4903                }
4904                fos.close();
4905                FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4906            } catch (IOException e) {
4907                Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
4908                return;
4909            }
4910
4911            if (app != null) {
4912                ArrayList<Integer> firstPids = new ArrayList<Integer>();
4913                firstPids.add(app.pid);
4914                dumpStackTraces(tracesPath, firstPids, null, null, null);
4915            }
4916
4917            File lastTracesFile = null;
4918            File curTracesFile = null;
4919            for (int i=9; i>=0; i--) {
4920                String name = String.format(Locale.US, "slow%02d.txt", i);
4921                curTracesFile = new File(tracesDir, name);
4922                if (curTracesFile.exists()) {
4923                    if (lastTracesFile != null) {
4924                        curTracesFile.renameTo(lastTracesFile);
4925                    } else {
4926                        curTracesFile.delete();
4927                    }
4928                }
4929                lastTracesFile = curTracesFile;
4930            }
4931            tracesFile.renameTo(curTracesFile);
4932            if (tracesTmp.exists()) {
4933                tracesTmp.renameTo(tracesFile);
4934            }
4935        } finally {
4936            StrictMode.setThreadPolicy(oldPolicy);
4937        }
4938    }
4939
4940    final void appNotResponding(ProcessRecord app, ActivityRecord activity,
4941            ActivityRecord parent, boolean aboveSystem, final String annotation) {
4942        ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
4943        SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
4944
4945        if (mController != null) {
4946            try {
4947                // 0 == continue, -1 = kill process immediately
4948                int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
4949                if (res < 0 && app.pid != MY_PID) {
4950