Home | History | Annotate | Download | only in am
      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 
     17 package com.android.server.am;
     18 
     19 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
     20 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
     21 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
     22 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
     23 import static com.android.internal.util.XmlUtils.readBooleanAttribute;
     24 import static com.android.internal.util.XmlUtils.readIntAttribute;
     25 import static com.android.internal.util.XmlUtils.readLongAttribute;
     26 import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
     27 import static com.android.internal.util.XmlUtils.writeIntAttribute;
     28 import static com.android.internal.util.XmlUtils.writeLongAttribute;
     29 import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
     30 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
     31 import static org.xmlpull.v1.XmlPullParser.START_TAG;
     32 import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID;
     33 import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
     34 
     35 import android.Manifest;
     36 import android.app.AppOpsManager;
     37 import android.app.ApplicationThreadNative;
     38 import android.app.IActivityContainer;
     39 import android.app.IActivityContainerCallback;
     40 import android.app.IAppTask;
     41 import android.app.ITaskStackListener;
     42 import android.app.ProfilerInfo;
     43 import android.app.admin.DevicePolicyManager;
     44 import android.app.usage.UsageEvents;
     45 import android.app.usage.UsageStatsManagerInternal;
     46 import android.appwidget.AppWidgetManager;
     47 import android.content.res.Resources;
     48 import android.graphics.Bitmap;
     49 import android.graphics.Point;
     50 import android.graphics.Rect;
     51 import android.os.BatteryStats;
     52 import android.os.PersistableBundle;
     53 import android.os.storage.IMountService;
     54 import android.os.storage.StorageManager;
     55 import android.service.voice.IVoiceInteractionSession;
     56 import android.util.ArrayMap;
     57 import android.util.ArraySet;
     58 import android.util.SparseIntArray;
     59 
     60 import android.view.Display;
     61 import com.android.internal.R;
     62 import com.android.internal.annotations.GuardedBy;
     63 import com.android.internal.app.IAppOpsService;
     64 import com.android.internal.app.IVoiceInteractor;
     65 import com.android.internal.app.ProcessMap;
     66 import com.android.internal.app.ProcessStats;
     67 import com.android.internal.os.BackgroundThread;
     68 import com.android.internal.os.BatteryStatsImpl;
     69 import com.android.internal.os.ProcessCpuTracker;
     70 import com.android.internal.os.TransferPipe;
     71 import com.android.internal.os.Zygote;
     72 import com.android.internal.util.FastPrintWriter;
     73 import com.android.internal.util.FastXmlSerializer;
     74 import com.android.internal.util.MemInfoReader;
     75 import com.android.internal.util.Preconditions;
     76 import com.android.server.AppOpsService;
     77 import com.android.server.AttributeCache;
     78 import com.android.server.IntentResolver;
     79 import com.android.server.LocalServices;
     80 import com.android.server.ServiceThread;
     81 import com.android.server.SystemService;
     82 import com.android.server.SystemServiceManager;
     83 import com.android.server.Watchdog;
     84 import com.android.server.am.ActivityStack.ActivityState;
     85 import com.android.server.firewall.IntentFirewall;
     86 import com.android.server.pm.Installer;
     87 import com.android.server.pm.UserManagerService;
     88 import com.android.server.statusbar.StatusBarManagerInternal;
     89 import com.android.server.wm.AppTransition;
     90 import com.android.server.wm.WindowManagerService;
     91 import com.google.android.collect.Lists;
     92 import com.google.android.collect.Maps;
     93 
     94 import libcore.io.IoUtils;
     95 
     96 import org.xmlpull.v1.XmlPullParser;
     97 import org.xmlpull.v1.XmlPullParserException;
     98 import org.xmlpull.v1.XmlSerializer;
     99 
    100 import android.app.Activity;
    101 import android.app.ActivityManager;
    102 import android.app.ActivityManager.RunningTaskInfo;
    103 import android.app.ActivityManager.StackInfo;
    104 import android.app.ActivityManagerInternal;
    105 import android.app.ActivityManagerNative;
    106 import android.app.ActivityOptions;
    107 import android.app.ActivityThread;
    108 import android.app.AlertDialog;
    109 import android.app.AppGlobals;
    110 import android.app.ApplicationErrorReport;
    111 import android.app.Dialog;
    112 import android.app.IActivityController;
    113 import android.app.IApplicationThread;
    114 import android.app.IInstrumentationWatcher;
    115 import android.app.INotificationManager;
    116 import android.app.IProcessObserver;
    117 import android.app.IServiceConnection;
    118 import android.app.IStopUserCallback;
    119 import android.app.IUiAutomationConnection;
    120 import android.app.IUserSwitchObserver;
    121 import android.app.Instrumentation;
    122 import android.app.Notification;
    123 import android.app.NotificationManager;
    124 import android.app.PendingIntent;
    125 import android.app.backup.IBackupManager;
    126 import android.content.ActivityNotFoundException;
    127 import android.content.BroadcastReceiver;
    128 import android.content.ClipData;
    129 import android.content.ComponentCallbacks2;
    130 import android.content.ComponentName;
    131 import android.content.ContentProvider;
    132 import android.content.ContentResolver;
    133 import android.content.Context;
    134 import android.content.DialogInterface;
    135 import android.content.IContentProvider;
    136 import android.content.IIntentReceiver;
    137 import android.content.IIntentSender;
    138 import android.content.Intent;
    139 import android.content.IntentFilter;
    140 import android.content.IntentSender;
    141 import android.content.pm.ActivityInfo;
    142 import android.content.pm.ApplicationInfo;
    143 import android.content.pm.ConfigurationInfo;
    144 import android.content.pm.IPackageDataObserver;
    145 import android.content.pm.IPackageManager;
    146 import android.content.pm.InstrumentationInfo;
    147 import android.content.pm.PackageInfo;
    148 import android.content.pm.PackageManager;
    149 import android.content.pm.ParceledListSlice;
    150 import android.content.pm.UserInfo;
    151 import android.content.pm.PackageManager.NameNotFoundException;
    152 import android.content.pm.PathPermission;
    153 import android.content.pm.ProviderInfo;
    154 import android.content.pm.ResolveInfo;
    155 import android.content.pm.ServiceInfo;
    156 import android.content.res.CompatibilityInfo;
    157 import android.content.res.Configuration;
    158 import android.net.Proxy;
    159 import android.net.ProxyInfo;
    160 import android.net.Uri;
    161 import android.os.Binder;
    162 import android.os.Build;
    163 import android.os.Bundle;
    164 import android.os.Debug;
    165 import android.os.DropBoxManager;
    166 import android.os.Environment;
    167 import android.os.FactoryTest;
    168 import android.os.FileObserver;
    169 import android.os.FileUtils;
    170 import android.os.Handler;
    171 import android.os.IBinder;
    172 import android.os.IPermissionController;
    173 import android.os.IRemoteCallback;
    174 import android.os.IUserManager;
    175 import android.os.Looper;
    176 import android.os.Message;
    177 import android.os.Parcel;
    178 import android.os.ParcelFileDescriptor;
    179 import android.os.PowerManagerInternal;
    180 import android.os.Process;
    181 import android.os.RemoteCallbackList;
    182 import android.os.RemoteException;
    183 import android.os.SELinux;
    184 import android.os.ServiceManager;
    185 import android.os.StrictMode;
    186 import android.os.SystemClock;
    187 import android.os.SystemProperties;
    188 import android.os.UpdateLock;
    189 import android.os.UserHandle;
    190 import android.os.UserManager;
    191 import android.provider.Settings;
    192 import android.text.format.DateUtils;
    193 import android.text.format.Time;
    194 import android.util.AtomicFile;
    195 import android.util.EventLog;
    196 import android.util.Log;
    197 import android.util.Pair;
    198 import android.util.PrintWriterPrinter;
    199 import android.util.Slog;
    200 import android.util.SparseArray;
    201 import android.util.TimeUtils;
    202 import android.util.Xml;
    203 import android.view.Gravity;
    204 import android.view.LayoutInflater;
    205 import android.view.View;
    206 import android.view.WindowManager;
    207 
    208 import dalvik.system.VMRuntime;
    209 
    210 import java.io.BufferedInputStream;
    211 import java.io.BufferedOutputStream;
    212 import java.io.DataInputStream;
    213 import java.io.DataOutputStream;
    214 import java.io.File;
    215 import java.io.FileDescriptor;
    216 import java.io.FileInputStream;
    217 import java.io.FileNotFoundException;
    218 import java.io.FileOutputStream;
    219 import java.io.IOException;
    220 import java.io.InputStreamReader;
    221 import java.io.PrintWriter;
    222 import java.io.StringWriter;
    223 import java.lang.ref.WeakReference;
    224 import java.util.ArrayList;
    225 import java.util.Arrays;
    226 import java.util.Collections;
    227 import java.util.Comparator;
    228 import java.util.HashMap;
    229 import java.util.HashSet;
    230 import java.util.Iterator;
    231 import java.util.List;
    232 import java.util.Locale;
    233 import java.util.Map;
    234 import java.util.Set;
    235 import java.util.concurrent.atomic.AtomicBoolean;
    236 import java.util.concurrent.atomic.AtomicLong;
    237 
    238 public final class ActivityManagerService extends ActivityManagerNative
    239         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    240 
    241     private static final String USER_DATA_DIR = "/data/user/";
    242     // File that stores last updated system version and called preboot receivers
    243     static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat";
    244 
    245     static final String TAG = "ActivityManager";
    246     static final String TAG_MU = "ActivityManagerServiceMU";
    247     static final boolean DEBUG = false;
    248     static final boolean localLOGV = DEBUG;
    249     static final boolean DEBUG_BACKUP = localLOGV || false;
    250     static final boolean DEBUG_BROADCAST = localLOGV || false;
    251     static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
    252     static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
    253     static final boolean DEBUG_CLEANUP = localLOGV || false;
    254     static final boolean DEBUG_CONFIGURATION = localLOGV || false;
    255     static final boolean DEBUG_FOCUS = false;
    256     static final boolean DEBUG_IMMERSIVE = localLOGV || false;
    257     static final boolean DEBUG_MU = localLOGV || false;
    258     static final boolean DEBUG_OOM_ADJ = localLOGV || false;
    259     static final boolean DEBUG_LRU = localLOGV || false;
    260     static final boolean DEBUG_PAUSE = localLOGV || false;
    261     static final boolean DEBUG_POWER = localLOGV || false;
    262     static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
    263     static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
    264     static final boolean DEBUG_PROCESSES = localLOGV || false;
    265     static final boolean DEBUG_PROVIDER = localLOGV || false;
    266     static final boolean DEBUG_RESULTS = localLOGV || false;
    267     static final boolean DEBUG_SERVICE = localLOGV || false;
    268     static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
    269     static final boolean DEBUG_STACK = localLOGV || false;
    270     static final boolean DEBUG_SWITCH = localLOGV || false;
    271     static final boolean DEBUG_TASKS = localLOGV || false;
    272     static final boolean DEBUG_THUMBNAILS = localLOGV || false;
    273     static final boolean DEBUG_TRANSITION = localLOGV || false;
    274     static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
    275     static final boolean DEBUG_USER_LEAVING = localLOGV || false;
    276     static final boolean DEBUG_VISBILITY = localLOGV || false;
    277     static final boolean DEBUG_PSS = localLOGV || false;
    278     static final boolean DEBUG_LOCKSCREEN = localLOGV || false;
    279     static final boolean DEBUG_RECENTS = localLOGV || false;
    280     static final boolean VALIDATE_TOKENS = false;
    281     static final boolean SHOW_ACTIVITY_START_TIME = true;
    282 
    283     // Control over CPU and battery monitoring.
    284     static final long BATTERY_STATS_TIME = 30*60*1000;      // write battery stats every 30 minutes.
    285     static final boolean MONITOR_CPU_USAGE = true;
    286     static final long MONITOR_CPU_MIN_TIME = 5*1000;        // don't sample cpu less than every 5 seconds.
    287     static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;    // wait possibly forever for next cpu sample.
    288     static final boolean MONITOR_THREAD_CPU_USAGE = false;
    289 
    290     // The flags that are set for all calls we make to the package manager.
    291     static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
    292 
    293     private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
    294 
    295     static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
    296 
    297     // Maximum number recent bitmaps to keep in memory.
    298     static final int MAX_RECENT_BITMAPS = 3;
    299 
    300     // Amount of time after a call to stopAppSwitches() during which we will
    301     // prevent further untrusted switches from happening.
    302     static final long APP_SWITCH_DELAY_TIME = 5*1000;
    303 
    304     // How long we wait for a launched process to attach to the activity manager
    305     // before we decide it's never going to come up for real.
    306     static final int PROC_START_TIMEOUT = 10*1000;
    307 
    308     // How long we wait for a launched process to attach to the activity manager
    309     // before we decide it's never going to come up for real, when the process was
    310     // started with a wrapper for instrumentation (such as Valgrind) because it
    311     // could take much longer than usual.
    312     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
    313 
    314     // How long to wait after going idle before forcing apps to GC.
    315     static final int GC_TIMEOUT = 5*1000;
    316 
    317     // The minimum amount of time between successive GC requests for a process.
    318     static final int GC_MIN_INTERVAL = 60*1000;
    319 
    320     // The minimum amount of time between successive PSS requests for a process.
    321     static final int FULL_PSS_MIN_INTERVAL = 10*60*1000;
    322 
    323     // The minimum amount of time between successive PSS requests for a process
    324     // when the request is due to the memory state being lowered.
    325     static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000;
    326 
    327     // The rate at which we check for apps using excessive power -- 15 mins.
    328     static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
    329 
    330     // The minimum sample duration we will allow before deciding we have
    331     // enough data on wake locks to start killing things.
    332     static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    333 
    334     // The minimum sample duration we will allow before deciding we have
    335     // enough data on CPU usage to start killing things.
    336     static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    337 
    338     // How long we allow a receiver to run before giving up on it.
    339     static final int BROADCAST_FG_TIMEOUT = 10*1000;
    340     static final int BROADCAST_BG_TIMEOUT = 60*1000;
    341 
    342     // How long we wait until we timeout on key dispatching.
    343     static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
    344 
    345     // How long we wait until we timeout on key dispatching during instrumentation.
    346     static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
    347 
    348     // Amount of time we wait for observers to handle a user switch before
    349     // giving up on them and unfreezing the screen.
    350     static final int USER_SWITCH_TIMEOUT = 2*1000;
    351 
    352     // Maximum number of users we allow to be running at a time.
    353     static final int MAX_RUNNING_USERS = 3;
    354 
    355     // How long to wait in getAssistContextExtras for the activity and foreground services
    356     // to respond with the result.
    357     static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
    358 
    359     // Maximum number of persisted Uri grants a package is allowed
    360     static final int MAX_PERSISTED_URI_GRANTS = 128;
    361 
    362     static final int MY_PID = Process.myPid();
    363 
    364     static final String[] EMPTY_STRING_ARRAY = new String[0];
    365 
    366     // How many bytes to write into the dropbox log before truncating
    367     static final int DROPBOX_MAX_SIZE = 256 * 1024;
    368 
    369     // Access modes for handleIncomingUser.
    370     static final int ALLOW_NON_FULL = 0;
    371     static final int ALLOW_NON_FULL_IN_PROFILE = 1;
    372     static final int ALLOW_FULL_ONLY = 2;
    373 
    374     static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000;
    375 
    376     // Delay in notifying task stack change listeners (in millis)
    377     static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 1000;
    378 
    379     /** All system services */
    380     SystemServiceManager mSystemServiceManager;
    381 
    382     private Installer mInstaller;
    383 
    384     /** Run all ActivityStacks through this */
    385     ActivityStackSupervisor mStackSupervisor;
    386 
    387     /** Task stack change listeners. */
    388     private RemoteCallbackList<ITaskStackListener> mTaskStackListeners =
    389             new RemoteCallbackList<ITaskStackListener>();
    390 
    391     public IntentFirewall mIntentFirewall;
    392 
    393     // Whether we should show our dialogs (ANR, crash, etc) or just perform their
    394     // default actuion automatically.  Important for devices without direct input
    395     // devices.
    396     private boolean mShowDialogs = true;
    397 
    398     BroadcastQueue mFgBroadcastQueue;
    399     BroadcastQueue mBgBroadcastQueue;
    400     // Convenient for easy iteration over the queues. Foreground is first
    401     // so that dispatch of foreground broadcasts gets precedence.
    402     final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
    403 
    404     BroadcastQueue broadcastQueueForIntent(Intent intent) {
    405         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
    406         if (DEBUG_BACKGROUND_BROADCAST) {
    407             Slog.i(TAG, "Broadcast intent " + intent + " on "
    408                     + (isFg ? "foreground" : "background")
    409                     + " queue");
    410         }
    411         return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
    412     }
    413 
    414     BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
    415         for (BroadcastQueue queue : mBroadcastQueues) {
    416             BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
    417             if (r != null) {
    418                 return r;
    419             }
    420         }
    421         return null;
    422     }
    423 
    424     /**
    425      * Activity we have told the window manager to have key focus.
    426      */
    427     ActivityRecord mFocusedActivity = null;
    428 
    429     /**
    430      * List of intents that were used to start the most recent tasks.
    431      */
    432     ArrayList<TaskRecord> mRecentTasks;
    433     ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>();
    434 
    435     /**
    436      * For addAppTask: cached of the last activity component that was added.
    437      */
    438     ComponentName mLastAddedTaskComponent;
    439 
    440     /**
    441      * For addAppTask: cached of the last activity uid that was added.
    442      */
    443     int mLastAddedTaskUid;
    444 
    445     /**
    446      * For addAppTask: cached of the last ActivityInfo that was added.
    447      */
    448     ActivityInfo mLastAddedTaskActivity;
    449 
    450     public class PendingAssistExtras extends Binder implements Runnable {
    451         public final ActivityRecord activity;
    452         public final Bundle extras;
    453         public final Intent intent;
    454         public final String hint;
    455         public final int userHandle;
    456         public boolean haveResult = false;
    457         public Bundle result = null;
    458         public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
    459                 String _hint, int _userHandle) {
    460             activity = _activity;
    461             extras = _extras;
    462             intent = _intent;
    463             hint = _hint;
    464             userHandle = _userHandle;
    465         }
    466         @Override
    467         public void run() {
    468             Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
    469             synchronized (this) {
    470                 haveResult = true;
    471                 notifyAll();
    472             }
    473         }
    474     }
    475 
    476     final ArrayList<PendingAssistExtras> mPendingAssistExtras
    477             = new ArrayList<PendingAssistExtras>();
    478 
    479     /**
    480      * Process management.
    481      */
    482     final ProcessList mProcessList = new ProcessList();
    483 
    484     /**
    485      * All of the applications we currently have running organized by name.
    486      * The keys are strings of the application package name (as
    487      * returned by the package manager), and the keys are ApplicationRecord
    488      * objects.
    489      */
    490     final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
    491 
    492     /**
    493      * Tracking long-term execution of processes to look for abuse and other
    494      * bad app behavior.
    495      */
    496     final ProcessStatsService mProcessStats;
    497 
    498     /**
    499      * The currently running isolated processes.
    500      */
    501     final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
    502 
    503     /**
    504      * Counter for assigning isolated process uids, to avoid frequently reusing the
    505      * same ones.
    506      */
    507     int mNextIsolatedProcessUid = 0;
    508 
    509     /**
    510      * The currently running heavy-weight process, if any.
    511      */
    512     ProcessRecord mHeavyWeightProcess = null;
    513 
    514     /**
    515      * The last time that various processes have crashed.
    516      */
    517     final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
    518 
    519     /**
    520      * Information about a process that is currently marked as bad.
    521      */
    522     static final class BadProcessInfo {
    523         BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
    524             this.time = time;
    525             this.shortMsg = shortMsg;
    526             this.longMsg = longMsg;
    527             this.stack = stack;
    528         }
    529 
    530         final long time;
    531         final String shortMsg;
    532         final String longMsg;
    533         final String stack;
    534     }
    535 
    536     /**
    537      * Set of applications that we consider to be bad, and will reject
    538      * incoming broadcasts from (which the user has no control over).
    539      * Processes are added to this set when they have crashed twice within
    540      * a minimum amount of time; they are removed from it when they are
    541      * later restarted (hopefully due to some user action).  The value is the
    542      * time it was added to the list.
    543      */
    544     final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>();
    545 
    546     /**
    547      * All of the processes we currently have running organized by pid.
    548      * The keys are the pid running the application.
    549      *
    550      * <p>NOTE: This object is protected by its own lock, NOT the global
    551      * activity manager lock!
    552      */
    553     final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
    554 
    555     /**
    556      * All of the processes that have been forced to be foreground.  The key
    557      * is the pid of the caller who requested it (we hold a death
    558      * link on it).
    559      */
    560     abstract class ForegroundToken implements IBinder.DeathRecipient {
    561         int pid;
    562         IBinder token;
    563     }
    564     final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>();
    565 
    566     /**
    567      * List of records for processes that someone had tried to start before the
    568      * system was ready.  We don't start them at that point, but ensure they
    569      * are started by the time booting is complete.
    570      */
    571     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
    572 
    573     /**
    574      * List of persistent applications that are in the process
    575      * of being started.
    576      */
    577     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
    578 
    579     /**
    580      * Processes that are being forcibly torn down.
    581      */
    582     final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>();
    583 
    584     /**
    585      * List of running applications, sorted by recent usage.
    586      * The first entry in the list is the least recently used.
    587      */
    588     final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();
    589 
    590     /**
    591      * Where in mLruProcesses that the processes hosting activities start.
    592      */
    593     int mLruProcessActivityStart = 0;
    594 
    595     /**
    596      * Where in mLruProcesses that the processes hosting services start.
    597      * This is after (lower index) than mLruProcessesActivityStart.
    598      */
    599     int mLruProcessServiceStart = 0;
    600 
    601     /**
    602      * List of processes that should gc as soon as things are idle.
    603      */
    604     final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
    605 
    606     /**
    607      * Processes we want to collect PSS data from.
    608      */
    609     final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
    610 
    611     /**
    612      * Last time we requested PSS data of all processes.
    613      */
    614     long mLastFullPssTime = SystemClock.uptimeMillis();
    615 
    616     /**
    617      * If set, the next time we collect PSS data we should do a full collection
    618      * with data from native processes and the kernel.
    619      */
    620     boolean mFullPssPending = false;
    621 
    622     /**
    623      * This is the process holding what we currently consider to be
    624      * the "home" activity.
    625      */
    626     ProcessRecord mHomeProcess;
    627 
    628     /**
    629      * This is the process holding the activity the user last visited that
    630      * is in a different process from the one they are currently in.
    631      */
    632     ProcessRecord mPreviousProcess;
    633 
    634     /**
    635      * The time at which the previous process was last visible.
    636      */
    637     long mPreviousProcessVisibleTime;
    638 
    639     /**
    640      * Which uses have been started, so are allowed to run code.
    641      */
    642     final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
    643 
    644     /**
    645      * LRU list of history of current users.  Most recently current is at the end.
    646      */
    647     final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
    648 
    649     /**
    650      * Constant array of the users that are currently started.
    651      */
    652     int[] mStartedUserArray = new int[] { 0 };
    653 
    654     /**
    655      * Registered observers of the user switching mechanics.
    656      */
    657     final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
    658             = new RemoteCallbackList<IUserSwitchObserver>();
    659 
    660     /**
    661      * Currently active user switch.
    662      */
    663     Object mCurUserSwitchCallback;
    664 
    665     /**
    666      * Packages that the user has asked to have run in screen size
    667      * compatibility mode instead of filling the screen.
    668      */
    669     final CompatModePackages mCompatModePackages;
    670 
    671     /**
    672      * Set of IntentSenderRecord objects that are currently active.
    673      */
    674     final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
    675             = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
    676 
    677     /**
    678      * Fingerprints (hashCode()) of stack traces that we've
    679      * already logged DropBox entries for.  Guarded by itself.  If
    680      * something (rogue user app) forces this over
    681      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
    682      */
    683     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
    684     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
    685 
    686     /**
    687      * Strict Mode background batched logging state.
    688      *
    689      * The string buffer is guarded by itself, and its lock is also
    690      * used to determine if another batched write is already
    691      * in-flight.
    692      */
    693     private final StringBuilder mStrictModeBuffer = new StringBuilder();
    694 
    695     /**
    696      * Keeps track of all IIntentReceivers that have been registered for
    697      * broadcasts.  Hash keys are the receiver IBinder, hash value is
    698      * a ReceiverList.
    699      */
    700     final HashMap<IBinder, ReceiverList> mRegisteredReceivers =
    701             new HashMap<IBinder, ReceiverList>();
    702 
    703     /**
    704      * Resolver for broadcast intents to registered receivers.
    705      * Holds BroadcastFilter (subclass of IntentFilter).
    706      */
    707     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
    708             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
    709         @Override
    710         protected boolean allowFilterResult(
    711                 BroadcastFilter filter, List<BroadcastFilter> dest) {
    712             IBinder target = filter.receiverList.receiver.asBinder();
    713             for (int i=dest.size()-1; i>=0; i--) {
    714                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
    715                     return false;
    716                 }
    717             }
    718             return true;
    719         }
    720 
    721         @Override
    722         protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
    723             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
    724                     || userId == filter.owningUserId) {
    725                 return super.newResult(filter, match, userId);
    726             }
    727             return null;
    728         }
    729 
    730         @Override
    731         protected BroadcastFilter[] newArray(int size) {
    732             return new BroadcastFilter[size];
    733         }
    734 
    735         @Override
    736         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
    737             return packageName.equals(filter.packageName);
    738         }
    739     };
    740 
    741     /**
    742      * State of all active sticky broadcasts per user.  Keys are the action of the
    743      * sticky Intent, values are an ArrayList of all broadcasted intents with
    744      * that action (which should usually be one).  The SparseArray is keyed
    745      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
    746      * for stickies that are sent to all users.
    747      */
    748     final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
    749             new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
    750 
    751     final ActiveServices mServices;
    752 
    753     final static class Association {
    754         final int mSourceUid;
    755         final String mSourceProcess;
    756         final int mTargetUid;
    757         final ComponentName mTargetComponent;
    758         final String mTargetProcess;
    759 
    760         int mCount;
    761         long mTime;
    762 
    763         int mNesting;
    764         long mStartTime;
    765 
    766         Association(int sourceUid, String sourceProcess, int targetUid,
    767                 ComponentName targetComponent, String targetProcess) {
    768             mSourceUid = sourceUid;
    769             mSourceProcess = sourceProcess;
    770             mTargetUid = targetUid;
    771             mTargetComponent = targetComponent;
    772             mTargetProcess = targetProcess;
    773         }
    774     }
    775 
    776     /**
    777      * When service association tracking is enabled, this is all of the associations we
    778      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
    779      * -> association data.
    780      */
    781     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
    782             mAssociations = new SparseArray<>();
    783     boolean mTrackingAssociations;
    784 
    785     /**
    786      * Backup/restore process management
    787      */
    788     String mBackupAppName = null;
    789     BackupRecord mBackupTarget = null;
    790 
    791     final ProviderMap mProviderMap;
    792 
    793     /**
    794      * List of content providers who have clients waiting for them.  The
    795      * application is currently being launched and the provider will be
    796      * removed from this list once it is published.
    797      */
    798     final ArrayList<ContentProviderRecord> mLaunchingProviders
    799             = new ArrayList<ContentProviderRecord>();
    800 
    801     /**
    802      * File storing persisted {@link #mGrantedUriPermissions}.
    803      */
    804     private final AtomicFile mGrantFile;
    805 
    806     /** XML constants used in {@link #mGrantFile} */
    807     private static final String TAG_URI_GRANTS = "uri-grants";
    808     private static final String TAG_URI_GRANT = "uri-grant";
    809     private static final String ATTR_USER_HANDLE = "userHandle";
    810     private static final String ATTR_SOURCE_USER_ID = "sourceUserId";
    811     private static final String ATTR_TARGET_USER_ID = "targetUserId";
    812     private static final String ATTR_SOURCE_PKG = "sourcePkg";
    813     private static final String ATTR_TARGET_PKG = "targetPkg";
    814     private static final String ATTR_URI = "uri";
    815     private static final String ATTR_MODE_FLAGS = "modeFlags";
    816     private static final String ATTR_CREATED_TIME = "createdTime";
    817     private static final String ATTR_PREFIX = "prefix";
    818 
    819     /**
    820      * Global set of specific {@link Uri} permissions that have been granted.
    821      * This optimized lookup structure maps from {@link UriPermission#targetUid}
    822      * to {@link UriPermission#uri} to {@link UriPermission}.
    823      */
    824     @GuardedBy("this")
    825     private final SparseArray<ArrayMap<GrantUri, UriPermission>>
    826             mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>();
    827 
    828     public static class GrantUri {
    829         public final int sourceUserId;
    830         public final Uri uri;
    831         public boolean prefix;
    832 
    833         public GrantUri(int sourceUserId, Uri uri, boolean prefix) {
    834             this.sourceUserId = sourceUserId;
    835             this.uri = uri;
    836             this.prefix = prefix;
    837         }
    838 
    839         @Override
    840         public int hashCode() {
    841             int hashCode = 1;
    842             hashCode = 31 * hashCode + sourceUserId;
    843             hashCode = 31 * hashCode + uri.hashCode();
    844             hashCode = 31 * hashCode + (prefix ? 1231 : 1237);
    845             return hashCode;
    846         }
    847 
    848         @Override
    849         public boolean equals(Object o) {
    850             if (o instanceof GrantUri) {
    851                 GrantUri other = (GrantUri) o;
    852                 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId)
    853                         && prefix == other.prefix;
    854             }
    855             return false;
    856         }
    857 
    858         @Override
    859         public String toString() {
    860             String result = Integer.toString(sourceUserId) + " @ " + uri.toString();
    861             if (prefix) result += " [prefix]";
    862             return result;
    863         }
    864 
    865         public String toSafeString() {
    866             String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString();
    867             if (prefix) result += " [prefix]";
    868             return result;
    869         }
    870 
    871         public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) {
    872             return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle),
    873                     ContentProvider.getUriWithoutUserId(uri), false);
    874         }
    875     }
    876 
    877     CoreSettingsObserver mCoreSettingsObserver;
    878 
    879     /**
    880      * Thread-local storage used to carry caller permissions over through
    881      * indirect content-provider access.
    882      */
    883     private class Identity {
    884         public final IBinder token;
    885         public final int pid;
    886         public final int uid;
    887 
    888         Identity(IBinder _token, int _pid, int _uid) {
    889             token = _token;
    890             pid = _pid;
    891             uid = _uid;
    892         }
    893     }
    894 
    895     private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
    896 
    897     /**
    898      * All information we have collected about the runtime performance of
    899      * any user id that can impact battery performance.
    900      */
    901     final BatteryStatsService mBatteryStatsService;
    902 
    903     /**
    904      * Information about component usage
    905      */
    906     UsageStatsManagerInternal mUsageStatsService;
    907 
    908     /**
    909      * Information about and control over application operations
    910      */
    911     final AppOpsService mAppOpsService;
    912 
    913     /**
    914      * Save recent tasks information across reboots.
    915      */
    916     final TaskPersister mTaskPersister;
    917 
    918     /**
    919      * Current configuration information.  HistoryRecord objects are given
    920      * a reference to this object to indicate which configuration they are
    921      * currently running in, so this object must be kept immutable.
    922      */
    923     Configuration mConfiguration = new Configuration();
    924 
    925     /**
    926      * Current sequencing integer of the configuration, for skipping old
    927      * configurations.
    928      */
    929     int mConfigurationSeq = 0;
    930 
    931     /**
    932      * Hardware-reported OpenGLES version.
    933      */
    934     final int GL_ES_VERSION;
    935 
    936     /**
    937      * List of initialization arguments to pass to all processes when binding applications to them.
    938      * For example, references to the commonly used services.
    939      */
    940     HashMap<String, IBinder> mAppBindArgs;
    941 
    942     /**
    943      * Temporary to avoid allocations.  Protected by main lock.
    944      */
    945     final StringBuilder mStringBuilder = new StringBuilder(256);
    946 
    947     /**
    948      * Used to control how we initialize the service.
    949      */
    950     ComponentName mTopComponent;
    951     String mTopAction = Intent.ACTION_MAIN;
    952     String mTopData;
    953     boolean mProcessesReady = false;
    954     boolean mSystemReady = false;
    955     boolean mBooting = false;
    956     boolean mCallFinishBooting = false;
    957     boolean mBootAnimationComplete = false;
    958     boolean mWaitingUpdate = false;
    959     boolean mDidUpdate = false;
    960     boolean mOnBattery = false;
    961     boolean mLaunchWarningShown = false;
    962 
    963     Context mContext;
    964 
    965     int mFactoryTest;
    966 
    967     boolean mCheckedForSetup;
    968 
    969     /**
    970      * The time at which we will allow normal application switches again,
    971      * after a call to {@link #stopAppSwitches()}.
    972      */
    973     long mAppSwitchesAllowedTime;
    974 
    975     /**
    976      * This is set to true after the first switch after mAppSwitchesAllowedTime
    977      * is set; any switches after that will clear the time.
    978      */
    979     boolean mDidAppSwitch;
    980 
    981     /**
    982      * Last time (in realtime) at which we checked for power usage.
    983      */
    984     long mLastPowerCheckRealtime;
    985 
    986     /**
    987      * Last time (in uptime) at which we checked for power usage.
    988      */
    989     long mLastPowerCheckUptime;
    990 
    991     /**
    992      * Set while we are wanting to sleep, to prevent any
    993      * activities from being started/resumed.
    994      */
    995     private boolean mSleeping = false;
    996 
    997     /**
    998      * Set while we are running a voice interaction.  This overrides
    999      * sleeping while it is active.
   1000      */
   1001     private boolean mRunningVoice = false;
   1002 
   1003     /**
   1004      * State of external calls telling us if the device is awake or asleep.
   1005      */
   1006     private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
   1007 
   1008     static final int LOCK_SCREEN_HIDDEN = 0;
   1009     static final int LOCK_SCREEN_LEAVING = 1;
   1010     static final int LOCK_SCREEN_SHOWN = 2;
   1011     /**
   1012      * State of external call telling us if the lock screen is shown.
   1013      */
   1014     int mLockScreenShown = LOCK_SCREEN_HIDDEN;
   1015 
   1016     /**
   1017      * Set if we are shutting down the system, similar to sleeping.
   1018      */
   1019     boolean mShuttingDown = false;
   1020 
   1021     /**
   1022      * Current sequence id for oom_adj computation traversal.
   1023      */
   1024     int mAdjSeq = 0;
   1025 
   1026     /**
   1027      * Current sequence id for process LRU updating.
   1028      */
   1029     int mLruSeq = 0;
   1030 
   1031     /**
   1032      * Keep track of the non-cached/empty process we last found, to help
   1033      * determine how to distribute cached/empty processes next time.
   1034      */
   1035     int mNumNonCachedProcs = 0;
   1036 
   1037     /**
   1038      * Keep track of the number of cached hidden procs, to balance oom adj
   1039      * distribution between those and empty procs.
   1040      */
   1041     int mNumCachedHiddenProcs = 0;
   1042 
   1043     /**
   1044      * Keep track of the number of service processes we last found, to
   1045      * determine on the next iteration which should be B services.
   1046      */
   1047     int mNumServiceProcs = 0;
   1048     int mNewNumAServiceProcs = 0;
   1049     int mNewNumServiceProcs = 0;
   1050 
   1051     /**
   1052      * Allow the current computed overall memory level of the system to go down?
   1053      * This is set to false when we are killing processes for reasons other than
   1054      * memory management, so that the now smaller process list will not be taken as
   1055      * an indication that memory is tighter.
   1056      */
   1057     boolean mAllowLowerMemLevel = false;
   1058 
   1059     /**
   1060      * The last computed memory level, for holding when we are in a state that
   1061      * processes are going away for other reasons.
   1062      */
   1063     int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
   1064 
   1065     /**
   1066      * The last total number of process we have, to determine if changes actually look
   1067      * like a shrinking number of process due to lower RAM.
   1068      */
   1069     int mLastNumProcesses;
   1070 
   1071     /**
   1072      * The uptime of the last time we performed idle maintenance.
   1073      */
   1074     long mLastIdleTime = SystemClock.uptimeMillis();
   1075 
   1076     /**
   1077      * Total time spent with RAM that has been added in the past since the last idle time.
   1078      */
   1079     long mLowRamTimeSinceLastIdle = 0;
   1080 
   1081     /**
   1082      * If RAM is currently low, when that horrible situation started.
   1083      */
   1084     long mLowRamStartTime = 0;
   1085 
   1086     /**
   1087      * For reporting to battery stats the current top application.
   1088      */
   1089     private String mCurResumedPackage = null;
   1090     private int mCurResumedUid = -1;
   1091 
   1092     /**
   1093      * For reporting to battery stats the apps currently running foreground
   1094      * service.  The ProcessMap is package/uid tuples; each of these contain
   1095      * an array of the currently foreground processes.
   1096      */
   1097     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
   1098             = new ProcessMap<ArrayList<ProcessRecord>>();
   1099 
   1100     /**
   1101      * This is set if we had to do a delayed dexopt of an app before launching
   1102      * it, to increase the ANR timeouts in that case.
   1103      */
   1104     boolean mDidDexOpt;
   1105 
   1106     /**
   1107      * Set if the systemServer made a call to enterSafeMode.
   1108      */
   1109     boolean mSafeMode;
   1110 
   1111     /**
   1112      * If true, we are running under a test environment so will sample PSS from processes
   1113      * much more rapidly to try to collect better data when the tests are rapidly
   1114      * running through apps.
   1115      */
   1116     boolean mTestPssMode = false;
   1117 
   1118     String mDebugApp = null;
   1119     boolean mWaitForDebugger = false;
   1120     boolean mDebugTransient = false;
   1121     String mOrigDebugApp = null;
   1122     boolean mOrigWaitForDebugger = false;
   1123     boolean mAlwaysFinishActivities = false;
   1124     IActivityController mController = null;
   1125     String mProfileApp = null;
   1126     ProcessRecord mProfileProc = null;
   1127     String mProfileFile;
   1128     ParcelFileDescriptor mProfileFd;
   1129     int mSamplingInterval = 0;
   1130     boolean mAutoStopProfiler = false;
   1131     int mProfileType = 0;
   1132     String mOpenGlTraceApp = null;
   1133 
   1134     final long[] mTmpLong = new long[1];
   1135 
   1136     static class ProcessChangeItem {
   1137         static final int CHANGE_ACTIVITIES = 1<<0;
   1138         static final int CHANGE_PROCESS_STATE = 1<<1;
   1139         int changes;
   1140         int uid;
   1141         int pid;
   1142         int processState;
   1143         boolean foregroundActivities;
   1144     }
   1145 
   1146     final RemoteCallbackList<IProcessObserver> mProcessObservers
   1147             = new RemoteCallbackList<IProcessObserver>();
   1148     ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
   1149 
   1150     final ArrayList<ProcessChangeItem> mPendingProcessChanges
   1151             = new ArrayList<ProcessChangeItem>();
   1152     final ArrayList<ProcessChangeItem> mAvailProcessChanges
   1153             = new ArrayList<ProcessChangeItem>();
   1154 
   1155     /**
   1156      * Runtime CPU use collection thread.  This object's lock is used to
   1157      * perform synchronization with the thread (notifying it to run).
   1158      */
   1159     final Thread mProcessCpuThread;
   1160 
   1161     /**
   1162      * Used to collect per-process CPU use for ANRs, battery stats, etc.
   1163      * Must acquire this object's lock when accessing it.
   1164      * NOTE: this lock will be held while doing long operations (trawling
   1165      * through all processes in /proc), so it should never be acquired by
   1166      * any critical paths such as when holding the main activity manager lock.
   1167      */
   1168     final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
   1169             MONITOR_THREAD_CPU_USAGE);
   1170     final AtomicLong mLastCpuTime = new AtomicLong(0);
   1171     final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
   1172 
   1173     long mLastWriteTime = 0;
   1174 
   1175     /**
   1176      * Used to retain an update lock when the foreground activity is in
   1177      * immersive mode.
   1178      */
   1179     final UpdateLock mUpdateLock = new UpdateLock("immersive");
   1180 
   1181     /**
   1182      * Set to true after the system has finished booting.
   1183      */
   1184     boolean mBooted = false;
   1185 
   1186     int mProcessLimit = ProcessList.MAX_CACHED_APPS;
   1187     int mProcessLimitOverride = -1;
   1188 
   1189     WindowManagerService mWindowManager;
   1190 
   1191     final ActivityThread mSystemThread;
   1192 
   1193     // Holds the current foreground user's id
   1194     int mCurrentUserId = 0;
   1195     // Holds the target user's id during a user switch
   1196     int mTargetUserId = UserHandle.USER_NULL;
   1197     // If there are multiple profiles for the current user, their ids are here
   1198     // Currently only the primary user can have managed profiles
   1199     int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack
   1200 
   1201     /**
   1202      * Mapping from each known user ID to the profile group ID it is associated with.
   1203      */
   1204     SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
   1205 
   1206     private UserManagerService mUserManager;
   1207 
   1208     private final class AppDeathRecipient implements IBinder.DeathRecipient {
   1209         final ProcessRecord mApp;
   1210         final int mPid;
   1211         final IApplicationThread mAppThread;
   1212 
   1213         AppDeathRecipient(ProcessRecord app, int pid,
   1214                 IApplicationThread thread) {
   1215             if (localLOGV) Slog.v(
   1216                 TAG, "New death recipient " + this
   1217                 + " for thread " + thread.asBinder());
   1218             mApp = app;
   1219             mPid = pid;
   1220             mAppThread = thread;
   1221         }
   1222 
   1223         @Override
   1224         public void binderDied() {
   1225             if (localLOGV) Slog.v(
   1226                 TAG, "Death received in " + this
   1227                 + " for thread " + mAppThread.asBinder());
   1228             synchronized(ActivityManagerService.this) {
   1229                 appDiedLocked(mApp, mPid, mAppThread);
   1230             }
   1231         }
   1232     }
   1233 
   1234     static final int SHOW_ERROR_MSG = 1;
   1235     static final int SHOW_NOT_RESPONDING_MSG = 2;
   1236     static final int SHOW_FACTORY_ERROR_MSG = 3;
   1237     static final int UPDATE_CONFIGURATION_MSG = 4;
   1238     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
   1239     static final int WAIT_FOR_DEBUGGER_MSG = 6;
   1240     static final int SERVICE_TIMEOUT_MSG = 12;
   1241     static final int UPDATE_TIME_ZONE = 13;
   1242     static final int SHOW_UID_ERROR_MSG = 14;
   1243     static final int SHOW_FINGERPRINT_ERROR_MSG = 15;
   1244     static final int PROC_START_TIMEOUT_MSG = 20;
   1245     static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
   1246     static final int KILL_APPLICATION_MSG = 22;
   1247     static final int FINALIZE_PENDING_INTENT_MSG = 23;
   1248     static final int POST_HEAVY_NOTIFICATION_MSG = 24;
   1249     static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
   1250     static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
   1251     static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
   1252     static final int CLEAR_DNS_CACHE_MSG = 28;
   1253     static final int UPDATE_HTTP_PROXY_MSG = 29;
   1254     static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
   1255     static final int DISPATCH_PROCESSES_CHANGED = 31;
   1256     static final int DISPATCH_PROCESS_DIED = 32;
   1257     static final int REPORT_MEM_USAGE_MSG = 33;
   1258     static final int REPORT_USER_SWITCH_MSG = 34;
   1259     static final int CONTINUE_USER_SWITCH_MSG = 35;
   1260     static final int USER_SWITCH_TIMEOUT_MSG = 36;
   1261     static final int IMMERSIVE_MODE_LOCK_MSG = 37;
   1262     static final int PERSIST_URI_GRANTS_MSG = 38;
   1263     static final int REQUEST_ALL_PSS_MSG = 39;
   1264     static final int START_PROFILES_MSG = 40;
   1265     static final int UPDATE_TIME = 41;
   1266     static final int SYSTEM_USER_START_MSG = 42;
   1267     static final int SYSTEM_USER_CURRENT_MSG = 43;
   1268     static final int ENTER_ANIMATION_COMPLETE_MSG = 44;
   1269     static final int FINISH_BOOTING_MSG = 45;
   1270     static final int START_USER_SWITCH_MSG = 46;
   1271     static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47;
   1272     static final int DISMISS_DIALOG_MSG = 48;
   1273     static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG = 49;
   1274 
   1275     static final int FIRST_ACTIVITY_STACK_MSG = 100;
   1276     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
   1277     static final int FIRST_COMPAT_MODE_MSG = 300;
   1278     static final int FIRST_SUPERVISOR_STACK_MSG = 100;
   1279 
   1280     CompatModeDialog mCompatModeDialog;
   1281     long mLastMemUsageReportTime = 0;
   1282 
   1283     /**
   1284      * Flag whether the current user is a "monkey", i.e. whether
   1285      * the UI is driven by a UI automation tool.
   1286      */
   1287     private boolean mUserIsMonkey;
   1288 
   1289     /** Flag whether the device has a Recents UI */
   1290     boolean mHasRecents;
   1291 
   1292     /** The dimensions of the thumbnails in the Recents UI. */
   1293     int mThumbnailWidth;
   1294     int mThumbnailHeight;
   1295 
   1296     final ServiceThread mHandlerThread;
   1297     final MainHandler mHandler;
   1298 
   1299     final class MainHandler extends Handler {
   1300         public MainHandler(Looper looper) {
   1301             super(looper, null, true);
   1302         }
   1303 
   1304         @Override
   1305         public void handleMessage(Message msg) {
   1306             switch (msg.what) {
   1307             case SHOW_ERROR_MSG: {
   1308                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
   1309                 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
   1310                         Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
   1311                 synchronized (ActivityManagerService.this) {
   1312                     ProcessRecord proc = (ProcessRecord)data.get("app");
   1313                     AppErrorResult res = (AppErrorResult) data.get("result");
   1314                     if (proc != null && proc.crashDialog != null) {
   1315                         Slog.e(TAG, "App already has crash dialog: " + proc);
   1316                         if (res != null) {
   1317                             res.set(0);
   1318                         }
   1319                         return;
   1320                     }
   1321                     boolean isBackground = (UserHandle.getAppId(proc.uid)
   1322                             >= Process.FIRST_APPLICATION_UID
   1323                             && proc.pid != MY_PID);
   1324                     for (int userId : mCurrentProfileIds) {
   1325                         isBackground &= (proc.userId != userId);
   1326                     }
   1327                     if (isBackground && !showBackground) {
   1328                         Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
   1329                         if (res != null) {
   1330                             res.set(0);
   1331                         }
   1332                         return;
   1333                     }
   1334                     if (mShowDialogs && !mSleeping && !mShuttingDown) {
   1335                         Dialog d = new AppErrorDialog(mContext,
   1336                                 ActivityManagerService.this, res, proc);
   1337                         d.show();
   1338                         proc.crashDialog = d;
   1339                     } else {
   1340                         // The device is asleep, so just pretend that the user
   1341                         // saw a crash dialog and hit "force quit".
   1342                         if (res != null) {
   1343                             res.set(0);
   1344                         }
   1345                     }
   1346                 }
   1347 
   1348                 ensureBootCompleted();
   1349             } break;
   1350             case SHOW_NOT_RESPONDING_MSG: {
   1351                 synchronized (ActivityManagerService.this) {
   1352                     HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
   1353                     ProcessRecord proc = (ProcessRecord)data.get("app");
   1354                     if (proc != null && proc.anrDialog != null) {
   1355                         Slog.e(TAG, "App already has anr dialog: " + proc);
   1356                         return;
   1357                     }
   1358 
   1359                     Intent intent = new Intent("android.intent.action.ANR");
   1360                     if (!mProcessesReady) {
   1361                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   1362                                 | Intent.FLAG_RECEIVER_FOREGROUND);
   1363                     }
   1364                     broadcastIntentLocked(null, null, intent,
   1365                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
   1366                             false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
   1367 
   1368                     if (mShowDialogs) {
   1369                         Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
   1370                                 mContext, proc, (ActivityRecord)data.get("activity"),
   1371                                 msg.arg1 != 0);
   1372                         d.show();
   1373                         proc.anrDialog = d;
   1374                     } else {
   1375                         // Just kill the app if there is no dialog to be shown.
   1376                         killAppAtUsersRequest(proc, null);
   1377                     }
   1378                 }
   1379 
   1380                 ensureBootCompleted();
   1381             } break;
   1382             case SHOW_STRICT_MODE_VIOLATION_MSG: {
   1383                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
   1384                 synchronized (ActivityManagerService.this) {
   1385                     ProcessRecord proc = (ProcessRecord) data.get("app");
   1386                     if (proc == null) {
   1387                         Slog.e(TAG, "App not found when showing strict mode dialog.");
   1388                         break;
   1389                     }
   1390                     if (proc.crashDialog != null) {
   1391                         Slog.e(TAG, "App already has strict mode dialog: " + proc);
   1392                         return;
   1393                     }
   1394                     AppErrorResult res = (AppErrorResult) data.get("result");
   1395                     if (mShowDialogs && !mSleeping && !mShuttingDown) {
   1396                         Dialog d = new StrictModeViolationDialog(mContext,
   1397                                 ActivityManagerService.this, res, proc);
   1398                         d.show();
   1399                         proc.crashDialog = d;
   1400                     } else {
   1401                         // The device is asleep, so just pretend that the user
   1402                         // saw a crash dialog and hit "force quit".
   1403                         res.set(0);
   1404                     }
   1405                 }
   1406                 ensureBootCompleted();
   1407             } break;
   1408             case SHOW_FACTORY_ERROR_MSG: {
   1409                 Dialog d = new FactoryErrorDialog(
   1410                     mContext, msg.getData().getCharSequence("msg"));
   1411                 d.show();
   1412                 ensureBootCompleted();
   1413             } break;
   1414             case UPDATE_CONFIGURATION_MSG: {
   1415                 final ContentResolver resolver = mContext.getContentResolver();
   1416                 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
   1417             } break;
   1418             case GC_BACKGROUND_PROCESSES_MSG: {
   1419                 synchronized (ActivityManagerService.this) {
   1420                     performAppGcsIfAppropriateLocked();
   1421                 }
   1422             } break;
   1423             case WAIT_FOR_DEBUGGER_MSG: {
   1424                 synchronized (ActivityManagerService.this) {
   1425                     ProcessRecord app = (ProcessRecord)msg.obj;
   1426                     if (msg.arg1 != 0) {
   1427                         if (!app.waitedForDebugger) {
   1428                             Dialog d = new AppWaitingForDebuggerDialog(
   1429                                     ActivityManagerService.this,
   1430                                     mContext, app);
   1431                             app.waitDialog = d;
   1432                             app.waitedForDebugger = true;
   1433                             d.show();
   1434                         }
   1435                     } else {
   1436                         if (app.waitDialog != null) {
   1437                             app.waitDialog.dismiss();
   1438                             app.waitDialog = null;
   1439                         }
   1440                     }
   1441                 }
   1442             } break;
   1443             case SERVICE_TIMEOUT_MSG: {
   1444                 if (mDidDexOpt) {
   1445                     mDidDexOpt = false;
   1446                     Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
   1447                     nmsg.obj = msg.obj;
   1448                     mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
   1449                     return;
   1450                 }
   1451                 mServices.serviceTimeout((ProcessRecord)msg.obj);
   1452             } break;
   1453             case UPDATE_TIME_ZONE: {
   1454                 synchronized (ActivityManagerService.this) {
   1455                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1456                         ProcessRecord r = mLruProcesses.get(i);
   1457                         if (r.thread != null) {
   1458                             try {
   1459                                 r.thread.updateTimeZone();
   1460                             } catch (RemoteException ex) {
   1461                                 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
   1462                             }
   1463                         }
   1464                     }
   1465                 }
   1466             } break;
   1467             case CLEAR_DNS_CACHE_MSG: {
   1468                 synchronized (ActivityManagerService.this) {
   1469                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1470                         ProcessRecord r = mLruProcesses.get(i);
   1471                         if (r.thread != null) {
   1472                             try {
   1473                                 r.thread.clearDnsCache();
   1474                             } catch (RemoteException ex) {
   1475                                 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
   1476                             }
   1477                         }
   1478                     }
   1479                 }
   1480             } break;
   1481             case UPDATE_HTTP_PROXY_MSG: {
   1482                 ProxyInfo proxy = (ProxyInfo)msg.obj;
   1483                 String host = "";
   1484                 String port = "";
   1485                 String exclList = "";
   1486                 Uri pacFileUrl = Uri.EMPTY;
   1487                 if (proxy != null) {
   1488                     host = proxy.getHost();
   1489                     port = Integer.toString(proxy.getPort());
   1490                     exclList = proxy.getExclusionListAsString();
   1491                     pacFileUrl = proxy.getPacFileUrl();
   1492                 }
   1493                 synchronized (ActivityManagerService.this) {
   1494                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1495                         ProcessRecord r = mLruProcesses.get(i);
   1496                         if (r.thread != null) {
   1497                             try {
   1498                                 r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
   1499                             } catch (RemoteException ex) {
   1500                                 Slog.w(TAG, "Failed to update http proxy for: " +
   1501                                         r.info.processName);
   1502                             }
   1503                         }
   1504                     }
   1505                 }
   1506             } break;
   1507             case SHOW_UID_ERROR_MSG: {
   1508                 if (mShowDialogs) {
   1509                     AlertDialog d = new BaseErrorDialog(mContext);
   1510                     d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
   1511                     d.setCancelable(false);
   1512                     d.setTitle(mContext.getText(R.string.android_system_label));
   1513                     d.setMessage(mContext.getText(R.string.system_error_wipe_data));
   1514                     d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
   1515                             mHandler.obtainMessage(DISMISS_DIALOG_MSG, d));
   1516                     d.show();
   1517                 }
   1518             } break;
   1519             case SHOW_FINGERPRINT_ERROR_MSG: {
   1520                 if (mShowDialogs) {
   1521                     AlertDialog d = new BaseErrorDialog(mContext);
   1522                     d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
   1523                     d.setCancelable(false);
   1524                     d.setTitle(mContext.getText(R.string.android_system_label));
   1525                     d.setMessage(mContext.getText(R.string.system_error_manufacturer));
   1526                     d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
   1527                             mHandler.obtainMessage(DISMISS_DIALOG_MSG, d));
   1528                     d.show();
   1529                 }
   1530             } break;
   1531             case PROC_START_TIMEOUT_MSG: {
   1532                 if (mDidDexOpt) {
   1533                     mDidDexOpt = false;
   1534                     Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
   1535                     nmsg.obj = msg.obj;
   1536                     mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
   1537                     return;
   1538                 }
   1539                 ProcessRecord app = (ProcessRecord)msg.obj;
   1540                 synchronized (ActivityManagerService.this) {
   1541                     processStartTimedOutLocked(app);
   1542                 }
   1543             } break;
   1544             case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
   1545                 synchronized (ActivityManagerService.this) {
   1546                     mStackSupervisor.doPendingActivityLaunchesLocked(true);
   1547                 }
   1548             } break;
   1549             case KILL_APPLICATION_MSG: {
   1550                 synchronized (ActivityManagerService.this) {
   1551                     int appid = msg.arg1;
   1552                     boolean restart = (msg.arg2 == 1);
   1553                     Bundle bundle = (Bundle)msg.obj;
   1554                     String pkg = bundle.getString("pkg");
   1555                     String reason = bundle.getString("reason");
   1556                     forceStopPackageLocked(pkg, appid, restart, false, true, false,
   1557                             false, UserHandle.USER_ALL, reason);
   1558                 }
   1559             } break;
   1560             case FINALIZE_PENDING_INTENT_MSG: {
   1561                 ((PendingIntentRecord)msg.obj).completeFinalize();
   1562             } break;
   1563             case POST_HEAVY_NOTIFICATION_MSG: {
   1564                 INotificationManager inm = NotificationManager.getService();
   1565                 if (inm == null) {
   1566                     return;
   1567                 }
   1568 
   1569                 ActivityRecord root = (ActivityRecord)msg.obj;
   1570                 ProcessRecord process = root.app;
   1571                 if (process == null) {
   1572                     return;
   1573                 }
   1574 
   1575                 try {
   1576                     Context context = mContext.createPackageContext(process.info.packageName, 0);
   1577                     String text = mContext.getString(R.string.heavy_weight_notification,
   1578                             context.getApplicationInfo().loadLabel(context.getPackageManager()));
   1579                     Notification notification = new Notification();
   1580                     notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
   1581                     notification.when = 0;
   1582                     notification.flags = Notification.FLAG_ONGOING_EVENT;
   1583                     notification.tickerText = text;
   1584                     notification.defaults = 0; // please be quiet
   1585                     notification.sound = null;
   1586                     notification.vibrate = null;
   1587                     notification.color = mContext.getResources().getColor(
   1588                             com.android.internal.R.color.system_notification_accent_color);
   1589                     notification.setLatestEventInfo(context, text,
   1590                             mContext.getText(R.string.heavy_weight_notification_detail),
   1591                             PendingIntent.getActivityAsUser(mContext, 0, root.intent,
   1592                                     PendingIntent.FLAG_CANCEL_CURRENT, null,
   1593                                     new UserHandle(root.userId)));
   1594 
   1595                     try {
   1596                         int[] outId = new int[1];
   1597                         inm.enqueueNotificationWithTag("android", "android", null,
   1598                                 R.string.heavy_weight_notification,
   1599                                 notification, outId, root.userId);
   1600                     } catch (RuntimeException e) {
   1601                         Slog.w(ActivityManagerService.TAG,
   1602                                 "Error showing notification for heavy-weight app", e);
   1603                     } catch (RemoteException e) {
   1604                     }
   1605                 } catch (NameNotFoundException e) {
   1606                     Slog.w(TAG, "Unable to create context for heavy notification", e);
   1607                 }
   1608             } break;
   1609             case CANCEL_HEAVY_NOTIFICATION_MSG: {
   1610                 INotificationManager inm = NotificationManager.getService();
   1611                 if (inm == null) {
   1612                     return;
   1613                 }
   1614                 try {
   1615                     inm.cancelNotificationWithTag("android", null,
   1616                             R.string.heavy_weight_notification,  msg.arg1);
   1617                 } catch (RuntimeException e) {
   1618                     Slog.w(ActivityManagerService.TAG,
   1619                             "Error canceling notification for service", e);
   1620                 } catch (RemoteException e) {
   1621                 }
   1622             } break;
   1623             case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
   1624                 synchronized (ActivityManagerService.this) {
   1625                     checkExcessivePowerUsageLocked(true);
   1626                     removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1627                     Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1628                     sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
   1629                 }
   1630             } break;
   1631             case SHOW_COMPAT_MODE_DIALOG_MSG: {
   1632                 synchronized (ActivityManagerService.this) {
   1633                     ActivityRecord ar = (ActivityRecord)msg.obj;
   1634                     if (mCompatModeDialog != null) {
   1635                         if (mCompatModeDialog.mAppInfo.packageName.equals(
   1636                                 ar.info.applicationInfo.packageName)) {
   1637                             return;
   1638                         }
   1639                         mCompatModeDialog.dismiss();
   1640                         mCompatModeDialog = null;
   1641                     }
   1642                     if (ar != null && false) {
   1643                         if (mCompatModePackages.getPackageAskCompatModeLocked(
   1644                                 ar.packageName)) {
   1645                             int mode = mCompatModePackages.computeCompatModeLocked(
   1646                                     ar.info.applicationInfo);
   1647                             if (mode == ActivityManager.COMPAT_MODE_DISABLED
   1648                                     || mode == ActivityManager.COMPAT_MODE_ENABLED) {
   1649                                 mCompatModeDialog = new CompatModeDialog(
   1650                                         ActivityManagerService.this, mContext,
   1651                                         ar.info.applicationInfo);
   1652                                 mCompatModeDialog.show();
   1653                             }
   1654                         }
   1655                     }
   1656                 }
   1657                 break;
   1658             }
   1659             case DISPATCH_PROCESSES_CHANGED: {
   1660                 dispatchProcessesChanged();
   1661                 break;
   1662             }
   1663             case DISPATCH_PROCESS_DIED: {
   1664                 final int pid = msg.arg1;
   1665                 final int uid = msg.arg2;
   1666                 dispatchProcessDied(pid, uid);
   1667                 break;
   1668             }
   1669             case REPORT_MEM_USAGE_MSG: {
   1670                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
   1671                 Thread thread = new Thread() {
   1672                     @Override public void run() {
   1673                         reportMemUsage(memInfos);
   1674                     }
   1675                 };
   1676                 thread.start();
   1677                 break;
   1678             }
   1679             case START_USER_SWITCH_MSG: {
   1680                 showUserSwitchDialog(msg.arg1, (String) msg.obj);
   1681                 break;
   1682             }
   1683             case REPORT_USER_SWITCH_MSG: {
   1684                 dispatchUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
   1685                 break;
   1686             }
   1687             case CONTINUE_USER_SWITCH_MSG: {
   1688                 continueUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
   1689                 break;
   1690             }
   1691             case USER_SWITCH_TIMEOUT_MSG: {
   1692                 timeoutUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
   1693                 break;
   1694             }
   1695             case IMMERSIVE_MODE_LOCK_MSG: {
   1696                 final boolean nextState = (msg.arg1 != 0);
   1697                 if (mUpdateLock.isHeld() != nextState) {
   1698                     if (DEBUG_IMMERSIVE) {
   1699                         final ActivityRecord r = (ActivityRecord) msg.obj;
   1700                         Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
   1701                     }
   1702                     if (nextState) {
   1703                         mUpdateLock.acquire();
   1704                     } else {
   1705                         mUpdateLock.release();
   1706                     }
   1707                 }
   1708                 break;
   1709             }
   1710             case PERSIST_URI_GRANTS_MSG: {
   1711                 writeGrantedUriPermissions();
   1712                 break;
   1713             }
   1714             case REQUEST_ALL_PSS_MSG: {
   1715                 synchronized (ActivityManagerService.this) {
   1716                     requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
   1717                 }
   1718                 break;
   1719             }
   1720             case START_PROFILES_MSG: {
   1721                 synchronized (ActivityManagerService.this) {
   1722                     startProfilesLocked();
   1723                 }
   1724                 break;
   1725             }
   1726             case UPDATE_TIME: {
   1727                 synchronized (ActivityManagerService.this) {
   1728                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1729                         ProcessRecord r = mLruProcesses.get(i);
   1730                         if (r.thread != null) {
   1731                             try {
   1732                                 r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true);
   1733                             } catch (RemoteException ex) {
   1734                                 Slog.w(TAG, "Failed to update preferences for: " + r.info.processName);
   1735                             }
   1736                         }
   1737                     }
   1738                 }
   1739                 break;
   1740             }
   1741             case SYSTEM_USER_START_MSG: {
   1742                 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
   1743                         Integer.toString(msg.arg1), msg.arg1);
   1744                 mSystemServiceManager.startUser(msg.arg1);
   1745                 break;
   1746             }
   1747             case SYSTEM_USER_CURRENT_MSG: {
   1748                 mBatteryStatsService.noteEvent(
   1749                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
   1750                         Integer.toString(msg.arg2), msg.arg2);
   1751                 mBatteryStatsService.noteEvent(
   1752                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
   1753                         Integer.toString(msg.arg1), msg.arg1);
   1754                 mSystemServiceManager.switchUser(msg.arg1);
   1755                 break;
   1756             }
   1757             case ENTER_ANIMATION_COMPLETE_MSG: {
   1758                 synchronized (ActivityManagerService.this) {
   1759                     ActivityRecord r = ActivityRecord.forToken((IBinder) msg.obj);
   1760                     if (r != null && r.app != null && r.app.thread != null) {
   1761                         try {
   1762                             r.app.thread.scheduleEnterAnimationComplete(r.appToken);
   1763                         } catch (RemoteException e) {
   1764                         }
   1765                     }
   1766                 }
   1767                 break;
   1768             }
   1769             case FINISH_BOOTING_MSG: {
   1770                 if (msg.arg1 != 0) {
   1771                     finishBooting();
   1772                 }
   1773                 if (msg.arg2 != 0) {
   1774                     enableScreenAfterBoot();
   1775                 }
   1776                 break;
   1777             }
   1778             case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: {
   1779                 try {
   1780                     Locale l = (Locale) msg.obj;
   1781                     IBinder service = ServiceManager.getService("mount");
   1782                     IMountService mountService = IMountService.Stub.asInterface(service);
   1783                     Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
   1784                     mountService.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
   1785                 } catch (RemoteException e) {
   1786                     Log.e(TAG, "Error storing locale for decryption UI", e);
   1787                 }
   1788                 break;
   1789             }
   1790             case DISMISS_DIALOG_MSG: {
   1791                 final Dialog d = (Dialog) msg.obj;
   1792                 d.dismiss();
   1793                 break;
   1794             }
   1795             case NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG: {
   1796                 synchronized (ActivityManagerService.this) {
   1797                     int i = mTaskStackListeners.beginBroadcast();
   1798                     while (i > 0) {
   1799                         i--;
   1800                         try {
   1801                             // Make a one-way callback to the listener
   1802                             mTaskStackListeners.getBroadcastItem(i).onTaskStackChanged();
   1803                         } catch (RemoteException e){
   1804                             // Handled by the RemoteCallbackList
   1805                         }
   1806                     }
   1807                     mTaskStackListeners.finishBroadcast();
   1808                 }
   1809                 break;
   1810             }
   1811             }
   1812         }
   1813     };
   1814 
   1815     static final int COLLECT_PSS_BG_MSG = 1;
   1816 
   1817     final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
   1818         @Override
   1819         public void handleMessage(Message msg) {
   1820             switch (msg.what) {
   1821             case COLLECT_PSS_BG_MSG: {
   1822                 long start = SystemClock.uptimeMillis();
   1823                 MemInfoReader memInfo = null;
   1824                 synchronized (ActivityManagerService.this) {
   1825                     if (mFullPssPending) {
   1826                         mFullPssPending = false;
   1827                         memInfo = new MemInfoReader();
   1828                     }
   1829                 }
   1830                 if (memInfo != null) {
   1831                     updateCpuStatsNow();
   1832                     long nativeTotalPss = 0;
   1833                     synchronized (mProcessCpuTracker) {
   1834                         final int N = mProcessCpuTracker.countStats();
   1835                         for (int j=0; j<N; j++) {
   1836                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j);
   1837                             if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) {
   1838                                 // This is definitely an application process; skip it.
   1839                                 continue;
   1840                             }
   1841                             synchronized (mPidsSelfLocked) {
   1842                                 if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) {
   1843                                     // This is one of our own processes; skip it.
   1844                                     continue;
   1845                                 }
   1846                             }
   1847                             nativeTotalPss += Debug.getPss(st.pid, null, null);
   1848                         }
   1849                     }
   1850                     memInfo.readMemInfo();
   1851                     synchronized (ActivityManagerService.this) {
   1852                         if (DEBUG_PSS) Slog.d(TAG, "Collected native and kernel memory in "
   1853                                 + (SystemClock.uptimeMillis()-start) + "ms");
   1854                         mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(),
   1855                                 memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(),
   1856                                 memInfo.getKernelUsedSizeKb(), nativeTotalPss);
   1857                     }
   1858                 }
   1859 
   1860                 int num = 0;
   1861                 long[] tmp = new long[1];
   1862                 do {
   1863                     ProcessRecord proc;
   1864                     int procState;
   1865                     int pid;
   1866                     long lastPssTime;
   1867                     synchronized (ActivityManagerService.this) {
   1868                         if (mPendingPssProcesses.size() <= 0) {
   1869                             if (mTestPssMode || DEBUG_PSS) Slog.d(TAG, "Collected PSS of " + num
   1870                                     + " processes in " + (SystemClock.uptimeMillis()-start) + "ms");
   1871                             mPendingPssProcesses.clear();
   1872                             return;
   1873                         }
   1874                         proc = mPendingPssProcesses.remove(0);
   1875                         procState = proc.pssProcState;
   1876                         lastPssTime = proc.lastPssTime;
   1877                         if (proc.thread != null && procState == proc.setProcState
   1878                                 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
   1879                                         < SystemClock.uptimeMillis()) {
   1880                             pid = proc.pid;
   1881                         } else {
   1882                             proc = null;
   1883                             pid = 0;
   1884                         }
   1885                     }
   1886                     if (proc != null) {
   1887                         long pss = Debug.getPss(pid, tmp, null);
   1888                         synchronized (ActivityManagerService.this) {
   1889                             if (pss != 0 && proc.thread != null && proc.setProcState == procState
   1890                                     && proc.pid == pid && proc.lastPssTime == lastPssTime) {
   1891                                 num++;
   1892                                 recordPssSample(proc, procState, pss, tmp[0],
   1893                                         SystemClock.uptimeMillis());
   1894                             }
   1895                         }
   1896                     }
   1897                 } while (true);
   1898             }
   1899             }
   1900         }
   1901     };
   1902 
   1903     public void setSystemProcess() {
   1904         try {
   1905             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
   1906             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
   1907             ServiceManager.addService("meminfo", new MemBinder(this));
   1908             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
   1909             ServiceManager.addService("dbinfo", new DbBinder(this));
   1910             if (MONITOR_CPU_USAGE) {
   1911                 ServiceManager.addService("cpuinfo", new CpuBinder(this));
   1912             }
   1913             ServiceManager.addService("permission", new PermissionController(this));
   1914 
   1915             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
   1916                     "android", STOCK_PM_FLAGS);
   1917             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
   1918 
   1919             synchronized (this) {
   1920                 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
   1921                 app.persistent = true;
   1922                 app.pid = MY_PID;
   1923                 app.maxAdj = ProcessList.SYSTEM_ADJ;
   1924                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
   1925                 mProcessNames.put(app.processName, app.uid, app);
   1926                 synchronized (mPidsSelfLocked) {
   1927                     mPidsSelfLocked.put(app.pid, app);
   1928                 }
   1929                 updateLruProcessLocked(app, false, null);
   1930                 updateOomAdjLocked();
   1931             }
   1932         } catch (PackageManager.NameNotFoundException e) {
   1933             throw new RuntimeException(
   1934                     "Unable to find android system package", e);
   1935         }
   1936     }
   1937 
   1938     public void setWindowManager(WindowManagerService wm) {
   1939         mWindowManager = wm;
   1940         mStackSupervisor.setWindowManager(wm);
   1941     }
   1942 
   1943     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
   1944         mUsageStatsService = usageStatsManager;
   1945     }
   1946 
   1947     public void startObservingNativeCrashes() {
   1948         final NativeCrashListener ncl = new NativeCrashListener(this);
   1949         ncl.start();
   1950     }
   1951 
   1952     public IAppOpsService getAppOpsService() {
   1953         return mAppOpsService;
   1954     }
   1955 
   1956     static class MemBinder extends Binder {
   1957         ActivityManagerService mActivityManagerService;
   1958         MemBinder(ActivityManagerService activityManagerService) {
   1959             mActivityManagerService = activityManagerService;
   1960         }
   1961 
   1962         @Override
   1963         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   1964             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   1965                     != PackageManager.PERMISSION_GRANTED) {
   1966                 pw.println("Permission Denial: can't dump meminfo from from pid="
   1967                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   1968                         + " without permission " + android.Manifest.permission.DUMP);
   1969                 return;
   1970             }
   1971 
   1972             mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, "  ", args, false, null);
   1973         }
   1974     }
   1975 
   1976     static class GraphicsBinder extends Binder {
   1977         ActivityManagerService mActivityManagerService;
   1978         GraphicsBinder(ActivityManagerService activityManagerService) {
   1979             mActivityManagerService = activityManagerService;
   1980         }
   1981 
   1982         @Override
   1983         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   1984             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   1985                     != PackageManager.PERMISSION_GRANTED) {
   1986                 pw.println("Permission Denial: can't dump gfxinfo from from pid="
   1987                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   1988                         + " without permission " + android.Manifest.permission.DUMP);
   1989                 return;
   1990             }
   1991 
   1992             mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
   1993         }
   1994     }
   1995 
   1996     static class DbBinder extends Binder {
   1997         ActivityManagerService mActivityManagerService;
   1998         DbBinder(ActivityManagerService activityManagerService) {
   1999             mActivityManagerService = activityManagerService;
   2000         }
   2001 
   2002         @Override
   2003         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2004             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2005                     != PackageManager.PERMISSION_GRANTED) {
   2006                 pw.println("Permission Denial: can't dump dbinfo from from pid="
   2007                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2008                         + " without permission " + android.Manifest.permission.DUMP);
   2009                 return;
   2010             }
   2011 
   2012             mActivityManagerService.dumpDbInfo(fd, pw, args);
   2013         }
   2014     }
   2015 
   2016     static class CpuBinder extends Binder {
   2017         ActivityManagerService mActivityManagerService;
   2018         CpuBinder(ActivityManagerService activityManagerService) {
   2019             mActivityManagerService = activityManagerService;
   2020         }
   2021 
   2022         @Override
   2023         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2024             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2025                     != PackageManager.PERMISSION_GRANTED) {
   2026                 pw.println("Permission Denial: can't dump cpuinfo from from pid="
   2027                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2028                         + " without permission " + android.Manifest.permission.DUMP);
   2029                 return;
   2030             }
   2031 
   2032             synchronized (mActivityManagerService.mProcessCpuTracker) {
   2033                 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
   2034                 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
   2035                         SystemClock.uptimeMillis()));
   2036             }
   2037         }
   2038     }
   2039 
   2040     public static final class Lifecycle extends SystemService {
   2041         private final ActivityManagerService mService;
   2042 
   2043         public Lifecycle(Context context) {
   2044             super(context);
   2045             mService = new ActivityManagerService(context);
   2046         }
   2047 
   2048         @Override
   2049         public void onStart() {
   2050             mService.start();
   2051         }
   2052 
   2053         public ActivityManagerService getService() {
   2054             return mService;
   2055         }
   2056     }
   2057 
   2058     // Note: This method is invoked on the main thread but may need to attach various
   2059     // handlers to other threads.  So take care to be explicit about the looper.
   2060     public ActivityManagerService(Context systemContext) {
   2061         mContext = systemContext;
   2062         mFactoryTest = FactoryTest.getMode();
   2063         mSystemThread = ActivityThread.currentActivityThread();
   2064 
   2065         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
   2066 
   2067         mHandlerThread = new ServiceThread(TAG,
   2068                 android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
   2069         mHandlerThread.start();
   2070         mHandler = new MainHandler(mHandlerThread.getLooper());
   2071 
   2072         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
   2073                 "foreground", BROADCAST_FG_TIMEOUT, false);
   2074         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
   2075                 "background", BROADCAST_BG_TIMEOUT, true);
   2076         mBroadcastQueues[0] = mFgBroadcastQueue;
   2077         mBroadcastQueues[1] = mBgBroadcastQueue;
   2078 
   2079         mServices = new ActiveServices(this);
   2080         mProviderMap = new ProviderMap(this);
   2081 
   2082         // TODO: Move creation of battery stats service outside of activity manager service.
   2083         File dataDir = Environment.getDataDirectory();
   2084         File systemDir = new File(dataDir, "system");
   2085         systemDir.mkdirs();
   2086         mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
   2087         mBatteryStatsService.getActiveStatistics().readLocked();
   2088         mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
   2089         mOnBattery = DEBUG_POWER ? true
   2090                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
   2091         mBatteryStatsService.getActiveStatistics().setCallback(this);
   2092 
   2093         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
   2094 
   2095         mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
   2096 
   2097         mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
   2098 
   2099         // User 0 is the first and only user that runs at boot.
   2100         mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
   2101         mUserLru.add(Integer.valueOf(0));
   2102         updateStartedUserArrayLocked();
   2103 
   2104         GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
   2105             ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
   2106 
   2107         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
   2108 
   2109         mConfiguration.setToDefaults();
   2110         mConfiguration.locale = Locale.getDefault();
   2111 
   2112         mConfigurationSeq = mConfiguration.seq = 1;
   2113         mProcessCpuTracker.init();
   2114 
   2115         mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
   2116         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
   2117         mStackSupervisor = new ActivityStackSupervisor(this);
   2118         mTaskPersister = new TaskPersister(systemDir, mStackSupervisor);
   2119 
   2120         mProcessCpuThread = new Thread("CpuTracker") {
   2121             @Override
   2122             public void run() {
   2123                 while (true) {
   2124                     try {
   2125                         try {
   2126                             synchronized(this) {
   2127                                 final long now = SystemClock.uptimeMillis();
   2128                                 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
   2129                                 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
   2130                                 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
   2131                                 //        + ", write delay=" + nextWriteDelay);
   2132                                 if (nextWriteDelay < nextCpuDelay) {
   2133                                     nextCpuDelay = nextWriteDelay;
   2134                                 }
   2135                                 if (nextCpuDelay > 0) {
   2136                                     mProcessCpuMutexFree.set(true);
   2137                                     this.wait(nextCpuDelay);
   2138                                 }
   2139                             }
   2140                         } catch (InterruptedException e) {
   2141                         }
   2142                         updateCpuStatsNow();
   2143                     } catch (Exception e) {
   2144                         Slog.e(TAG, "Unexpected exception collecting process stats", e);
   2145                     }
   2146                 }
   2147             }
   2148         };
   2149 
   2150         Watchdog.getInstance().addMonitor(this);
   2151         Watchdog.getInstance().addThread(mHandler);
   2152     }
   2153 
   2154     public void setSystemServiceManager(SystemServiceManager mgr) {
   2155         mSystemServiceManager = mgr;
   2156     }
   2157 
   2158     public void setInstaller(Installer installer) {
   2159         mInstaller = installer;
   2160     }
   2161 
   2162     private void start() {
   2163         Process.removeAllProcessGroups();
   2164         mProcessCpuThread.start();
   2165 
   2166         mBatteryStatsService.publish(mContext);
   2167         mAppOpsService.publish(mContext);
   2168         Slog.d("AppOps", "AppOpsService published");
   2169         LocalServices.addService(ActivityManagerInternal.class, new LocalService());
   2170     }
   2171 
   2172     public void initPowerManagement() {
   2173         mStackSupervisor.initPowerManagement();
   2174         mBatteryStatsService.initPowerManagement();
   2175     }
   2176 
   2177     @Override
   2178     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
   2179             throws RemoteException {
   2180         if (code == SYSPROPS_TRANSACTION) {
   2181             // We need to tell all apps about the system property change.
   2182             ArrayList<IBinder> procs = new ArrayList<IBinder>();
   2183             synchronized(this) {
   2184                 final int NP = mProcessNames.getMap().size();
   2185                 for (int ip=0; ip<NP; ip++) {
   2186                     SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
   2187                     final int NA = apps.size();
   2188                     for (int ia=0; ia<NA; ia++) {
   2189                         ProcessRecord app = apps.valueAt(ia);
   2190                         if (app.thread != null) {
   2191                             procs.add(app.thread.asBinder());
   2192                         }
   2193                     }
   2194                 }
   2195             }
   2196 
   2197             int N = procs.size();
   2198             for (int i=0; i<N; i++) {
   2199                 Parcel data2 = Parcel.obtain();
   2200                 try {
   2201                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
   2202                 } catch (RemoteException e) {
   2203                 }
   2204                 data2.recycle();
   2205             }
   2206         }
   2207         try {
   2208             return super.onTransact(code, data, reply, flags);
   2209         } catch (RuntimeException e) {
   2210             // The activity manager only throws security exceptions, so let's
   2211             // log all others.
   2212             if (!(e instanceof SecurityException)) {
   2213                 Slog.wtf(TAG, "Activity Manager Crash", e);
   2214             }
   2215             throw e;
   2216         }
   2217     }
   2218 
   2219     void updateCpuStats() {
   2220         final long now = SystemClock.uptimeMillis();
   2221         if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
   2222             return;
   2223         }
   2224         if (mProcessCpuMutexFree.compareAndSet(true, false)) {
   2225             synchronized (mProcessCpuThread) {
   2226                 mProcessCpuThread.notify();
   2227             }
   2228         }
   2229     }
   2230 
   2231     void updateCpuStatsNow() {
   2232         synchronized (mProcessCpuTracker) {
   2233             mProcessCpuMutexFree.set(false);
   2234             final long now = SystemClock.uptimeMillis();
   2235             boolean haveNewCpuStats = false;
   2236 
   2237             if (MONITOR_CPU_USAGE &&
   2238                     mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
   2239                 mLastCpuTime.set(now);
   2240                 haveNewCpuStats = true;
   2241                 mProcessCpuTracker.update();
   2242                 //Slog.i(TAG, mProcessCpu.printCurrentState());
   2243                 //Slog.i(TAG, "Total CPU usage: "
   2244                 //        + mProcessCpu.getTotalCpuPercent() + "%");
   2245 
   2246                 // Slog the cpu usage if the property is set.
   2247                 if ("true".equals(SystemProperties.get("events.cpu"))) {
   2248                     int user = mProcessCpuTracker.getLastUserTime();
   2249                     int system = mProcessCpuTracker.getLastSystemTime();
   2250                     int iowait = mProcessCpuTracker.getLastIoWaitTime();
   2251                     int irq = mProcessCpuTracker.getLastIrqTime();
   2252                     int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
   2253                     int idle = mProcessCpuTracker.getLastIdleTime();
   2254 
   2255                     int total = user + system + iowait + irq + softIrq + idle;
   2256                     if (total == 0) total = 1;
   2257 
   2258                     EventLog.writeEvent(EventLogTags.CPU,
   2259                             ((user+system+iowait+irq+softIrq) * 100) / total,
   2260                             (user * 100) / total,
   2261                             (system * 100) / total,
   2262                             (iowait * 100) / total,
   2263                             (irq * 100) / total,
   2264                             (softIrq * 100) / total);
   2265                 }
   2266             }
   2267 
   2268             long[] cpuSpeedTimes = mProcessCpuTracker.getLastCpuSpeedTimes();
   2269             final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
   2270             synchronized(bstats) {
   2271                 synchronized(mPidsSelfLocked) {
   2272                     if (haveNewCpuStats) {
   2273                         if (mOnBattery) {
   2274                             int perc = bstats.startAddingCpuLocked();
   2275                             int totalUTime = 0;
   2276                             int totalSTime = 0;
   2277                             final int N = mProcessCpuTracker.countStats();
   2278                             for (int i=0; i<N; i++) {
   2279                                 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
   2280                                 if (!st.working) {
   2281                                     continue;
   2282                                 }
   2283                                 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
   2284                                 int otherUTime = (st.rel_utime*perc)/100;
   2285                                 int otherSTime = (st.rel_stime*perc)/100;
   2286                                 totalUTime += otherUTime;
   2287                                 totalSTime += otherSTime;
   2288                                 if (pr != null) {
   2289                                     BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
   2290                                     if (ps == null || !ps.isActive()) {
   2291                                         pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
   2292                                                 pr.info.uid, pr.processName);
   2293                                     }
   2294                                     ps.addCpuTimeLocked(st.rel_utime-otherUTime,
   2295                                             st.rel_stime-otherSTime);
   2296                                     ps.addSpeedStepTimes(cpuSpeedTimes);
   2297                                     pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
   2298                                 } else {
   2299                                     BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
   2300                                     if (ps == null || !ps.isActive()) {
   2301                                         st.batteryStats = ps = bstats.getProcessStatsLocked(
   2302                                                 bstats.mapUid(st.uid), st.name);
   2303                                     }
   2304                                     ps.addCpuTimeLocked(st.rel_utime-otherUTime,
   2305                                             st.rel_stime-otherSTime);
   2306                                     ps.addSpeedStepTimes(cpuSpeedTimes);
   2307                                 }
   2308                             }
   2309                             bstats.finishAddingCpuLocked(perc, totalUTime,
   2310                                     totalSTime, cpuSpeedTimes);
   2311                         }
   2312                     }
   2313                 }
   2314 
   2315                 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
   2316                     mLastWriteTime = now;
   2317                     mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
   2318                 }
   2319             }
   2320         }
   2321     }
   2322 
   2323     @Override
   2324     public void batteryNeedsCpuUpdate() {
   2325         updateCpuStatsNow();
   2326     }
   2327 
   2328     @Override
   2329     public void batteryPowerChanged(boolean onBattery) {
   2330         // When plugging in, update the CPU stats first before changing
   2331         // the plug state.
   2332         updateCpuStatsNow();
   2333         synchronized (this) {
   2334             synchronized(mPidsSelfLocked) {
   2335                 mOnBattery = DEBUG_POWER ? true : onBattery;
   2336             }
   2337         }
   2338     }
   2339 
   2340     /**
   2341      * Initialize the application bind args. These are passed to each
   2342      * process when the bindApplication() IPC is sent to the process. They're
   2343      * lazily setup to make sure the services are running when they're asked for.
   2344      */
   2345     private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
   2346         if (mAppBindArgs == null) {
   2347             mAppBindArgs = new HashMap<>();
   2348 
   2349             // Isolated processes won't get this optimization, so that we don't
   2350             // violate the rules about which services they have access to.
   2351             if (!isolated) {
   2352                 // Setup the application init args
   2353                 mAppBindArgs.put("package", ServiceManager.getService("package"));
   2354                 mAppBindArgs.put("window", ServiceManager.getService("window"));
   2355                 mAppBindArgs.put(Context.ALARM_SERVICE,
   2356                         ServiceManager.getService(Context.ALARM_SERVICE));
   2357             }
   2358         }
   2359         return mAppBindArgs;
   2360     }
   2361 
   2362     final void setFocusedActivityLocked(ActivityRecord r, String reason) {
   2363         if (mFocusedActivity != r) {
   2364             if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedActivityLocked: r=" + r);
   2365             mFocusedActivity = r;
   2366             if (r.task != null && r.task.voiceInteractor != null) {
   2367                 startRunningVoiceLocked();
   2368             } else {
   2369                 finishRunningVoiceLocked();
   2370             }
   2371             mStackSupervisor.setFocusedStack(r, reason + " setFocusedActivity");
   2372             if (r != null) {
   2373                 mWindowManager.setFocusedApp(r.appToken, true);
   2374             }
   2375             applyUpdateLockStateLocked(r);
   2376         }
   2377         EventLog.writeEvent(EventLogTags.AM_FOCUSED_ACTIVITY, mCurrentUserId,
   2378                 mFocusedActivity == null ? "NULL" : mFocusedActivity.shortComponentName);
   2379     }
   2380 
   2381     final void clearFocusedActivity(ActivityRecord r) {
   2382         if (mFocusedActivity == r) {
   2383             mFocusedActivity = null;
   2384         }
   2385     }
   2386 
   2387     @Override
   2388     public void setFocusedStack(int stackId) {
   2389         if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedStack: stackId=" + stackId);
   2390         synchronized (ActivityManagerService.this) {
   2391             ActivityStack stack = mStackSupervisor.getStack(stackId);
   2392             if (stack != null) {
   2393                 ActivityRecord r = stack.topRunningActivityLocked(null);
   2394                 if (r != null) {
   2395                     setFocusedActivityLocked(r, "setFocusedStack");
   2396                 }
   2397             }
   2398         }
   2399     }
   2400 
   2401     /** Sets the task stack listener that gets callbacks when a task stack changes. */
   2402     @Override
   2403     public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException {
   2404         synchronized (ActivityManagerService.this) {
   2405             if (listener != null) {
   2406                 mTaskStackListeners.register(listener);
   2407             }
   2408         }
   2409     }
   2410 
   2411     @Override
   2412     public void notifyActivityDrawn(IBinder token) {
   2413         if (DEBUG_VISBILITY) Slog.d(TAG, "notifyActivityDrawn: token=" + token);
   2414         synchronized (this) {
   2415             ActivityRecord r= mStackSupervisor.isInAnyStackLocked(token);
   2416             if (r != null) {
   2417                 r.task.stack.notifyActivityDrawnLocked(r);
   2418             }
   2419         }
   2420     }
   2421 
   2422     final void applyUpdateLockStateLocked(ActivityRecord r) {
   2423         // Modifications to the UpdateLock state are done on our handler, outside
   2424         // the activity manager's locks.  The new state is determined based on the
   2425         // state *now* of the relevant activity record.  The object is passed to
   2426         // the handler solely for logging detail, not to be consulted/modified.
   2427         final boolean nextState = r != null && r.immersive;
   2428         mHandler.sendMessage(
   2429                 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
   2430     }
   2431 
   2432     final void showAskCompatModeDialogLocked(ActivityRecord r) {
   2433         Message msg = Message.obtain();
   2434         msg.what = SHOW_COMPAT_MODE_DIALOG_MSG;
   2435         msg.obj = r.task.askedCompatMode ? null : r;
   2436         mHandler.sendMessage(msg);
   2437     }
   2438 
   2439     private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index,
   2440             String what, Object obj, ProcessRecord srcApp) {
   2441         app.lastActivityTime = now;
   2442 
   2443         if (app.activities.size() > 0) {
   2444             // Don't want to touch dependent processes that are hosting activities.
   2445             return index;
   2446         }
   2447 
   2448         int lrui = mLruProcesses.lastIndexOf(app);
   2449         if (lrui < 0) {
   2450             Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: "
   2451                     + what + " " + obj + " from " + srcApp);
   2452             return index;
   2453         }
   2454 
   2455         if (lrui >= index) {
   2456             // Don't want to cause this to move dependent processes *back* in the
   2457             // list as if they were less frequently used.
   2458             return index;
   2459         }
   2460 
   2461         if (lrui >= mLruProcessActivityStart) {
   2462             // Don't want to touch dependent processes that are hosting activities.
   2463             return index;
   2464         }
   2465 
   2466         mLruProcesses.remove(lrui);
   2467         if (index > 0) {
   2468             index--;
   2469         }
   2470         if (DEBUG_LRU) Slog.d(TAG, "Moving dep from " + lrui + " to " + index
   2471                 + " in LRU list: " + app);
   2472         mLruProcesses.add(index, app);
   2473         return index;
   2474     }
   2475 
   2476     final void removeLruProcessLocked(ProcessRecord app) {
   2477         int lrui = mLruProcesses.lastIndexOf(app);
   2478         if (lrui >= 0) {
   2479             if (!app.killed) {
   2480                 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app);
   2481                 Process.killProcessQuiet(app.pid);
   2482                 Process.killProcessGroup(app.info.uid, app.pid);
   2483             }
   2484             if (lrui <= mLruProcessActivityStart) {
   2485                 mLruProcessActivityStart--;
   2486             }
   2487             if (lrui <= mLruProcessServiceStart) {
   2488                 mLruProcessServiceStart--;
   2489             }
   2490             mLruProcesses.remove(lrui);
   2491         }
   2492     }
   2493 
   2494     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
   2495             ProcessRecord client) {
   2496         final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities
   2497                 || app.treatLikeActivity;
   2498         final boolean hasService = false; // not impl yet. app.services.size() > 0;
   2499         if (!activityChange && hasActivity) {
   2500             // The process has activities, so we are only allowing activity-based adjustments
   2501             // to move it.  It should be kept in the front of the list with other
   2502             // processes that have activities, and we don't want those to change their
   2503             // order except due to activity operations.
   2504             return;
   2505         }
   2506 
   2507         mLruSeq++;
   2508         final long now = SystemClock.uptimeMillis();
   2509         app.lastActivityTime = now;
   2510 
   2511         // First a quick reject: if the app is already at the position we will
   2512         // put it, then there is nothing to do.
   2513         if (hasActivity) {
   2514             final int N = mLruProcesses.size();
   2515             if (N > 0 && mLruProcesses.get(N-1) == app) {
   2516                 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top activity: " + app);
   2517                 return;
   2518             }
   2519         } else {
   2520             if (mLruProcessServiceStart > 0
   2521                     && mLruProcesses.get(mLruProcessServiceStart-1) == app) {
   2522                 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top other: " + app);
   2523                 return;
   2524             }
   2525         }
   2526 
   2527         int lrui = mLruProcesses.lastIndexOf(app);
   2528 
   2529         if (app.persistent && lrui >= 0) {
   2530             // We don't care about the position of persistent processes, as long as
   2531             // they are in the list.
   2532             if (DEBUG_LRU) Slog.d(TAG, "Not moving, persistent: " + app);
   2533             return;
   2534         }
   2535 
   2536         /* In progress: compute new position first, so we can avoid doing work
   2537            if the process is not actually going to move.  Not yet working.
   2538         int addIndex;
   2539         int nextIndex;
   2540         boolean inActivity = false, inService = false;
   2541         if (hasActivity) {
   2542             // Process has activities, put it at the very tipsy-top.
   2543             addIndex = mLruProcesses.size();
   2544             nextIndex = mLruProcessServiceStart;
   2545             inActivity = true;
   2546         } else if (hasService) {
   2547             // Process has services, put it at the top of the service list.
   2548             addIndex = mLruProcessActivityStart;
   2549             nextIndex = mLruProcessServiceStart;
   2550             inActivity = true;
   2551             inService = true;
   2552         } else  {
   2553             // Process not otherwise of interest, it goes to the top of the non-service area.
   2554             addIndex = mLruProcessServiceStart;
   2555             if (client != null) {
   2556                 int clientIndex = mLruProcesses.lastIndexOf(client);
   2557                 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating "
   2558                         + app);
   2559                 if (clientIndex >= 0 && addIndex > clientIndex) {
   2560                     addIndex = clientIndex;
   2561                 }
   2562             }
   2563             nextIndex = addIndex > 0 ? addIndex-1 : addIndex;
   2564         }
   2565 
   2566         Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act="
   2567                 + mLruProcessActivityStart + "): " + app);
   2568         */
   2569 
   2570         if (lrui >= 0) {
   2571             if (lrui < mLruProcessActivityStart) {
   2572                 mLruProcessActivityStart--;
   2573             }
   2574             if (lrui < mLruProcessServiceStart) {
   2575                 mLruProcessServiceStart--;
   2576             }
   2577             /*
   2578             if (addIndex > lrui) {
   2579                 addIndex--;
   2580             }
   2581             if (nextIndex > lrui) {
   2582                 nextIndex--;
   2583             }
   2584             */
   2585             mLruProcesses.remove(lrui);
   2586         }
   2587 
   2588         /*
   2589         mLruProcesses.add(addIndex, app);
   2590         if (inActivity) {
   2591             mLruProcessActivityStart++;
   2592         }
   2593         if (inService) {
   2594             mLruProcessActivityStart++;
   2595         }
   2596         */
   2597 
   2598         int nextIndex;
   2599         if (hasActivity) {
   2600             final int N = mLruProcesses.size();
   2601             if (app.activities.size() == 0 && mLruProcessActivityStart < (N-1)) {
   2602                 // Process doesn't have activities, but has clients with
   2603                 // activities...  move it up, but one below the top (the top
   2604                 // should always have a real activity).
   2605                 if (DEBUG_LRU) Slog.d(TAG, "Adding to second-top of LRU activity list: " + app);
   2606                 mLruProcesses.add(N-1, app);
   2607                 // To keep it from spamming the LRU list (by making a bunch of clients),
   2608                 // we will push down any other entries owned by the app.
   2609                 final int uid = app.info.uid;
   2610                 for (int i=N-2; i>mLruProcessActivityStart; i--) {
   2611                     ProcessRecord subProc = mLruProcesses.get(i);
   2612                     if (subProc.info.uid == uid) {
   2613                         // We want to push this one down the list.  If the process after
   2614                         // it is for the same uid, however, don't do so, because we don't
   2615                         // want them internally to be re-ordered.
   2616                         if (mLruProcesses.get(i-1).info.uid != uid) {
   2617                             if (DEBUG_LRU) Slog.d(TAG, "Pushing uid " + uid + " swapping at " + i
   2618                                     + ": " + mLruProcesses.get(i) + " : " + mLruProcesses.get(i-1));
   2619                             ProcessRecord tmp = mLruProcesses.get(i);
   2620                             mLruProcesses.set(i, mLruProcesses.get(i-1));
   2621                             mLruProcesses.set(i-1, tmp);
   2622                             i--;
   2623                         }
   2624                     } else {
   2625                         // A gap, we can stop here.
   2626                         break;
   2627                     }
   2628                 }
   2629             } else {
   2630                 // Process has activities, put it at the very tipsy-top.
   2631                 if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU activity list: " + app);
   2632                 mLruProcesses.add(app);
   2633             }
   2634             nextIndex = mLruProcessServiceStart;
   2635         } else if (hasService) {
   2636             // Process has services, put it at the top of the service list.
   2637             if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU service list: " + app);
   2638             mLruProcesses.add(mLruProcessActivityStart, app);
   2639             nextIndex = mLruProcessServiceStart;
   2640             mLruProcessActivityStart++;
   2641         } else  {
   2642             // Process not otherwise of interest, it goes to the top of the non-service area.
   2643             int index = mLruProcessServiceStart;
   2644             if (client != null) {
   2645                 // If there is a client, don't allow the process to be moved up higher
   2646                 // in the list than that client.
   2647                 int clientIndex = mLruProcesses.lastIndexOf(client);
   2648                 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG, "Unknown client " + client
   2649                         + " when updating " + app);
   2650                 if (clientIndex <= lrui) {
   2651                     // Don't allow the client index restriction to push it down farther in the
   2652                     // list than it already is.
   2653                     clientIndex = lrui;
   2654                 }
   2655                 if (clientIndex >= 0 && index > clientIndex) {
   2656                     index = clientIndex;
   2657                 }
   2658             }
   2659             if (DEBUG_LRU) Slog.d(TAG, "Adding at " + index + " of LRU list: " + app);
   2660             mLruProcesses.add(index, app);
   2661             nextIndex = index-1;
   2662             mLruProcessActivityStart++;
   2663             mLruProcessServiceStart++;
   2664         }
   2665 
   2666         // If the app is currently using a content provider or service,
   2667         // bump those processes as well.
   2668         for (int j=app.connections.size()-1; j>=0; j--) {
   2669             ConnectionRecord cr = app.connections.valueAt(j);
   2670             if (cr.binding != null && !cr.serviceDead && cr.binding.service != null
   2671                     && cr.binding.service.app != null
   2672                     && cr.binding.service.app.lruSeq != mLruSeq
   2673                     && !cr.binding.service.app.persistent) {
   2674                 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex,
   2675                         "service connection", cr, app);
   2676             }
   2677         }
   2678         for (int j=app.conProviders.size()-1; j>=0; j--) {
   2679             ContentProviderRecord cpr = app.conProviders.get(j).provider;
   2680             if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) {
   2681                 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex,
   2682                         "provider reference", cpr, app);
   2683             }
   2684         }
   2685     }
   2686 
   2687     final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
   2688         if (uid == Process.SYSTEM_UID) {
   2689             // The system gets to run in any process.  If there are multiple
   2690             // processes with the same uid, just pick the first (this
   2691             // should never happen).
   2692             SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName);
   2693             if (procs == null) return null;
   2694             final int procCount = procs.size();
   2695             for (int i = 0; i < procCount; i++) {
   2696                 final int procUid = procs.keyAt(i);
   2697                 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
   2698                     // Don't use an app process or different user process for system component.
   2699                     continue;
   2700                 }
   2701                 return procs.valueAt(i);
   2702             }
   2703         }
   2704         ProcessRecord proc = mProcessNames.get(processName, uid);
   2705         if (false && proc != null && !keepIfLarge
   2706                 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY
   2707                 && proc.lastCachedPss >= 4000) {
   2708             // Turn this condition on to cause killing to happen regularly, for testing.
   2709             if (proc.baseProcessTracker != null) {
   2710                 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
   2711             }
   2712             proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
   2713         } else if (proc != null && !keepIfLarge
   2714                 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
   2715                 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
   2716             if (DEBUG_PSS) Slog.d(TAG, "May not keep " + proc + ": pss=" + proc.lastCachedPss);
   2717             if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) {
   2718                 if (proc.baseProcessTracker != null) {
   2719                     proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
   2720                 }
   2721                 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
   2722             }
   2723         }
   2724         return proc;
   2725     }
   2726 
   2727     void ensurePackageDexOpt(String packageName) {
   2728         IPackageManager pm = AppGlobals.getPackageManager();
   2729         try {
   2730             if (pm.performDexOptIfNeeded(packageName, null /* instruction set */)) {
   2731                 mDidDexOpt = true;
   2732             }
   2733         } catch (RemoteException e) {
   2734         }
   2735     }
   2736 
   2737     boolean isNextTransitionForward() {
   2738         int transit = mWindowManager.getPendingAppTransition();
   2739         return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
   2740                 || transit == AppTransition.TRANSIT_TASK_OPEN
   2741                 || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
   2742     }
   2743 
   2744     int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
   2745             String processName, String abiOverride, int uid, Runnable crashHandler) {
   2746         synchronized(this) {
   2747             ApplicationInfo info = new ApplicationInfo();
   2748             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
   2749             // For isolated processes, the former contains the parent's uid and the latter the
   2750             // actual uid of the isolated process.
   2751             // In the special case introduced by this method (which is, starting an isolated
   2752             // process directly from the SystemServer without an actual parent app process) the
   2753             // closest thing to a parent's uid is SYSTEM_UID.
   2754             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
   2755             // the |isolated| logic in the ProcessRecord constructor.
   2756             info.uid = Process.SYSTEM_UID;
   2757             info.processName = processName;
   2758             info.className = entryPoint;
   2759             info.packageName = "android";
   2760             ProcessRecord proc = startProcessLocked(processName, info /* info */,
   2761                     false /* knownToBeDead */, 0 /* intentFlags */, ""  /* hostingType */,
   2762                     null /* hostingName */, true /* allowWhileBooting */, true /* isolated */,
   2763                     uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
   2764                     crashHandler);
   2765             return proc != null ? proc.pid : 0;
   2766         }
   2767     }
   2768 
   2769     final ProcessRecord startProcessLocked(String processName,
   2770             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
   2771             String hostingType, ComponentName hostingName, boolean allowWhileBooting,
   2772             boolean isolated, boolean keepIfLarge) {
   2773         return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
   2774                 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
   2775                 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
   2776                 null /* crashHandler */);
   2777     }
   2778 
   2779     final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
   2780             boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
   2781             boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
   2782             String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
   2783         long startTime = SystemClock.elapsedRealtime();
   2784         ProcessRecord app;
   2785         if (!isolated) {
   2786             app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
   2787             checkTime(startTime, "startProcess: after getProcessRecord");
   2788         } else {
   2789             // If this is an isolated process, it can't re-use an existing process.
   2790             app = null;
   2791         }
   2792         // We don't have to do anything more if:
   2793         // (1) There is an existing application record; and
   2794         // (2) The caller doesn't think it is dead, OR there is no thread
   2795         //     object attached to it so we know it couldn't have crashed; and
   2796         // (3) There is a pid assigned to it, so it is either starting or
   2797         //     already running.
   2798         if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
   2799                 + " app=" + app + " knownToBeDead=" + knownToBeDead
   2800                 + " thread=" + (app != null ? app.thread : null)
   2801                 + " pid=" + (app != null ? app.pid : -1));
   2802         if (app != null && app.pid > 0) {
   2803             if (!knownToBeDead || app.thread == null) {
   2804                 // We already have the app running, or are waiting for it to
   2805                 // come up (we have a pid but not yet its thread), so keep it.
   2806                 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
   2807                 // If this is a new package in the process, add the package to the list
   2808                 app.addPackage(info.packageName, info.versionCode, mProcessStats);
   2809                 checkTime(startTime, "startProcess: done, added package to proc");
   2810                 return app;
   2811             }
   2812 
   2813             // An application record is attached to a previous process,
   2814             // clean it up now.
   2815             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
   2816             checkTime(startTime, "startProcess: bad proc running, killing");
   2817             Process.killProcessGroup(app.info.uid, app.pid);
   2818             handleAppDiedLocked(app, true, true);
   2819             checkTime(startTime, "startProcess: done killing old proc");
   2820         }
   2821 
   2822         String hostingNameStr = hostingName != null
   2823                 ? hostingName.flattenToShortString() : null;
   2824 
   2825         if (!isolated) {
   2826             if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
   2827                 // If we are in the background, then check to see if this process
   2828                 // is bad.  If so, we will just silently fail.
   2829                 if (mBadProcesses.get(info.processName, info.uid) != null) {
   2830                     if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
   2831                             + "/" + info.processName);
   2832                     return null;
   2833                 }
   2834             } else {
   2835                 // When the user is explicitly starting a process, then clear its
   2836                 // crash count so that we won't make it bad until they see at
   2837                 // least one crash dialog again, and make the process good again
   2838                 // if it had been bad.
   2839                 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
   2840                         + "/" + info.processName);
   2841                 mProcessCrashTimes.remove(info.processName, info.uid);
   2842                 if (mBadProcesses.get(info.processName, info.uid) != null) {
   2843                     EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
   2844                             UserHandle.getUserId(info.uid), info.uid,
   2845                             info.processName);
   2846                     mBadProcesses.remove(info.processName, info.uid);
   2847                     if (app != null) {
   2848                         app.bad = false;
   2849                     }
   2850                 }
   2851             }
   2852         }
   2853 
   2854         if (app == null) {
   2855             checkTime(startTime, "startProcess: creating new process record");
   2856             app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
   2857             if (app == null) {
   2858                 Slog.w(TAG, "Failed making new process record for "
   2859                         + processName + "/" + info.uid + " isolated=" + isolated);
   2860                 return null;
   2861             }
   2862             app.crashHandler = crashHandler;
   2863             mProcessNames.put(processName, app.uid, app);
   2864             if (isolated) {
   2865                 mIsolatedProcesses.put(app.uid, app);
   2866             }
   2867             checkTime(startTime, "startProcess: done creating new process record");
   2868         } else {
   2869             // If this is a new package in the process, add the package to the list
   2870             app.addPackage(info.packageName, info.versionCode, mProcessStats);
   2871             checkTime(startTime, "startProcess: added package to existing proc");
   2872         }
   2873 
   2874         // If the system is not ready yet, then hold off on starting this
   2875         // process until it is.
   2876         if (!mProcessesReady
   2877                 && !isAllowedWhileBooting(info)
   2878                 && !allowWhileBooting) {
   2879             if (!mProcessesOnHold.contains(app)) {
   2880                 mProcessesOnHold.add(app);
   2881             }
   2882             if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
   2883             checkTime(startTime, "startProcess: returning with proc on hold");
   2884             return app;
   2885         }
   2886 
   2887         checkTime(startTime, "startProcess: stepping in to startProcess");
   2888         startProcessLocked(
   2889                 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
   2890         checkTime(startTime, "startProcess: done starting proc!");
   2891         return (app.pid != 0) ? app : null;
   2892     }
   2893 
   2894     boolean isAllowedWhileBooting(ApplicationInfo ai) {
   2895         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
   2896     }
   2897 
   2898     private final void startProcessLocked(ProcessRecord app,
   2899             String hostingType, String hostingNameStr) {
   2900         startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */,
   2901                 null /* entryPoint */, null /* entryPointArgs */);
   2902     }
   2903 
   2904     private final void startProcessLocked(ProcessRecord app, String hostingType,
   2905             String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
   2906         long startTime = SystemClock.elapsedRealtime();
   2907         if (app.pid > 0 && app.pid != MY_PID) {
   2908             checkTime(startTime, "startProcess: removing from pids map");
   2909             synchronized (mPidsSelfLocked) {
   2910                 mPidsSelfLocked.remove(app.pid);
   2911                 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
   2912             }
   2913             checkTime(startTime, "startProcess: done removing from pids map");
   2914             app.setPid(0);
   2915         }
   2916 
   2917         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
   2918                 "startProcessLocked removing on hold: " + app);
   2919         mProcessesOnHold.remove(app);
   2920 
   2921         checkTime(startTime, "startProcess: starting to update cpu stats");
   2922         updateCpuStats();
   2923         checkTime(startTime, "startProcess: done updating cpu stats");
   2924 
   2925         try {
   2926             int uid = app.uid;
   2927 
   2928             int[] gids = null;
   2929             int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
   2930             if (!app.isolated) {
   2931                 int[] permGids = null;
   2932                 try {
   2933                     checkTime(startTime, "startProcess: getting gids from package manager");
   2934                     final PackageManager pm = mContext.getPackageManager();
   2935                     permGids = pm.getPackageGids(app.info.packageName);
   2936 
   2937                     if (Environment.isExternalStorageEmulated()) {
   2938                         checkTime(startTime, "startProcess: checking external storage perm");
   2939                         if (pm.checkPermission(
   2940                                 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
   2941                                 app.info.packageName) == PERMISSION_GRANTED) {
   2942                             mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
   2943                         } else {
   2944                             mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
   2945                         }
   2946                     }
   2947                 } catch (PackageManager.NameNotFoundException e) {
   2948                     Slog.w(TAG, "Unable to retrieve gids", e);
   2949                 }
   2950 
   2951                 /*
   2952                  * Add shared application and profile GIDs so applications can share some
   2953                  * resources like shared libraries and access user-wide resources
   2954                  */
   2955                 if (permGids == null) {
   2956                     gids = new int[2];
   2957                 } else {
   2958                     gids = new int[permGids.length + 2];
   2959                     System.arraycopy(permGids, 0, gids, 2, permGids.length);
   2960                 }
   2961                 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
   2962                 gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));
   2963             }
   2964             checkTime(startTime, "startProcess: building args");
   2965             if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) {
   2966                 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
   2967                         && mTopComponent != null
   2968                         && app.processName.equals(mTopComponent.getPackageName())) {
   2969                     uid = 0;
   2970                 }
   2971                 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL
   2972                         && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
   2973                     uid = 0;
   2974                 }
   2975             }
   2976             int debugFlags = 0;
   2977             if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
   2978                 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
   2979                 // Also turn on CheckJNI for debuggable apps. It's quite
   2980                 // awkward to turn on otherwise.
   2981                 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
   2982             }
   2983             // Run the app in safe mode if its manifest requests so or the
   2984             // system is booted in safe mode.
   2985             if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
   2986                 mSafeMode == true) {
   2987                 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
   2988             }
   2989             if ("1".equals(SystemProperties.get("debug.checkjni"))) {
   2990                 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
   2991             }
   2992             if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
   2993                 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
   2994             }
   2995             if ("1".equals(SystemProperties.get("debug.assert"))) {
   2996                 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
   2997             }
   2998 
   2999             String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
   3000             if (requiredAbi == null) {
   3001                 requiredAbi = Build.SUPPORTED_ABIS[0];
   3002             }
   3003 
   3004             String instructionSet = null;
   3005             if (app.info.primaryCpuAbi != null) {
   3006                 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
   3007             }
   3008 
   3009             app.gids = gids;
   3010             app.requiredAbi = requiredAbi;
   3011             app.instructionSet = instructionSet;
   3012 
   3013             // Start the process.  It will either succeed and return a result containing
   3014             // the PID of the new process, or else throw a RuntimeException.
   3015             boolean isActivityProcess = (entryPoint == null);
   3016             if (entryPoint == null) entryPoint = "android.app.ActivityThread";
   3017             checkTime(startTime, "startProcess: asking zygote to start proc");
   3018             Process.ProcessStartResult startResult = Process.start(entryPoint,
   3019                     app.processName, uid, uid, gids, debugFlags, mountExternal,
   3020                     app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
   3021                     app.info.dataDir, entryPointArgs);
   3022             checkTime(startTime, "startProcess: returned from zygote!");
   3023 
   3024             if (app.isolated) {
   3025                 mBatteryStatsService.addIsolatedUid(app.uid, app.info.uid);
   3026             }
   3027             mBatteryStatsService.noteProcessStart(app.processName, app.info.uid);
   3028             checkTime(startTime, "startProcess: done updating battery stats");
   3029 
   3030             EventLog.writeEvent(EventLogTags.AM_PROC_START,
   3031                     UserHandle.getUserId(uid), startResult.pid, uid,
   3032                     app.processName, hostingType,
   3033                     hostingNameStr != null ? hostingNameStr : "");
   3034 
   3035             if (app.persistent) {
   3036                 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
   3037             }
   3038 
   3039             checkTime(startTime, "startProcess: building log message");
   3040             StringBuilder buf = mStringBuilder;
   3041             buf.setLength(0);
   3042             buf.append("Start proc ");
   3043             buf.append(startResult.pid);
   3044             buf.append(':');
   3045             buf.append(app.processName);
   3046             buf.append('/');
   3047             UserHandle.formatUid(buf, uid);
   3048             if (!isActivityProcess) {
   3049                 buf.append(" [");
   3050                 buf.append(entryPoint);
   3051                 buf.append("]");
   3052             }
   3053             buf.append(" for ");
   3054             buf.append(hostingType);
   3055             if (hostingNameStr != null) {
   3056                 buf.append(" ");
   3057                 buf.append(hostingNameStr);
   3058             }
   3059             Slog.i(TAG, buf.toString());
   3060             app.setPid(startResult.pid);
   3061             app.usingWrapper = startResult.usingWrapper;
   3062             app.removed = false;
   3063             app.killed = false;
   3064             app.killedByAm = false;
   3065             checkTime(startTime, "startProcess: starting to update pids map");
   3066             synchronized (mPidsSelfLocked) {
   3067                 this.mPidsSelfLocked.put(startResult.pid, app);
   3068                 if (isActivityProcess) {
   3069                     Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
   3070                     msg.obj = app;
   3071                     mHandler.sendMessageDelayed(msg, startResult.usingWrapper
   3072                             ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
   3073                 }
   3074             }
   3075             checkTime(startTime, "startProcess: done updating pids map");
   3076         } catch (RuntimeException e) {
   3077             // XXX do better error recovery.
   3078             app.setPid(0);
   3079             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
   3080             if (app.isolated) {
   3081                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
   3082             }
   3083             Slog.e(TAG, "Failure starting process " + app.processName, e);
   3084         }
   3085     }
   3086 
   3087     void updateUsageStats(ActivityRecord component, boolean resumed) {
   3088         if (DEBUG_SWITCH) Slog.d(TAG, "updateUsageStats: comp=" + component + "res=" + resumed);
   3089         final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
   3090         if (resumed) {
   3091             if (mUsageStatsService != null) {
   3092                 mUsageStatsService.reportEvent(component.realActivity, component.userId,
   3093                         UsageEvents.Event.MOVE_TO_FOREGROUND);
   3094             }
   3095             synchronized (stats) {
   3096                 stats.noteActivityResumedLocked(component.app.uid);
   3097             }
   3098         } else {
   3099             if (mUsageStatsService != null) {
   3100                 mUsageStatsService.reportEvent(component.realActivity, component.userId,
   3101                         UsageEvents.Event.MOVE_TO_BACKGROUND);
   3102             }
   3103             synchronized (stats) {
   3104                 stats.noteActivityPausedLocked(component.app.uid);
   3105             }
   3106         }
   3107     }
   3108 
   3109     Intent getHomeIntent() {
   3110         Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
   3111         intent.setComponent(mTopComponent);
   3112         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
   3113             intent.addCategory(Intent.CATEGORY_HOME);
   3114         }
   3115         return intent;
   3116     }
   3117 
   3118     boolean startHomeActivityLocked(int userId, String reason) {
   3119         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
   3120                 && mTopAction == null) {
   3121             // We are running in factory test mode, but unable to find
   3122             // the factory test app, so just sit around displaying the
   3123             // error message and don't try to start anything.
   3124             return false;
   3125         }
   3126         Intent intent = getHomeIntent();
   3127         ActivityInfo aInfo =
   3128             resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
   3129         if (aInfo != null) {
   3130             intent.setComponent(new ComponentName(
   3131                     aInfo.applicationInfo.packageName, aInfo.name));
   3132             // Don't do this if the home app is currently being
   3133             // instrumented.
   3134             aInfo = new ActivityInfo(aInfo);
   3135             aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
   3136             ProcessRecord app = getProcessRecordLocked(aInfo.processName,
   3137                     aInfo.applicationInfo.uid, true);
   3138             if (app == null || app.instrumentationClass == null) {
   3139                 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
   3140                 mStackSupervisor.startHomeActivity(intent, aInfo, reason);
   3141             }
   3142         }
   3143 
   3144         return true;
   3145     }
   3146 
   3147     private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
   3148         ActivityInfo ai = null;
   3149         ComponentName comp = intent.getComponent();
   3150         try {
   3151             if (comp != null) {
   3152                 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
   3153             } else {
   3154                 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
   3155                         intent,
   3156                         intent.resolveTypeIfNeeded(mContext.getContentResolver()),
   3157                             flags, userId);
   3158 
   3159                 if (info != null) {
   3160                     ai = info.activityInfo;
   3161                 }
   3162             }
   3163         } catch (RemoteException e) {
   3164             // ignore
   3165         }
   3166 
   3167         return ai;
   3168     }
   3169 
   3170     /**
   3171      * Starts the "new version setup screen" if appropriate.
   3172      */
   3173     void startSetupActivityLocked() {
   3174         // Only do this once per boot.
   3175         if (mCheckedForSetup) {
   3176             return;
   3177         }
   3178 
   3179         // We will show this screen if the current one is a different
   3180         // version than the last one shown, and we are not running in
   3181         // low-level factory test mode.
   3182         final ContentResolver resolver = mContext.getContentResolver();
   3183         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL &&
   3184                 Settings.Global.getInt(resolver,
   3185                         Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
   3186             mCheckedForSetup = true;
   3187 
   3188             // See if we should be showing the platform update setup UI.
   3189             Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
   3190             List<ResolveInfo> ris = mContext.getPackageManager()
   3191                     .queryIntentActivities(intent, PackageManager.GET_META_DATA);
   3192 
   3193             // We don't allow third party apps to replace this.
   3194             ResolveInfo ri = null;
   3195             for (int i=0; ris != null && i<ris.size(); i++) {
   3196                 if ((ris.get(i).activityInfo.applicationInfo.flags
   3197                         & ApplicationInfo.FLAG_SYSTEM) != 0) {
   3198                     ri = ris.get(i);
   3199                     break;
   3200                 }
   3201             }
   3202 
   3203             if (ri != null) {
   3204                 String vers = ri.activityInfo.metaData != null
   3205                         ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
   3206                         : null;
   3207                 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
   3208                     vers = ri.activityInfo.applicationInfo.metaData.getString(
   3209                             Intent.METADATA_SETUP_VERSION);
   3210                 }
   3211                 String lastVers = Settings.Secure.getString(
   3212                         resolver, Settings.Secure.LAST_SETUP_SHOWN);
   3213                 if (vers != null && !vers.equals(lastVers)) {
   3214                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   3215                     intent.setComponent(new ComponentName(
   3216                             ri.activityInfo.packageName, ri.activityInfo.name));
   3217                     mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo,
   3218                             null, null, null, null, 0, 0, 0, null, 0, 0, 0, null, false, null, null,
   3219                             null);
   3220                 }
   3221             }
   3222         }
   3223     }
   3224 
   3225     CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
   3226         return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
   3227     }
   3228 
   3229     void enforceNotIsolatedCaller(String caller) {
   3230         if (UserHandle.isIsolated(Binder.getCallingUid())) {
   3231             throw new SecurityException("Isolated process not allowed to call " + caller);
   3232         }
   3233     }
   3234 
   3235     void enforceShellRestriction(String restriction, int userHandle) {
   3236         if (Binder.getCallingUid() == Process.SHELL_UID) {
   3237             if (userHandle < 0
   3238                     || mUserManager.hasUserRestriction(restriction, userHandle)) {
   3239                 throw new SecurityException("Shell does not have permission to access user "
   3240                         + userHandle);
   3241             }
   3242         }
   3243     }
   3244 
   3245     @Override
   3246     public int getFrontActivityScreenCompatMode() {
   3247         enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
   3248         synchronized (this) {
   3249             return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
   3250         }
   3251     }
   3252 
   3253     @Override
   3254     public void setFrontActivityScreenCompatMode(int mode) {
   3255         enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
   3256                 "setFrontActivityScreenCompatMode");
   3257         synchronized (this) {
   3258             mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
   3259         }
   3260     }
   3261 
   3262     @Override
   3263     public int getPackageScreenCompatMode(String packageName) {
   3264         enforceNotIsolatedCaller("getPackageScreenCompatMode");
   3265         synchronized (this) {
   3266             return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
   3267         }
   3268     }
   3269 
   3270     @Override
   3271     public void setPackageScreenCompatMode(String packageName, int mode) {
   3272         enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
   3273                 "setPackageScreenCompatMode");
   3274         synchronized (this) {
   3275             mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
   3276         }
   3277     }
   3278 
   3279     @Override
   3280     public boolean getPackageAskScreenCompat(String packageName) {
   3281         enforceNotIsolatedCaller("getPackageAskScreenCompat");
   3282         synchronized (this) {
   3283             return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
   3284         }
   3285     }
   3286 
   3287     @Override
   3288     public void setPackageAskScreenCompat(String packageName, boolean ask) {
   3289         enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
   3290                 "setPackageAskScreenCompat");
   3291         synchronized (this) {
   3292             mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
   3293         }
   3294     }
   3295 
   3296     private void dispatchProcessesChanged() {
   3297         int N;
   3298         synchronized (this) {
   3299             N = mPendingProcessChanges.size();
   3300             if (mActiveProcessChanges.length < N) {
   3301                 mActiveProcessChanges = new ProcessChangeItem[N];
   3302             }
   3303             mPendingProcessChanges.toArray(mActiveProcessChanges);
   3304             mAvailProcessChanges.addAll(mPendingProcessChanges);
   3305             mPendingProcessChanges.clear();
   3306             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
   3307         }
   3308 
   3309         int i = mProcessObservers.beginBroadcast();
   3310         while (i > 0) {
   3311             i--;
   3312             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
   3313             if (observer != null) {
   3314                 try {
   3315                     for (int j=0; j<N; j++) {
   3316                         ProcessChangeItem item = mActiveProcessChanges[j];
   3317                         if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
   3318                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
   3319                                     + item.pid + " uid=" + item.uid + ": "
   3320                                     + item.foregroundActivities);
   3321                             observer.onForegroundActivitiesChanged(item.pid, item.uid,
   3322                                     item.foregroundActivities);
   3323                         }
   3324                         if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) {
   3325                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "PROCSTATE CHANGED pid="
   3326                                     + item.pid + " uid=" + item.uid + ": " + item.processState);
   3327                             observer.onProcessStateChanged(item.pid, item.uid, item.processState);
   3328                         }
   3329                     }
   3330                 } catch (RemoteException e) {
   3331                 }
   3332             }
   3333         }
   3334         mProcessObservers.finishBroadcast();
   3335     }
   3336 
   3337     private void dispatchProcessDied(int pid, int uid) {
   3338         int i = mProcessObservers.beginBroadcast();
   3339         while (i > 0) {
   3340             i--;
   3341             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
   3342             if (observer != null) {
   3343                 try {
   3344                     observer.onProcessDied(pid, uid);
   3345                 } catch (RemoteException e) {
   3346                 }
   3347             }
   3348         }
   3349         mProcessObservers.finishBroadcast();
   3350     }
   3351 
   3352     @Override
   3353     public final int startActivity(IApplicationThread caller, String callingPackage,
   3354             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   3355             int startFlags, ProfilerInfo profilerInfo, Bundle options) {
   3356         return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
   3357             resultWho, requestCode, startFlags, profilerInfo, options,
   3358             UserHandle.getCallingUserId());
   3359     }
   3360 
   3361     @Override
   3362     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
   3363             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   3364             int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
   3365         enforceNotIsolatedCaller("startActivity");
   3366         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
   3367                 false, ALLOW_FULL_ONLY, "startActivity", null);
   3368         // TODO: Switch to user app stacks here.
   3369         return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
   3370                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
   3371                 profilerInfo, null, null, options, userId, null, null);
   3372     }
   3373 
   3374     @Override
   3375     public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
   3376             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   3377             int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
   3378 
   3379         // This is very dangerous -- it allows you to perform a start activity (including
   3380         // permission grants) as any app that may launch one of your own activities.  So
   3381         // we will only allow this to be done from activities that are part of the core framework,
   3382         // and then only when they are running as the system.
   3383         final ActivityRecord sourceRecord;
   3384         final int targetUid;
   3385         final String targetPackage;
   3386         synchronized (this) {
   3387             if (resultTo == null) {
   3388                 throw new SecurityException("Must be called from an activity");
   3389             }
   3390             sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
   3391             if (sourceRecord == null) {
   3392                 throw new SecurityException("Called with bad activity token: " + resultTo);
   3393             }
   3394             if (!sourceRecord.info.packageName.equals("android")) {
   3395                 throw new SecurityException(
   3396                         "Must be called from an activity that is declared in the android package");
   3397             }
   3398             if (sourceRecord.app == null) {
   3399                 throw new SecurityException("Called without a process attached to activity");
   3400             }
   3401             if (UserHandle.getAppId(sourceRecord.app.uid) != Process.SYSTEM_UID) {
   3402                 // This is still okay, as long as this activity is running under the
   3403                 // uid of the original calling activity.
   3404                 if (sourceRecord.app.uid != sourceRecord.launchedFromUid) {
   3405                     throw new SecurityException(
   3406                             "Calling activity in uid " + sourceRecord.app.uid
   3407                                     + " must be system uid or original calling uid "
   3408                                     + sourceRecord.launchedFromUid);
   3409                 }
   3410             }
   3411             targetUid = sourceRecord.launchedFromUid;
   3412             targetPackage = sourceRecord.launchedFromPackage;
   3413         }
   3414 
   3415         if (userId == UserHandle.USER_NULL) {
   3416             userId = UserHandle.getUserId(sourceRecord.app.uid);
   3417         }
   3418 
   3419         // TODO: Switch to user app stacks here.
   3420         try {
   3421             int ret = mStackSupervisor.startActivityMayWait(null, targetUid, targetPackage, intent,
   3422                     resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null,
   3423                     null, null, options, userId, null, null);
   3424             return ret;
   3425         } catch (SecurityException e) {
   3426             // XXX need to figure out how to propagate to original app.
   3427             // A SecurityException here is generally actually a fault of the original
   3428             // calling activity (such as a fairly granting permissions), so propagate it
   3429             // back to them.
   3430             /*
   3431             StringBuilder msg = new StringBuilder();
   3432             msg.append("While launching");
   3433             msg.append(intent.toString());
   3434             msg.append(": ");
   3435             msg.append(e.getMessage());
   3436             */
   3437             throw e;
   3438         }
   3439     }
   3440 
   3441     @Override
   3442     public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
   3443             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   3444             int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
   3445         enforceNotIsolatedCaller("startActivityAndWait");
   3446         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
   3447                 false, ALLOW_FULL_ONLY, "startActivityAndWait", null);
   3448         WaitResult res = new WaitResult();
   3449         // TODO: Switch to user app stacks here.
   3450         mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
   3451                 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null,
   3452                 options, userId, null, null);
   3453         return res;
   3454     }
   3455 
   3456     @Override
   3457     public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
   3458             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   3459             int startFlags, Configuration config, Bundle options, int userId) {
   3460         enforceNotIsolatedCaller("startActivityWithConfig");
   3461         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
   3462                 false, ALLOW_FULL_ONLY, "startActivityWithConfig", null);
   3463         // TODO: Switch to user app stacks here.
   3464         int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
   3465                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
   3466                 null, null, config, options, userId, null, null);
   3467         return ret;
   3468     }
   3469 
   3470     @Override
   3471     public int startActivityIntentSender(IApplicationThread caller,
   3472             IntentSender intent, Intent fillInIntent, String resolvedType,
   3473             IBinder resultTo, String resultWho, int requestCode,
   3474             int flagsMask, int flagsValues, Bundle options) {
   3475         enforceNotIsolatedCaller("startActivityIntentSender");
   3476         // Refuse possible leaked file descriptors
   3477         if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
   3478             throw new IllegalArgumentException("File descriptors passed in Intent");
   3479         }
   3480 
   3481         IIntentSender sender = intent.getTarget();
   3482         if (!(sender instanceof PendingIntentRecord)) {
   3483             throw new IllegalArgumentException("Bad PendingIntent object");
   3484         }
   3485 
   3486         PendingIntentRecord pir = (PendingIntentRecord)sender;
   3487 
   3488         synchronized (this) {
   3489             // If this is coming from the currently resumed activity, it is
   3490             // effectively saying that app switches are allowed at this point.
   3491             final ActivityStack stack = getFocusedStack();
   3492             if (stack.mResumedActivity != null &&
   3493                     stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
   3494                 mAppSwitchesAllowedTime = 0;
   3495             }
   3496         }
   3497         int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
   3498                 resultTo, resultWho, requestCode, flagsMask, flagsValues, options, null);
   3499         return ret;
   3500     }
   3501 
   3502     @Override
   3503     public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
   3504             Intent intent, String resolvedType, IVoiceInteractionSession session,
   3505             IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
   3506             Bundle options, int userId) {
   3507         if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION)
   3508                 != PackageManager.PERMISSION_GRANTED) {
   3509             String msg = "Permission Denial: startVoiceActivity() from pid="
   3510                     + Binder.getCallingPid()
   3511                     + ", uid=" + Binder.getCallingUid()
   3512                     + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION;
   3513             Slog.w(TAG, msg);
   3514             throw new SecurityException(msg);
   3515         }
   3516         if (session == null || interactor == null) {
   3517             throw new NullPointerException("null session or interactor");
   3518         }
   3519         userId = handleIncomingUser(callingPid, callingUid, userId,
   3520                 false, ALLOW_FULL_ONLY, "startVoiceActivity", null);
   3521         // TODO: Switch to user app stacks here.
   3522         return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent,
   3523                 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null,
   3524                 null, options, userId, null, null);
   3525     }
   3526 
   3527     @Override
   3528     public boolean startNextMatchingActivity(IBinder callingActivity,
   3529             Intent intent, Bundle options) {
   3530         // Refuse possible leaked file descriptors
   3531         if (intent != null && intent.hasFileDescriptors() == true) {
   3532             throw new IllegalArgumentException("File descriptors passed in Intent");
   3533         }
   3534 
   3535         synchronized (this) {
   3536             final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
   3537             if (r == null) {
   3538                 ActivityOptions.abort(options);
   3539                 return false;
   3540             }
   3541             if (r.app == null || r.app.thread == null) {
   3542                 // The caller is not running...  d'oh!
   3543                 ActivityOptions.abort(options);
   3544                 return false;
   3545             }
   3546             intent = new Intent(intent);
   3547             // The caller is not allowed to change the data.
   3548             intent.setDataAndType(r.intent.getData(), r.intent.getType());
   3549             // And we are resetting to find the next component...
   3550             intent.setComponent(null);
   3551 
   3552             final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
   3553 
   3554             ActivityInfo aInfo = null;
   3555             try {
   3556                 List<ResolveInfo> resolves =
   3557                     AppGlobals.getPackageManager().queryIntentActivities(
   3558                             intent, r.resolvedType,
   3559                             PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
   3560                             UserHandle.getCallingUserId());
   3561 
   3562                 // Look for the original activity in the list...
   3563                 final int N = resolves != null ? resolves.size() : 0;
   3564                 for (int i=0; i<N; i++) {
   3565                     ResolveInfo rInfo = resolves.get(i);
   3566                     if (rInfo.activityInfo.packageName.equals(r.packageName)
   3567                             && rInfo.activityInfo.name.equals(r.info.name)) {
   3568                         // We found the current one...  the next matching is
   3569                         // after it.
   3570                         i++;
   3571                         if (i<N) {
   3572                             aInfo = resolves.get(i).activityInfo;
   3573                         }
   3574                         if (debug) {
   3575                             Slog.v(TAG, "Next matching activity: found current " + r.packageName
   3576                                     + "/" + r.info.name);
   3577                             Slog.v(TAG, "Next matching activity: next is " + aInfo.packageName
   3578                                     + "/" + aInfo.name);
   3579                         }
   3580                         break;
   3581                     }
   3582                 }
   3583             } catch (RemoteException e) {
   3584             }
   3585 
   3586             if (aInfo == null) {
   3587                 // Nobody who is next!
   3588                 ActivityOptions.abort(options);
   3589                 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
   3590                 return false;
   3591             }
   3592 
   3593             intent.setComponent(new ComponentName(
   3594                     aInfo.applicationInfo.packageName, aInfo.name));
   3595             intent.setFlags(intent.getFlags()&~(
   3596                     Intent.FLAG_ACTIVITY_FORWARD_RESULT|
   3597                     Intent.FLAG_ACTIVITY_CLEAR_TOP|
   3598                     Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
   3599                     Intent.FLAG_ACTIVITY_NEW_TASK));
   3600 
   3601             // Okay now we need to start the new activity, replacing the
   3602             // currently running activity.  This is a little tricky because
   3603             // we want to start the new one as if the current one is finished,
   3604             // but not finish the current one first so that there is no flicker.
   3605             // And thus...
   3606             final boolean wasFinishing = r.finishing;
   3607             r.finishing = true;
   3608 
   3609             // Propagate reply information over to the new activity.
   3610             final ActivityRecord resultTo = r.resultTo;
   3611             final String resultWho = r.resultWho;
   3612             final int requestCode = r.requestCode;
   3613             r.resultTo = null;
   3614             if (resultTo != null) {
   3615                 resultTo.removeResultsLocked(r, resultWho, requestCode);
   3616             }
   3617 
   3618             final long origId = Binder.clearCallingIdentity();
   3619             int res = mStackSupervisor.startActivityLocked(r.app.thread, intent,
   3620                     r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null,
   3621                     resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage,
   3622                     -1, r.launchedFromUid, 0, options, false, null, null, null);
   3623             Binder.restoreCallingIdentity(origId);
   3624 
   3625             r.finishing = wasFinishing;
   3626             if (res != ActivityManager.START_SUCCESS) {
   3627                 return false;
   3628             }
   3629             return true;
   3630         }
   3631     }
   3632 
   3633     @Override
   3634     public final int startActivityFromRecents(int taskId, Bundle options) {
   3635         if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) {
   3636             String msg = "Permission Denial: startActivityFromRecents called without " +
   3637                     START_TASKS_FROM_RECENTS;
   3638             Slog.w(TAG, msg);
   3639             throw new SecurityException(msg);
   3640         }
   3641         return startActivityFromRecentsInner(taskId, options);
   3642     }
   3643 
   3644     final int startActivityFromRecentsInner(int taskId, Bundle options) {
   3645         final TaskRecord task;
   3646         final int callingUid;
   3647         final String callingPackage;
   3648         final Intent intent;
   3649         final int userId;
   3650         synchronized (this) {
   3651             task = recentTaskForIdLocked(taskId);
   3652             if (task == null) {
   3653                 throw new IllegalArgumentException("Task " + taskId + " not found.");
   3654             }
   3655             if (task.getRootActivity() != null) {
   3656                 moveTaskToFrontLocked(task.taskId, 0, null);
   3657                 return ActivityManager.START_TASK_TO_FRONT;
   3658             }
   3659             callingUid = task.mCallingUid;
   3660             callingPackage = task.mCallingPackage;
   3661             intent = task.intent;
   3662             intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
   3663             userId = task.userId;
   3664         }
   3665         return startActivityInPackage(callingUid, callingPackage, intent, null, null, null, 0, 0,
   3666                 options, userId, null, task);
   3667     }
   3668 
   3669     final int startActivityInPackage(int uid, String callingPackage,
   3670             Intent intent, String resolvedType, IBinder resultTo,
   3671             String resultWho, int requestCode, int startFlags, Bundle options, int userId,
   3672             IActivityContainer container, TaskRecord inTask) {
   3673 
   3674         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
   3675                 false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
   3676 
   3677         // TODO: Switch to user app stacks here.
   3678         int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent,
   3679                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
   3680                 null, null, null, options, userId, container, inTask);
   3681         return ret;
   3682     }
   3683 
   3684     @Override
   3685     public final int startActivities(IApplicationThread caller, String callingPackage,
   3686             Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
   3687             int userId) {
   3688         enforceNotIsolatedCaller("startActivities");
   3689         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
   3690                 false, ALLOW_FULL_ONLY, "startActivity", null);
   3691         // TODO: Switch to user app stacks here.
   3692         int ret = mStackSupervisor.startActivities(caller, -1, callingPackage, intents,
   3693                 resolvedTypes, resultTo, options, userId);
   3694         return ret;
   3695     }
   3696 
   3697     final int startActivitiesInPackage(int uid, String callingPackage,
   3698             Intent[] intents, String[] resolvedTypes, IBinder resultTo,
   3699             Bundle options, int userId) {
   3700 
   3701         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
   3702                 false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
   3703         // TODO: Switch to user app stacks here.
   3704         int ret = mStackSupervisor.startActivities(null, uid, callingPackage, intents, resolvedTypes,
   3705                 resultTo, options, userId);
   3706         return ret;
   3707     }
   3708 
   3709     //explicitly remove thd old information in mRecentTasks when removing existing user.
   3710     private void removeRecentTasksForUserLocked(int userId) {
   3711         if(userId <= 0) {
   3712             Slog.i(TAG, "Can't remove recent task on user " + userId);
   3713             return;
   3714         }
   3715 
   3716         for (int i = mRecentTasks.size() - 1; i >= 0; --i) {
   3717             TaskRecord tr = mRecentTasks.get(i);
   3718             if (tr.userId == userId) {
   3719                 if(DEBUG_TASKS) Slog.i(TAG, "remove RecentTask " + tr
   3720                         + " when finishing user" + userId);
   3721                 mRecentTasks.remove(i);
   3722                 tr.removedFromRecents();
   3723             }
   3724         }
   3725 
   3726         // Remove tasks from persistent storage.
   3727         notifyTaskPersisterLocked(null, true);
   3728     }
   3729 
   3730     // Sort by taskId
   3731     private Comparator<TaskRecord> mTaskRecordComparator = new Comparator<TaskRecord>() {
   3732         @Override
   3733         public int compare(TaskRecord lhs, TaskRecord rhs) {
   3734             return rhs.taskId - lhs.taskId;
   3735         }
   3736     };
   3737 
   3738     // Extract the affiliates of the chain containing mRecentTasks[start].
   3739     private int processNextAffiliateChainLocked(int start) {
   3740         final TaskRecord startTask = mRecentTasks.get(start);
   3741         final int affiliateId = startTask.mAffiliatedTaskId;
   3742 
   3743         // Quick identification of isolated tasks. I.e. those not launched behind.
   3744         if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
   3745                 startTask.mNextAffiliate == null) {
   3746             // There is still a slim chance that there are other tasks that point to this task
   3747             // and that the chain is so messed up that this task no longer points to them but
   3748             // the gain of this optimization outweighs the risk.
   3749             startTask.inRecents = true;
   3750             return start + 1;
   3751         }
   3752 
   3753         // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
   3754         mTmpRecents.clear();
   3755         for (int i = mRecentTasks.size() - 1; i >= start; --i) {
   3756             final TaskRecord task = mRecentTasks.get(i);
   3757             if (task.mAffiliatedTaskId == affiliateId) {
   3758                 mRecentTasks.remove(i);
   3759                 mTmpRecents.add(task);
   3760             }
   3761         }
   3762 
   3763         // Sort them all by taskId. That is the order they were create in and that order will
   3764         // always be correct.
   3765         Collections.sort(mTmpRecents, mTaskRecordComparator);
   3766 
   3767         // Go through and fix up the linked list.
   3768         // The first one is the end of the chain and has no next.
   3769         final TaskRecord first = mTmpRecents.get(0);
   3770         first.inRecents = true;
   3771         if (first.mNextAffiliate != null) {
   3772             Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
   3773             first.setNextAffiliate(null);
   3774             notifyTaskPersisterLocked(first, false);
   3775         }
   3776         // Everything in the middle is doubly linked from next to prev.
   3777         final int tmpSize = mTmpRecents.size();
   3778         for (int i = 0; i < tmpSize - 1; ++i) {
   3779             final TaskRecord next = mTmpRecents.get(i);
   3780             final TaskRecord prev = mTmpRecents.get(i + 1);
   3781             if (next.mPrevAffiliate != prev) {
   3782                 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
   3783                         " setting prev=" + prev);
   3784                 next.setPrevAffiliate(prev);
   3785                 notifyTaskPersisterLocked(next, false);
   3786             }
   3787             if (prev.mNextAffiliate != next) {
   3788                 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
   3789                         " setting next=" + next);
   3790                 prev.setNextAffiliate(next);
   3791                 notifyTaskPersisterLocked(prev, false);
   3792             }
   3793             prev.inRecents = true;
   3794         }
   3795         // The last one is the beginning of the list and has no prev.
   3796         final TaskRecord last = mTmpRecents.get(tmpSize - 1);
   3797         if (last.mPrevAffiliate != null) {
   3798             Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
   3799             last.setPrevAffiliate(null);
   3800             notifyTaskPersisterLocked(last, false);
   3801         }
   3802 
   3803         // Insert the group back into mRecentTasks at start.
   3804         mRecentTasks.addAll(start, mTmpRecents);
   3805 
   3806         // Let the caller know where we left off.
   3807         return start + tmpSize;
   3808     }
   3809 
   3810     /**
   3811      * Update the recent tasks lists: make sure tasks should still be here (their
   3812      * applications / activities still exist), update their availability, fixup ordering
   3813      * of affiliations.
   3814      */
   3815     void cleanupRecentTasksLocked(int userId) {
   3816         if (mRecentTasks == null) {
   3817             // Happens when called from the packagemanager broadcast before boot.
   3818             return;
   3819         }
   3820 
   3821         final HashMap<ComponentName, ActivityInfo> availActCache = new HashMap<>();
   3822         final HashMap<String, ApplicationInfo> availAppCache = new HashMap<>();
   3823         final IPackageManager pm = AppGlobals.getPackageManager();
   3824         final ActivityInfo dummyAct = new ActivityInfo();
   3825         final ApplicationInfo dummyApp = new ApplicationInfo();
   3826 
   3827         int N = mRecentTasks.size();
   3828 
   3829         int[] users = userId == UserHandle.USER_ALL
   3830                 ? getUsersLocked() : new int[] { userId };
   3831         for (int user : users) {
   3832             for (int i = 0; i < N; i++) {
   3833                 TaskRecord task = mRecentTasks.get(i);
   3834                 if (task.userId != user) {
   3835                     // Only look at tasks for the user ID of interest.
   3836                     continue;
   3837                 }
   3838                 if (task.autoRemoveRecents && task.getTopActivity() == null) {
   3839                     // This situation is broken, and we should just get rid of it now.
   3840                     mRecentTasks.remove(i);
   3841                     task.removedFromRecents();
   3842                     i--;
   3843                     N--;
   3844                     Slog.w(TAG, "Removing auto-remove without activity: " + task);
   3845                     continue;
   3846                 }
   3847                 // Check whether this activity is currently available.
   3848                 if (task.realActivity != null) {
   3849                     ActivityInfo ai = availActCache.get(task.realActivity);
   3850                     if (ai == null) {
   3851                         try {
   3852                             ai = pm.getActivityInfo(task.realActivity,
   3853                                     PackageManager.GET_UNINSTALLED_PACKAGES
   3854                                     | PackageManager.GET_DISABLED_COMPONENTS, user);
   3855                         } catch (RemoteException e) {
   3856                             // Will never happen.
   3857                             continue;
   3858                         }
   3859                         if (ai == null) {
   3860                             ai = dummyAct;
   3861                         }
   3862                         availActCache.put(task.realActivity, ai);
   3863                     }
   3864                     if (ai == dummyAct) {
   3865                         // This could be either because the activity no longer exists, or the
   3866                         // app is temporarily gone.  For the former we want to remove the recents
   3867                         // entry; for the latter we want to mark it as unavailable.
   3868                         ApplicationInfo app = availAppCache.get(task.realActivity.getPackageName());
   3869                         if (app == null) {
   3870                             try {
   3871                                 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
   3872                                         PackageManager.GET_UNINSTALLED_PACKAGES
   3873                                         | PackageManager.GET_DISABLED_COMPONENTS, user);
   3874                             } catch (RemoteException e) {
   3875                                 // Will never happen.
   3876                                 continue;
   3877                             }
   3878                             if (app == null) {
   3879                                 app = dummyApp;
   3880                             }
   3881                             availAppCache.put(task.realActivity.getPackageName(), app);
   3882                         }
   3883                         if (app == dummyApp || (app.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
   3884                             // Doesn't exist any more!  Good-bye.
   3885                             mRecentTasks.remove(i);
   3886                             task.removedFromRecents();
   3887                             i--;
   3888                             N--;
   3889                             Slog.w(TAG, "Removing no longer valid recent: " + task);
   3890                             continue;
   3891                         } else {
   3892                             // Otherwise just not available for now.
   3893                             if (task.isAvailable) {
   3894                                 if (DEBUG_RECENTS) Slog.d(TAG, "Making recent unavailable: "
   3895                                         + task);
   3896                             }
   3897                             task.isAvailable = false;
   3898                         }
   3899                     } else {
   3900                         if (!ai.enabled || !ai.applicationInfo.enabled
   3901                                 || (ai.applicationInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
   3902                             if (task.isAvailable) {
   3903                                 if (DEBUG_RECENTS) Slog.d(TAG, "Making recent unavailable: "
   3904                                         + task + " (enabled=" + ai.enabled + "/"
   3905                                         + ai.applicationInfo.enabled +  " flags="
   3906                                         + Integer.toHexString(ai.applicationInfo.flags) + ")");
   3907                             }
   3908                             task.isAvailable = false;
   3909                         } else {
   3910                             if (!task.isAvailable) {
   3911                                 if (DEBUG_RECENTS) Slog.d(TAG, "Making recent available: "
   3912                                         + task);
   3913                             }
   3914                             task.isAvailable = true;
   3915                         }
   3916                     }
   3917                 }
   3918             }
   3919         }
   3920 
   3921         // Verify the affiliate chain for each task.
   3922         for (int i = 0; i < N; i = processNextAffiliateChainLocked(i)) {
   3923         }
   3924 
   3925         mTmpRecents.clear();
   3926         // mRecentTasks is now in sorted, affiliated order.
   3927     }
   3928 
   3929     private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) {
   3930         int N = mRecentTasks.size();
   3931         TaskRecord top = task;
   3932         int topIndex = taskIndex;
   3933         while (top.mNextAffiliate != null && topIndex > 0) {
   3934             top = top.mNextAffiliate;
   3935             topIndex--;
   3936         }
   3937         if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding affilliates starting at "
   3938                 + topIndex + " from intial " + taskIndex);
   3939         // Find the end of the chain, doing a sanity check along the way.
   3940         boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
   3941         int endIndex = topIndex;
   3942         TaskRecord prev = top;
   3943         while (endIndex < N) {
   3944             TaskRecord cur = mRecentTasks.get(endIndex);
   3945             if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: looking at next chain @"
   3946                     + endIndex + " " + cur);
   3947             if (cur == top) {
   3948                 // Verify start of the chain.
   3949                 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
   3950                     Slog.wtf(TAG, "Bad chain @" + endIndex
   3951                             + ": first task has next affiliate: " + prev);
   3952                     sane = false;
   3953                     break;
   3954                 }
   3955             } else {
   3956                 // Verify middle of the chain's next points back to the one before.
   3957                 if (cur.mNextAffiliate != prev
   3958                         || cur.mNextAffiliateTaskId != prev.taskId) {
   3959                     Slog.wtf(TAG, "Bad chain @" + endIndex
   3960                             + ": middle task " + cur + " @" + endIndex
   3961                             + " has bad next affiliate "
   3962                             + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
   3963                             + ", expected " + prev);
   3964                     sane = false;
   3965                     break;
   3966                 }
   3967             }
   3968             if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
   3969                 // Chain ends here.
   3970                 if (cur.mPrevAffiliate != null) {
   3971                     Slog.wtf(TAG, "Bad chain @" + endIndex
   3972                             + ": last task " + cur + " has previous affiliate "
   3973                             + cur.mPrevAffiliate);
   3974                     sane = false;
   3975                 }
   3976                 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: end of chain @" + endIndex);
   3977                 break;
   3978             } else {
   3979                 // Verify middle of the chain's prev points to a valid item.
   3980                 if (cur.mPrevAffiliate == null) {
   3981                     Slog.wtf(TAG, "Bad chain @" + endIndex
   3982                             + ": task " + cur + " has previous affiliate "
   3983                             + cur.mPrevAffiliate + " but should be id "
   3984                             + cur.mPrevAffiliate);
   3985                     sane = false;
   3986                     break;
   3987                 }
   3988             }
   3989             if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
   3990                 Slog.wtf(TAG, "Bad chain @" + endIndex
   3991                         + ": task " + cur + " has affiliated id "
   3992                         + cur.mAffiliatedTaskId + " but should be "
   3993                         + task.mAffiliatedTaskId);
   3994                 sane = false;
   3995                 break;
   3996             }
   3997             prev = cur;
   3998             endIndex++;
   3999             if (endIndex >= N) {
   4000                 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
   4001                         + ": last task " + prev);
   4002                 sane = false;
   4003                 break;
   4004             }
   4005         }
   4006         if (sane) {
   4007             if (endIndex < taskIndex) {
   4008                 Slog.wtf(TAG, "Bad chain @" + endIndex
   4009                         + ": did not extend to task " + task + " @" + taskIndex);
   4010                 sane = false;
   4011             }
   4012         }
   4013         if (sane) {
   4014             // All looks good, we can just move all of the affiliated tasks
   4015             // to the top.
   4016             for (int i=topIndex; i<=endIndex; i++) {
   4017                 if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving affiliated " + task
   4018                         + " from " + i + " to " + (i-topIndex));
   4019                 TaskRecord cur = mRecentTasks.remove(i);
   4020                 mRecentTasks.add(i-topIndex, cur);
   4021             }
   4022             if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: done moving tasks  " +  topIndex
   4023                     + " to " + endIndex);
   4024             return true;
   4025         }
   4026 
   4027         // Whoops, couldn't do it.
   4028         return false;
   4029     }
   4030 
   4031     final void addRecentTaskLocked(TaskRecord task) {
   4032         final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
   4033                 || task.mNextAffiliateTaskId != INVALID_TASK_ID
   4034                 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
   4035 
   4036         int N = mRecentTasks.size();
   4037         // Quick case: check if the top-most recent task is the same.
   4038         if (!isAffiliated && N > 0 && mRecentTasks.get(0) == task) {
   4039             if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: already at top: " + task);
   4040             return;
   4041         }
   4042         // Another quick case: check if this is part of a set of affiliated
   4043         // tasks that are at the top.
   4044         if (isAffiliated && N > 0 && task.inRecents
   4045                 && task.mAffiliatedTaskId == mRecentTasks.get(0).mAffiliatedTaskId) {
   4046             if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: affiliated " + mRecentTasks.get(0)
   4047                     + " at top when adding " + task);
   4048             return;
   4049         }
   4050         // Another quick case: never add voice sessions.
   4051         if (task.voiceSession != null) {
   4052             if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: not adding voice interaction " + task);
   4053             return;
   4054         }
   4055 
   4056         boolean needAffiliationFix = false;
   4057 
   4058         // Slightly less quick case: the task is already in recents, so all we need
   4059         // to do is move it.
   4060         if (task.inRecents) {
   4061             int taskIndex = mRecentTasks.indexOf(task);
   4062             if (taskIndex >= 0) {
   4063                 if (!isAffiliated) {
   4064                     // Simple case: this is not an affiliated task, so we just move it to the front.
   4065                     mRecentTasks.remove(taskIndex);
   4066                     mRecentTasks.add(0, task);
   4067                     notifyTaskPersisterLocked(task, false);
   4068                     if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: moving to top " + task
   4069                             + " from " + taskIndex);
   4070                     return;
   4071                 } else {
   4072                     // More complicated: need to keep all affiliated tasks together.
   4073                     if (moveAffiliatedTasksToFront(task, taskIndex)) {
   4074                         // All went well.
   4075                         return;
   4076                     }
   4077 
   4078                     // Uh oh...  something bad in the affiliation chain, try to rebuild
   4079                     // everything and then go through our general path of adding a new task.
   4080                     needAffiliationFix = true;
   4081                 }
   4082             } else {
   4083                 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
   4084                 needAffiliationFix = true;
   4085             }
   4086         }
   4087 
   4088         if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: trimming tasks for " + task);
   4089         trimRecentsForTaskLocked(task, true);
   4090 
   4091         N = mRecentTasks.size();
   4092         while (N >= ActivityManager.getMaxRecentTasksStatic()) {
   4093             final TaskRecord tr = mRecentTasks.remove(N - 1);
   4094             tr.removedFromRecents();
   4095             N--;
   4096         }
   4097         task.inRecents = true;
   4098         if (!isAffiliated || needAffiliationFix) {
   4099             // If this is a simple non-affiliated task, or we had some failure trying to
   4100             // handle it as part of an affilated task, then just place it at the top.
   4101             mRecentTasks.add(0, task);
   4102         } else if (isAffiliated) {
   4103             // If this is a new affiliated task, then move all of the affiliated tasks
   4104             // to the front and insert this new one.
   4105             TaskRecord other = task.mNextAffiliate;
   4106             if (other == null) {
   4107                 other = task.mPrevAffiliate;
   4108             }
   4109             if (other != null) {
   4110                 int otherIndex = mRecentTasks.indexOf(other);
   4111                 if (otherIndex >= 0) {
   4112                     // Insert new task at appropriate location.
   4113                     int taskIndex;
   4114                     if (other == task.mNextAffiliate) {
   4115                         // We found the index of our next affiliation, which is who is
   4116                         // before us in the list, so add after that point.
   4117                         taskIndex = otherIndex+1;
   4118                     } else {
   4119                         // We found the index of our previous affiliation, which is who is
   4120                         // after us in the list, so add at their position.
   4121                         taskIndex = otherIndex;
   4122                     }
   4123                     if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: new affiliated task added at "
   4124                             + taskIndex + ": " + task);
   4125                     mRecentTasks.add(taskIndex, task);
   4126 
   4127                     // Now move everything to the front.
   4128                     if (moveAffiliatedTasksToFront(task, taskIndex)) {
   4129                         // All went well.
   4130                         return;
   4131                     }
   4132 
   4133                     // Uh oh...  something bad in the affiliation chain, try to rebuild
   4134                     // everything and then go through our general path of adding a new task.
   4135                     needAffiliationFix = true;
   4136                 } else {
   4137                     if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: couldn't find other affiliation "
   4138                             + other);
   4139                     needAffiliationFix = true;
   4140                 }
   4141             } else {
   4142                 if (DEBUG_RECENTS) Slog.d(TAG,
   4143                         "addRecent: adding affiliated task without next/prev:" + task);
   4144                 needAffiliationFix = true;
   4145             }
   4146         }
   4147         if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: adding " + task);
   4148 
   4149         if (needAffiliationFix) {
   4150             if (DEBUG_RECENTS) Slog.d(TAG, "addRecent: regrouping affiliations");
   4151             cleanupRecentTasksLocked(task.userId);
   4152         }
   4153     }
   4154 
   4155     /**
   4156      * If needed, remove oldest existing entries in recents that are for the same kind
   4157      * of task as the given one.
   4158      */
   4159     int trimRecentsForTaskLocked(TaskRecord task, boolean doTrim) {
   4160         int N = mRecentTasks.size();
   4161         final Intent intent = task.intent;
   4162         final boolean document = intent != null && intent.isDocument();
   4163 
   4164         int maxRecents = task.maxRecents - 1;
   4165         for (int i=0; i<N; i++) {
   4166             final TaskRecord tr = mRecentTasks.get(i);
   4167             if (task != tr) {
   4168                 if (task.userId != tr.userId) {
   4169                     continue;
   4170                 }
   4171                 if (i > MAX_RECENT_BITMAPS) {
   4172                     tr.freeLastThumbnail();
   4173                 }
   4174                 final Intent trIntent = tr.intent;
   4175                 if ((task.affinity == null || !task.affinity.equals(tr.affinity)) &&
   4176                     (intent == null || !intent.filterEquals(trIntent))) {
   4177                     continue;
   4178                 }
   4179                 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
   4180                 if (document && trIsDocument) {
   4181                     // These are the same document activity (not necessarily the same doc).
   4182                     if (maxRecents > 0) {
   4183                         --maxRecents;
   4184                         continue;
   4185                     }
   4186                     // Hit the maximum number of documents for this task. Fall through
   4187                     // and remove this document from recents.
   4188                 } else if (document || trIsDocument) {
   4189                     // Only one of these is a document. Not the droid we're looking for.
   4190                     continue;
   4191                 }
   4192             }
   4193 
   4194             if (!doTrim) {
   4195                 // If the caller is not actually asking for a trim, just tell them we reached
   4196                 // a point where the trim would happen.
   4197                 return i;
   4198             }
   4199 
   4200             // Either task and tr are the same or, their affinities match or their intents match
   4201             // and neither of them is a document, or they are documents using the same activity
   4202             // and their maxRecents has been reached.
   4203             tr.disposeThumbnail();
   4204             mRecentTasks.remove(i);
   4205             if (task != tr) {
   4206                 tr.removedFromRecents();
   4207             }
   4208             i--;
   4209             N--;
   4210             if (task.intent == null) {
   4211                 // If the new recent task we are adding is not fully
   4212                 // specified, then replace it with the existing recent task.
   4213                 task = tr;
   4214             }
   4215             notifyTaskPersisterLocked(tr, false);
   4216         }
   4217 
   4218         return -1;
   4219     }
   4220 
   4221     @Override
   4222     public void reportActivityFullyDrawn(IBinder token) {
   4223         synchronized (this) {
   4224             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4225             if (r == null) {
   4226                 return;
   4227             }
   4228             r.reportFullyDrawnLocked();
   4229         }
   4230     }
   4231 
   4232     @Override
   4233     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
   4234         synchronized (this) {
   4235             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4236             if (r == null) {
   4237                 return;
   4238             }
   4239             final long origId = Binder.clearCallingIdentity();
   4240             mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
   4241             Configuration config = mWindowManager.updateOrientationFromAppTokens(
   4242                     mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
   4243             if (config != null) {
   4244                 r.frozenBeforeDestroy = true;
   4245                 if (!updateConfigurationLocked(config, r, false, false)) {
   4246                     mStackSupervisor.resumeTopActivitiesLocked();
   4247                 }
   4248             }
   4249             Binder.restoreCallingIdentity(origId);
   4250         }
   4251     }
   4252 
   4253     @Override
   4254     public int getRequestedOrientation(IBinder token) {
   4255         synchronized (this) {
   4256             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4257             if (r == null) {
   4258                 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
   4259             }
   4260             return mWindowManager.getAppOrientation(r.appToken);
   4261         }
   4262     }
   4263 
   4264     /**
   4265      * This is the internal entry point for handling Activity.finish().
   4266      *
   4267      * @param token The Binder token referencing the Activity we want to finish.
   4268      * @param resultCode Result code, if any, from this Activity.
   4269      * @param resultData Result data (Intent), if any, from this Activity.
   4270      * @param finishTask Whether to finish the task associated with this Activity.  Only applies to
   4271      *            the root Activity in the task.
   4272      *
   4273      * @return Returns true if the activity successfully finished, or false if it is still running.
   4274      */
   4275     @Override
   4276     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
   4277             boolean finishTask) {
   4278         // Refuse possible leaked file descriptors
   4279         if (resultData != null && resultData.hasFileDescriptors() == true) {
   4280             throw new IllegalArgumentException("File descriptors passed in Intent");
   4281         }
   4282 
   4283         synchronized(this) {
   4284             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4285             if (r == null) {
   4286                 return true;
   4287             }
   4288             // Keep track of the root activity of the task before we finish it
   4289             TaskRecord tr = r.task;
   4290             ActivityRecord rootR = tr.getRootActivity();
   4291             if (rootR == null) {
   4292                 Slog.w(TAG, "Finishing task with all activities already finished");
   4293             }
   4294             // Do not allow task to finish in Lock Task mode.
   4295             if (tr == mStackSupervisor.mLockTaskModeTask) {
   4296                 if (rootR == r) {
   4297                     Slog.i(TAG, "Not finishing task in lock task mode");
   4298                     mStackSupervisor.showLockTaskToast();
   4299                     return false;
   4300                 }
   4301             }
   4302             if (mController != null) {
   4303                 // Find the first activity that is not finishing.
   4304                 ActivityRecord next = r.task.stack.topRunningActivityLocked(token, 0);
   4305                 if (next != null) {
   4306                     // ask watcher if this is allowed
   4307                     boolean resumeOK = true;
   4308                     try {
   4309                         resumeOK = mController.activityResuming(next.packageName);
   4310                     } catch (RemoteException e) {
   4311                         mController = null;
   4312                         Watchdog.getInstance().setActivityController(null);
   4313                     }
   4314 
   4315                     if (!resumeOK) {
   4316                         Slog.i(TAG, "Not finishing activity because controller resumed");
   4317                         return false;
   4318                     }
   4319                 }
   4320             }
   4321             final long origId = Binder.clearCallingIdentity();
   4322             try {
   4323                 boolean res;
   4324                 if (finishTask && r == rootR) {
   4325                     // If requested, remove the task that is associated to this activity only if it
   4326                     // was the root activity in the task. The result code and data is ignored
   4327                     // because we don't support returning them across task boundaries.
   4328                     res = removeTaskByIdLocked(tr.taskId, false);
   4329                     if (!res) {
   4330                         Slog.i(TAG, "Removing task failed to finish activity");
   4331                     }
   4332                 } else {
   4333                     res = tr.stack.requestFinishActivityLocked(token, resultCode,
   4334                             resultData, "app-request", true);
   4335                     if (!res) {
   4336                         Slog.i(TAG, "Failed to finish by app-request");
   4337                     }
   4338                 }
   4339                 return res;
   4340             } finally {
   4341                 Binder.restoreCallingIdentity(origId);
   4342             }
   4343         }
   4344     }
   4345 
   4346     @Override
   4347     public final void finishHeavyWeightApp() {
   4348         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
   4349                 != PackageManager.PERMISSION_GRANTED) {
   4350             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
   4351                     + Binder.getCallingPid()
   4352                     + ", uid=" + Binder.getCallingUid()
   4353                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
   4354             Slog.w(TAG, msg);
   4355             throw new SecurityException(msg);
   4356         }
   4357 
   4358         synchronized(this) {
   4359             if (mHeavyWeightProcess == null) {
   4360                 return;
   4361             }
   4362 
   4363             ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
   4364                     mHeavyWeightProcess.activities);
   4365             for (int i=0; i<activities.size(); i++) {
   4366                 ActivityRecord r = activities.get(i);
   4367                 if (!r.finishing) {
   4368                     r.task.stack.finishActivityLocked(r, Activity.RESULT_CANCELED,
   4369                             null, "finish-heavy", true);
   4370                 }
   4371             }
   4372 
   4373             mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
   4374                     mHeavyWeightProcess.userId, 0));
   4375             mHeavyWeightProcess = null;
   4376         }
   4377     }
   4378 
   4379     @Override
   4380     public void crashApplication(int uid, int initialPid, String packageName,
   4381             String message) {
   4382         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
   4383                 != PackageManager.PERMISSION_GRANTED) {
   4384             String msg = "Permission Denial: crashApplication() from pid="
   4385                     + Binder.getCallingPid()
   4386                     + ", uid=" + Binder.getCallingUid()
   4387                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
   4388             Slog.w(TAG, msg);
   4389             throw new SecurityException(msg);
   4390         }
   4391 
   4392         synchronized(this) {
   4393             ProcessRecord proc = null;
   4394 
   4395             // Figure out which process to kill.  We don't trust that initialPid
   4396             // still has any relation to current pids, so must scan through the
   4397             // list.
   4398             synchronized (mPidsSelfLocked) {
   4399                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
   4400                     ProcessRecord p = mPidsSelfLocked.valueAt(i);
   4401                     if (p.uid != uid) {
   4402                         continue;
   4403                     }
   4404                     if (p.pid == initialPid) {
   4405                         proc = p;
   4406                         break;
   4407                     }
   4408                     if (p.pkgList.containsKey(packageName)) {
   4409                         proc = p;
   4410                     }
   4411                 }
   4412             }
   4413 
   4414             if (proc == null) {
   4415                 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
   4416                         + " initialPid=" + initialPid
   4417                         + " packageName=" + packageName);
   4418                 return;
   4419             }
   4420 
   4421             if (proc.thread != null) {
   4422                 if (proc.pid == Process.myPid()) {
   4423                     Log.w(TAG, "crashApplication: trying to crash self!");
   4424                     return;
   4425                 }
   4426                 long ident = Binder.clearCallingIdentity();
   4427                 try {
   4428                     proc.thread.scheduleCrash(message);
   4429                 } catch (RemoteException e) {
   4430                 }
   4431                 Binder.restoreCallingIdentity(ident);
   4432             }
   4433         }
   4434     }
   4435 
   4436     @Override
   4437     public final void finishSubActivity(IBinder token, String resultWho,
   4438             int requestCode) {
   4439         synchronized(this) {
   4440             final long origId = Binder.clearCallingIdentity();
   4441             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4442             if (r != null) {
   4443                 r.task.stack.finishSubActivityLocked(r, resultWho, requestCode);
   4444             }
   4445             Binder.restoreCallingIdentity(origId);
   4446         }
   4447     }
   4448 
   4449     @Override
   4450     public boolean finishActivityAffinity(IBinder token) {
   4451         synchronized(this) {
   4452             final long origId = Binder.clearCallingIdentity();
   4453             try {
   4454                 ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4455 
   4456                 ActivityRecord rootR = r.task.getRootActivity();
   4457                 // Do not allow task to finish in Lock Task mode.
   4458                 if (r.task == mStackSupervisor.mLockTaskModeTask) {
   4459                     if (rootR == r) {
   4460                         mStackSupervisor.showLockTaskToast();
   4461                         return false;
   4462                     }
   4463                 }
   4464                 boolean res = false;
   4465                 if (r != null) {
   4466                     res = r.task.stack.finishActivityAffinityLocked(r);
   4467                 }
   4468                 return res;
   4469             } finally {
   4470                 Binder.restoreCallingIdentity(origId);
   4471             }
   4472         }
   4473     }
   4474 
   4475     @Override
   4476     public void finishVoiceTask(IVoiceInteractionSession session) {
   4477         synchronized(this) {
   4478             final long origId = Binder.clearCallingIdentity();
   4479             try {
   4480                 mStackSupervisor.finishVoiceTask(session);
   4481             } finally {
   4482                 Binder.restoreCallingIdentity(origId);
   4483             }
   4484         }
   4485 
   4486     }
   4487 
   4488     @Override
   4489     public boolean releaseActivityInstance(IBinder token) {
   4490         synchronized(this) {
   4491             final long origId = Binder.clearCallingIdentity();
   4492             try {
   4493                 ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4494                 if (r.task == null || r.task.stack == null) {
   4495                     return false;
   4496                 }
   4497                 return r.task.stack.safelyDestroyActivityLocked(r, "app-req");
   4498             } finally {
   4499                 Binder.restoreCallingIdentity(origId);
   4500             }
   4501         }
   4502     }
   4503 
   4504     @Override
   4505     public void releaseSomeActivities(IApplicationThread appInt) {
   4506         synchronized(this) {
   4507             final long origId = Binder.clearCallingIdentity();
   4508             try {
   4509                 ProcessRecord app = getRecordForAppLocked(appInt);
   4510                 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
   4511             } finally {
   4512                 Binder.restoreCallingIdentity(origId);
   4513             }
   4514         }
   4515     }
   4516 
   4517     @Override
   4518     public boolean willActivityBeVisible(IBinder token) {
   4519         synchronized(this) {
   4520             ActivityStack stack = ActivityRecord.getStackLocked(token);
   4521             if (stack != null) {
   4522                 return stack.willActivityBeVisibleLocked(token);
   4523             }
   4524             return false;
   4525         }
   4526     }
   4527 
   4528     @Override
   4529     public void overridePendingTransition(IBinder token, String packageName,
   4530             int enterAnim, int exitAnim) {
   4531         synchronized(this) {
   4532             ActivityRecord self = ActivityRecord.isInStackLocked(token);
   4533             if (self == null) {
   4534                 return;
   4535             }
   4536 
   4537             final long origId = Binder.clearCallingIdentity();
   4538 
   4539             if (self.state == ActivityState.RESUMED
   4540                     || self.state == ActivityState.PAUSING) {
   4541                 mWindowManager.overridePendingAppTransition(packageName,
   4542                         enterAnim, exitAnim, null);
   4543             }
   4544 
   4545             Binder.restoreCallingIdentity(origId);
   4546         }
   4547     }
   4548 
   4549     /**
   4550      * Main function for removing an existing process from the activity manager
   4551      * as a result of that process going away.  Clears out all connections
   4552      * to the process.
   4553      */
   4554     private final void handleAppDiedLocked(ProcessRecord app,
   4555             boolean restarting, boolean allowRestart) {
   4556         int pid = app.pid;
   4557         boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
   4558         if (!kept && !restarting) {
   4559             removeLruProcessLocked(app);
   4560             if (pid > 0) {
   4561                 ProcessList.remove(pid);
   4562             }
   4563         }
   4564 
   4565         if (mProfileProc == app) {
   4566             clearProfilerLocked();
   4567         }
   4568 
   4569         // Remove this application's activities from active lists.
   4570         boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app);
   4571 
   4572         app.activities.clear();
   4573 
   4574         if (app.instrumentationClass != null) {
   4575             Slog.w(TAG, "Crash of app " + app.processName
   4576                   + " running instrumentation " + app.instrumentationClass);
   4577             Bundle info = new Bundle();
   4578             info.putString("shortMsg", "Process crashed.");
   4579             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
   4580         }
   4581 
   4582         if (!restarting) {
   4583             if (!mStackSupervisor.resumeTopActivitiesLocked()) {
   4584                 // If there was nothing to resume, and we are not already
   4585                 // restarting this process, but there is a visible activity that
   4586                 // is hosted by the process...  then make sure all visible
   4587                 // activities are running, taking care of restarting this
   4588                 // process.
   4589                 if (hasVisibleActivities) {
   4590                     mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
   4591                 }
   4592             }
   4593         }
   4594     }
   4595 
   4596     private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
   4597         IBinder threadBinder = thread.asBinder();
   4598         // Find the application record.
   4599         for (int i=mLruProcesses.size()-1; i>=0; i--) {
   4600             ProcessRecord rec = mLruProcesses.get(i);
   4601             if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
   4602                 return i;
   4603             }
   4604         }
   4605         return -1;
   4606     }
   4607 
   4608     final ProcessRecord getRecordForAppLocked(
   4609             IApplicationThread thread) {
   4610         if (thread == null) {
   4611             return null;
   4612         }
   4613 
   4614         int appIndex = getLRURecordIndexForAppLocked(thread);
   4615         return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
   4616     }
   4617 
   4618     final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
   4619         // If there are no longer any background processes running,
   4620         // and the app that died was not running instrumentation,
   4621         // then tell everyone we are now low on memory.
   4622         boolean haveBg = false;
   4623         for (int i=mLruProcesses.size()-1; i>=0; i--) {
   4624             ProcessRecord rec = mLruProcesses.get(i);
   4625             if (rec.thread != null
   4626                     && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
   4627                 haveBg = true;
   4628                 break;
   4629             }
   4630         }
   4631 
   4632         if (!haveBg) {
   4633             boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
   4634             if (doReport) {
   4635                 long now = SystemClock.uptimeMillis();
   4636                 if (now < (mLastMemUsageReportTime+5*60*1000)) {
   4637                     doReport = false;
   4638                 } else {
   4639                     mLastMemUsageReportTime = now;
   4640                 }
   4641             }
   4642             final ArrayList<ProcessMemInfo> memInfos
   4643                     = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null;
   4644             EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
   4645             long now = SystemClock.uptimeMillis();
   4646             for (int i=mLruProcesses.size()-1; i>=0; i--) {
   4647                 ProcessRecord rec = mLruProcesses.get(i);
   4648                 if (rec == dyingProc || rec.thread == null) {
   4649                     continue;
   4650                 }
   4651                 if (doReport) {
   4652                     memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
   4653                             rec.setProcState, rec.adjType, rec.makeAdjReason()));
   4654                 }
   4655                 if ((rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
   4656                     // The low memory report is overriding any current
   4657                     // state for a GC request.  Make sure to do
   4658                     // heavy/important/visible/foreground processes first.
   4659                     if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
   4660                         rec.lastRequestedGc = 0;
   4661                     } else {
   4662                         rec.lastRequestedGc = rec.lastLowMemory;
   4663                     }
   4664                     rec.reportLowMemory = true;
   4665                     rec.lastLowMemory = now;
   4666                     mProcessesToGc.remove(rec);
   4667                     addProcessToGcListLocked(rec);
   4668                 }
   4669             }
   4670             if (doReport) {
   4671                 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
   4672                 mHandler.sendMessage(msg);
   4673             }
   4674             scheduleAppGcsLocked();
   4675         }
   4676     }
   4677 
   4678     final void appDiedLocked(ProcessRecord app) {
   4679        appDiedLocked(app, app.pid, app.thread);
   4680     }
   4681 
   4682     final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread) {
   4683         // First check if this ProcessRecord is actually active for the pid.
   4684         synchronized (mPidsSelfLocked) {
   4685             ProcessRecord curProc = mPidsSelfLocked.get(pid);
   4686             if (curProc != app) {
   4687                 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
   4688                 return;
   4689             }
   4690         }
   4691 
   4692         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
   4693         synchronized (stats) {
   4694             stats.noteProcessDiedLocked(app.info.uid, pid);
   4695         }
   4696 
   4697         if (!app.killed) {
   4698             Process.killProcessQuiet(pid);
   4699             Process.killProcessGroup(app.info.uid, pid);
   4700             app.killed = true;
   4701         }
   4702 
   4703         // Clean up already done if the process has been re-started.
   4704         if (app.pid == pid && app.thread != null &&
   4705                 app.thread.asBinder() == thread.asBinder()) {
   4706             boolean doLowMem = app.instrumentationClass == null;
   4707             boolean doOomAdj = doLowMem;
   4708             if (!app.killedByAm) {
   4709                 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
   4710                         + ") has died");
   4711                 mAllowLowerMemLevel = true;
   4712             } else {
   4713                 // Note that we always want to do oom adj to update our state with the
   4714                 // new number of procs.
   4715                 mAllowLowerMemLevel = false;
   4716                 doLowMem = false;
   4717             }
   4718             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
   4719             if (DEBUG_CLEANUP) Slog.v(
   4720                 TAG, "Dying app: " + app + ", pid: " + pid
   4721                 + ", thread: " + thread.asBinder());
   4722             handleAppDiedLocked(app, false, true);
   4723 
   4724             if (doOomAdj) {
   4725                 updateOomAdjLocked();
   4726             }
   4727             if (doLowMem) {
   4728                 doLowMemReportIfNeededLocked(app);
   4729             }
   4730         } else if (app.pid != pid) {
   4731             // A new process has already been started.
   4732             Slog.i(TAG, "Process " + app.processName + " (pid " + pid
   4733                     + ") has died and restarted (pid " + app.pid + ").");
   4734             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
   4735         } else if (DEBUG_PROCESSES) {
   4736             Slog.d(TAG, "Received spurious death notification for thread "
   4737                     + thread.asBinder());
   4738         }
   4739     }
   4740 
   4741     /**
   4742      * If a stack trace dump file is configured, dump process stack traces.
   4743      * @param clearTraces causes the dump file to be erased prior to the new
   4744      *    traces being written, if true; when false, the new traces will be
   4745      *    appended to any existing file content.
   4746      * @param firstPids of dalvik VM processes to dump stack traces for first
   4747      * @param lastPids of dalvik VM processes to dump stack traces for last
   4748      * @param nativeProcs optional list of native process names to dump stack crawls
   4749      * @return file containing stack traces, or null if no dump file is configured
   4750      */
   4751     public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
   4752             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
   4753         String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
   4754         if (tracesPath == null || tracesPath.length() == 0) {
   4755             return null;
   4756         }
   4757 
   4758         File tracesFile = new File(tracesPath);
   4759         try {
   4760             File tracesDir = tracesFile.getParentFile();
   4761             if (!tracesDir.exists()) {
   4762                 tracesDir.mkdirs();
   4763                 if (!SELinux.restorecon(tracesDir)) {
   4764                     return null;
   4765                 }
   4766             }
   4767             FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
   4768 
   4769             if (clearTraces && tracesFile.exists()) tracesFile.delete();
   4770             tracesFile.createNewFile();
   4771             FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
   4772         } catch (IOException e) {
   4773             Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
   4774             return null;
   4775         }
   4776 
   4777         dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativeProcs);
   4778         return tracesFile;
   4779     }
   4780 
   4781     private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
   4782             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
   4783         // Use a FileObserver to detect when traces finish writing.
   4784         // The order of traces is considered important to maintain for legibility.
   4785         FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
   4786             @Override
   4787             public synchronized void onEvent(int event, String path) { notify(); }
   4788         };
   4789 
   4790         try {
   4791             observer.startWatching();
   4792 
   4793             // First collect all of the stacks of the most important pids.
   4794             if (firstPids != null) {
   4795                 try {
   4796                     int num = firstPids.size();
   4797                     for (int i = 0; i < num; i++) {
   4798                         synchronized (observer) {
   4799                             Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
   4800                             observer.wait(200);  // Wait for write-close, give up after 200msec
   4801                         }
   4802                     }
   4803                 } catch (InterruptedException e) {
   4804                     Slog.wtf(TAG, e);
   4805                 }
   4806             }
   4807 
   4808             // Next collect the stacks of the native pids
   4809             if (nativeProcs != null) {
   4810                 int[] pids = Process.getPidsForCommands(nativeProcs);
   4811                 if (pids != null) {
   4812                     for (int pid : pids) {
   4813                         Debug.dumpNativeBacktraceToFile(pid, tracesPath);
   4814                     }
   4815                 }
   4816             }
   4817 
   4818             // Lastly, measure CPU usage.
   4819             if (processCpuTracker != null) {
   4820                 processCpuTracker.init();
   4821                 System.gc();
   4822                 processCpuTracker.update();
   4823                 try {
   4824                     synchronized (processCpuTracker) {
   4825                         processCpuTracker.wait(500); // measure over 1/2 second.
   4826                     }
   4827                 } catch (InterruptedException e) {
   4828                 }
   4829                 processCpuTracker.update();
   4830 
   4831                 // We'll take the stack crawls of just the top apps using CPU.
   4832                 final int N = processCpuTracker.countWorkingStats();
   4833                 int numProcs = 0;
   4834                 for (int i=0; i<N && numProcs<5; i++) {
   4835                     ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
   4836                     if (lastPids.indexOfKey(stats.pid) >= 0) {
   4837                         numProcs++;
   4838                         try {
   4839                             synchronized (observer) {
   4840                                 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
   4841                                 observer.wait(200);  // Wait for write-close, give up after 200msec
   4842                             }
   4843                         } catch (InterruptedException e) {
   4844                             Slog.wtf(TAG, e);
   4845                         }
   4846 
   4847                     }
   4848                 }
   4849             }
   4850         } finally {
   4851             observer.stopWatching();
   4852         }
   4853     }
   4854 
   4855     final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
   4856         if (true || IS_USER_BUILD) {
   4857             return;
   4858         }
   4859         String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
   4860         if (tracesPath == null || tracesPath.length() == 0) {
   4861             return;
   4862         }
   4863 
   4864         StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
   4865         StrictMode.allowThreadDiskWrites();
   4866         try {
   4867             final File tracesFile = new File(tracesPath);
   4868             final File tracesDir = tracesFile.getParentFile();
   4869             final File tracesTmp = new File(tracesDir, "__tmp__");
   4870             try {
   4871                 if (!tracesDir.exists()) {
   4872                     tracesDir.mkdirs();
   4873                     if (!SELinux.restorecon(tracesDir.getPath())) {
   4874                         return;
   4875                     }
   4876                 }
   4877                 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
   4878 
   4879                 if (tracesFile.exists()) {
   4880                     tracesTmp.delete();
   4881                     tracesFile.renameTo(tracesTmp);
   4882                 }
   4883                 StringBuilder sb = new StringBuilder();
   4884                 Time tobj = new Time();
   4885                 tobj.set(System.currentTimeMillis());
   4886                 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
   4887                 sb.append(": ");
   4888                 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
   4889                 sb.append(" since ");
   4890                 sb.append(msg);
   4891                 FileOutputStream fos = new FileOutputStream(tracesFile);
   4892                 fos.write(sb.toString().getBytes());
   4893                 if (app == null) {
   4894                     fos.write("\n*** No application process!".getBytes());
   4895                 }
   4896                 fos.close();
   4897                 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
   4898             } catch (IOException e) {
   4899                 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
   4900                 return;
   4901             }
   4902 
   4903             if (app != null) {
   4904                 ArrayList<Integer> firstPids = new ArrayList<Integer>();
   4905                 firstPids.add(app.pid);
   4906                 dumpStackTraces(tracesPath, firstPids, null, null, null);
   4907             }
   4908 
   4909             File lastTracesFile = null;
   4910             File curTracesFile = null;
   4911             for (int i=9; i>=0; i--) {
   4912                 String name = String.format(Locale.US, "slow%02d.txt", i);
   4913                 curTracesFile = new File(tracesDir, name);
   4914                 if (curTracesFile.exists()) {
   4915                     if (lastTracesFile != null) {
   4916                         curTracesFile.renameTo(lastTracesFile);
   4917                     } else {
   4918                         curTracesFile.delete();
   4919                     }
   4920                 }
   4921                 lastTracesFile = curTracesFile;
   4922             }
   4923             tracesFile.renameTo(curTracesFile);
   4924             if (tracesTmp.exists()) {
   4925                 tracesTmp.renameTo(tracesFile);
   4926             }
   4927         } finally {
   4928             StrictMode.setThreadPolicy(oldPolicy);
   4929         }
   4930     }
   4931 
   4932     final void appNotResponding(ProcessRecord app, ActivityRecord activity,
   4933             ActivityRecord parent, boolean aboveSystem, final String annotation) {
   4934         ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
   4935         SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
   4936 
   4937         if (mController != null) {
   4938             try {
   4939                 // 0 == continue, -1 = kill process immediately
   4940                 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
   4941                 if (res < 0 && app.pid != MY_PID) {
   4942                     app.kill("anr", true);
   4943                 }
   4944             } catch (RemoteException e) {
   4945                 mController = null;
   4946                 Watchdog.getInstance().setActivityController(null);
   4947             }
   4948         }
   4949 
   4950         long anrTime = SystemClock.uptimeMillis();
   4951         if (MONITOR_CPU_USAGE) {
   4952             updateCpuStatsNow();
   4953         }
   4954 
   4955         synchronized (this) {
   4956             // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
   4957             if (mShuttingDown) {
   4958                 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
   4959                 return;
   4960             } else if (app.notResponding) {
   4961                 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
   4962                 return;
   4963             } else if (app.crashing) {
   4964                 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
   4965                 return;
   4966             }
   4967 
   4968             // In case we come through here for the same app before completing
   4969             // this one, mark as anring now so we will bail out.
   4970             app.notResponding = true;
   4971 
   4972             // Log the ANR to the event log.
   4973             EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
   4974                     app.processName, app.info.flags, annotation);
   4975 
   4976             // Dump thread traces as quickly as we can, starting with "interesting" processes.
   4977             firstPids.add(app.pid);
   4978 
   4979             int parentPid = app.pid;
   4980             if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
   4981             if (parentPid != app.pid) firstPids.add(parentPid);
   4982 
   4983             if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
   4984 
   4985             for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
   4986                 ProcessRecord r = mLruProcesses.get(i);
   4987                 if (r != null && r.thread != null) {
   4988                     int pid = r.pid;
   4989                     if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
   4990                         if (r.persistent) {
   4991                             firstPids.add(pid);
   4992                         } else {
   4993                             lastPids.put(pid, Boolean.TRUE);
   4994                         }
   4995                     }
   4996                 }
   4997             }
   4998         }
   4999 
   5000         // Log the ANR to the main log.
   5001         StringBuilder info = new StringBuilder();
   5002         info.setLength(0);
   5003         info.append("ANR in ").append(app.processName);
   5004         if (activity != null && activity.shortComponentName != null) {
   5005             info.append(" (").append(activity.shortComponentName).append(")");
   5006         }
   5007         info.append("\n");
   5008         info.append("PID: ").append(app.pid).append("\n");
   5009         if (annotation != null) {
   5010             info.append("Reason: ").append(annotation).append("\n");
   5011         }
   5012         if (parent != null && parent != activity) {
   5013             info.append("Parent: ").append(parent.shortComponentName).append("\n");
   5014         }
   5015 
   5016         final ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
   5017 
   5018         File tracesFile = dumpStackTraces(true, firstPids, processCpuTracker, lastPids,
   5019                 NATIVE_STACKS_OF_INTEREST);
   5020 
   5021         String cpuInfo = null;
   5022         if (MONITOR_CPU_USAGE) {
   5023             updateCpuStatsNow();
   5024             synchronized (mProcessCpuTracker) {
   5025                 cpuInfo = mProcessCpuTracker.printCurrentState(anrTime);
   5026             }
   5027             info.append(processCpuTracker.printCurrentLoad());
   5028             info.append(cpuInfo);
   5029         }
   5030 
   5031         info.append(processCpuTracker.printCurrentState(anrTime));
   5032 
   5033         Slog.e(TAG, info.toString());
   5034         if (tracesFile == null) {
   5035             // There is no trace file, so dump (only) the alleged culprit's threads to the log
   5036             Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
   5037         }
   5038 
   5039         addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
   5040                 cpuInfo, tracesFile, null);
   5041 
   5042         if (mController != null) {
   5043             try {
   5044                 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
   5045                 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
   5046                 if (res != 0) {
   5047                     if (res < 0 && app.pid != MY_PID) {
   5048                         app.kill("anr", true);
   5049                     } else {
   5050                         synchronized (this) {
   5051                             mServices.scheduleServiceTimeoutLocked(app);
   5052                         }
   5053                     }
   5054                     return;
   5055                 }
   5056             } catch (RemoteException e) {
   5057                 mController = null;
   5058                 Watchdog.getInstance().setActivityController(null);
   5059             }
   5060         }
   5061 
   5062         // Unless configured otherwise, swallow ANRs in background processes & kill the process.
   5063         boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
   5064                 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
   5065 
   5066         synchronized (this) {
   5067             mBatteryStatsService.noteProcessAnr(app.processName, app.uid);
   5068 
   5069             if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
   5070                 app.kill("bg anr", true);
   5071                 return;
   5072             }
   5073 
   5074             // Set the app's notResponding state, and look up the errorReportReceiver
   5075             makeAppNotRespondingLocked(app,
   5076                     activity != null ? activity.shortComponentName : null,
   5077                     annotation != null ? "ANR " + annotation : "ANR",
   5078                     info.toString());
   5079 
   5080             // Bring up the infamous App Not Responding dialog
   5081             Message msg = Message.obtain();
   5082             HashMap<String, Object> map = new HashMap<String, Object>();
   5083             msg.what = SHOW_NOT_RESPONDING_MSG;
   5084             msg.obj = map;
   5085             msg.arg1 = aboveSystem ? 1 : 0;
   5086             map.put("app", app);
   5087             if (activity != null) {
   5088                 map.put("activity", activity);
   5089             }
   5090 
   5091             mHandler.sendMessage(msg);
   5092         }
   5093     }
   5094 
   5095     final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
   5096         if (!mLaunchWarningShown) {
   5097             mLaunchWarningShown = true;
   5098             mHandler.post(new Runnable() {
   5099                 @Override
   5100                 public void run() {
   5101                     synchronized (ActivityManagerService.this) {
   5102                         final Dialog d = new LaunchWarningWindow(mContext, cur, next);
   5103                         d.show();
   5104                         mHandler.postDelayed(new Runnable() {
   5105                             @Override
   5106                             public void run() {
   5107                                 synchronized (ActivityManagerService.this) {
   5108                                     d.dismiss();
   5109                                     mLaunchWarningShown = false;
   5110                                 }
   5111                             }
   5112                         }, 4000);
   5113                     }
   5114                 }
   5115             });
   5116         }
   5117     }
   5118 
   5119     @Override
   5120     public boolean clearApplicationUserData(final String packageName,
   5121             final IPackageDataObserver observer, int userId) {
   5122         enforceNotIsolatedCaller("clearApplicationUserData");
   5123         int uid = Binder.getCallingUid();
   5124         int pid = Binder.getCallingPid();
   5125         userId = handleIncomingUser(pid, uid,
   5126                 userId, false, ALLOW_FULL_ONLY, "clearApplicationUserData", null);
   5127         long callingId = Binder.clearCallingIdentity();
   5128         try {
   5129             IPackageManager pm = AppGlobals.getPackageManager();
   5130             int pkgUid = -1;
   5131             synchronized(this) {
   5132                 try {
   5133                     pkgUid = pm.getPackageUid(packageName, userId);
   5134                 } catch (RemoteException e) {
   5135                 }
   5136                 if (pkgUid == -1) {
   5137                     Slog.w(TAG, "Invalid packageName: " + packageName);
   5138                     if (observer != null) {
   5139                         try {
   5140                             observer.onRemoveCompleted(packageName, false);
   5141                         } catch (RemoteException e) {
   5142                             Slog.i(TAG, "Observer no longer exists.");
   5143                         }
   5144                     }
   5145                     return false;
   5146                 }
   5147                 if (uid == pkgUid || checkComponentPermission(
   5148                         android.Manifest.permission.CLEAR_APP_USER_DATA,
   5149                         pid, uid, -1, true)
   5150                         == PackageManager.PERMISSION_GRANTED) {
   5151                     forceStopPackageLocked(packageName, pkgUid, "clear data");
   5152                 } else {
   5153                     throw new SecurityException("PID " + pid + " does not have permission "
   5154                             + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
   5155                                     + " of package " + packageName);
   5156                 }
   5157 
   5158                 // Remove all tasks match the cleared application package and user
   5159                 for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
   5160                     final TaskRecord tr = mRecentTasks.get(i);
   5161                     final String taskPackageName =
   5162                             tr.getBaseIntent().getComponent().getPackageName();
   5163                     if (tr.userId != userId) continue;
   5164                     if (!taskPackageName.equals(packageName)) continue;
   5165                     removeTaskByIdLocked(tr.taskId, false);
   5166                 }
   5167             }
   5168 
   5169             try {
   5170                 // Clear application user data
   5171                 pm.clearApplicationUserData(packageName, observer, userId);
   5172 
   5173                 synchronized(this) {
   5174                     // Remove all permissions granted from/to this package
   5175                     removeUriPermissionsForPackageLocked(packageName, userId, true);
   5176                 }
   5177 
   5178                 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
   5179                         Uri.fromParts("package", packageName, null));
   5180                 intent.putExtra(Intent.EXTRA_UID, pkgUid);
   5181                 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
   5182                         null, null, 0, null, null, null, false, false, userId);
   5183             } catch (RemoteException e) {
   5184             }
   5185         } finally {
   5186             Binder.restoreCallingIdentity(callingId);
   5187         }
   5188         return true;
   5189     }
   5190 
   5191     @Override
   5192     public void killBackgroundProcesses(final String packageName, int userId) {
   5193         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
   5194                 != PackageManager.PERMISSION_GRANTED &&
   5195                 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
   5196                         != PackageManager.PERMISSION_GRANTED) {
   5197             String msg = "Permission Denial: killBackgroundProcesses() from pid="
   5198                     + Binder.getCallingPid()
   5199                     + ", uid=" + Binder.getCallingUid()
   5200                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
   5201             Slog.w(TAG, msg);
   5202             throw new SecurityException(msg);
   5203         }
   5204 
   5205         userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   5206                 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
   5207         long callingId = Binder.clearCallingIdentity();
   5208         try {
   5209             IPackageManager pm = AppGlobals.getPackageManager();
   5210             synchronized(this) {
   5211                 int appId = -1;
   5212                 try {
   5213                     appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
   5214                 } catch (RemoteException e) {
   5215                 }
   5216                 if (appId == -1) {
   5217                     Slog.w(TAG, "Invalid packageName: " + packageName);
   5218                     return;
   5219                 }
   5220                 killPackageProcessesLocked(packageName, appId, userId,
   5221                         ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
   5222             }
   5223         } finally {
   5224             Binder.restoreCallingIdentity(callingId);
   5225         }
   5226     }
   5227 
   5228     @Override
   5229     public void killAllBackgroundProcesses() {
   5230         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
   5231                 != PackageManager.PERMISSION_GRANTED) {
   5232             String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
   5233                     + Binder.getCallingPid()
   5234                     + ", uid=" + Binder.getCallingUid()
   5235                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
   5236             Slog.w(TAG, msg);
   5237             throw new SecurityException(msg);
   5238         }
   5239 
   5240         long callingId = Binder.clearCallingIdentity();
   5241         try {
   5242             synchronized(this) {
   5243                 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
   5244                 final int NP = mProcessNames.getMap().size();
   5245                 for (int ip=0; ip<NP; ip++) {
   5246                     SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
   5247                     final int NA = apps.size();
   5248                     for (int ia=0; ia<NA; ia++) {
   5249                         ProcessRecord app = apps.valueAt(ia);
   5250                         if (app.persistent) {
   5251                             // we don't kill persistent processes
   5252                             continue;
   5253                         }
   5254                         if (app.removed) {
   5255                             procs.add(app);
   5256                         } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
   5257                             app.removed = true;
   5258                             procs.add(app);
   5259                         }
   5260                     }
   5261                 }
   5262 
   5263                 int N = procs.size();
   5264                 for (int i=0; i<N; i++) {
   5265                     removeProcessLocked(procs.get(i), false, true, "kill all background");
   5266                 }
   5267                 mAllowLowerMemLevel = true;
   5268                 updateOomAdjLocked();
   5269                 doLowMemReportIfNeededLocked(null);
   5270             }
   5271         } finally {
   5272             Binder.restoreCallingIdentity(callingId);
   5273         }
   5274     }
   5275 
   5276     @Override
   5277     public void forceStopPackage(final String packageName, int userId) {
   5278         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
   5279                 != PackageManager.PERMISSION_GRANTED) {
   5280             String msg = "Permission Denial: forceStopPackage() from pid="
   5281                     + Binder.getCallingPid()
   5282                     + ", uid=" + Binder.getCallingUid()
   5283                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
   5284             Slog.w(TAG, msg);
   5285             throw new SecurityException(msg);
   5286         }
   5287         final int callingPid = Binder.getCallingPid();
   5288         userId = handleIncomingUser(callingPid, Binder.getCallingUid(),
   5289                 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
   5290         long callingId = Binder.clearCallingIdentity();
   5291         try {
   5292             IPackageManager pm = AppGlobals.getPackageManager();
   5293             synchronized(this) {
   5294                 int[] users = userId == UserHandle.USER_ALL
   5295                         ? getUsersLocked() : new int[] { userId };
   5296                 for (int user : users) {
   5297                     int pkgUid = -1;
   5298                     try {
   5299                         pkgUid = pm.getPackageUid(packageName, user);
   5300                     } catch (RemoteException e) {
   5301                     }
   5302                     if (pkgUid == -1) {
   5303                         Slog.w(TAG, "Invalid packageName: " + packageName);
   5304                         continue;
   5305                     }
   5306                     try {
   5307                         pm.setPackageStoppedState(packageName, true, user);
   5308                     } catch (RemoteException e) {
   5309                     } catch (IllegalArgumentException e) {
   5310                         Slog.w(TAG, "Failed trying to unstop package "
   5311                                 + packageName + ": " + e);
   5312                     }
   5313                     if (isUserRunningLocked(user, false)) {
   5314                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
   5315                     }
   5316                 }
   5317             }
   5318         } finally {
   5319             Binder.restoreCallingIdentity(callingId);
   5320         }
   5321     }
   5322 
   5323     @Override
   5324     public void addPackageDependency(String packageName) {
   5325         synchronized (this) {
   5326             int callingPid = Binder.getCallingPid();
   5327             if (callingPid == Process.myPid()) {
   5328                 //  Yeah, um, no.
   5329                 return;
   5330             }
   5331             ProcessRecord proc;
   5332             synchronized (mPidsSelfLocked) {
   5333                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
   5334             }
   5335             if (proc != null) {
   5336                 if (proc.pkgDeps == null) {
   5337                     proc.pkgDeps = new ArraySet<String>(1);
   5338                 }
   5339                 proc.pkgDeps.add(packageName);
   5340             }
   5341         }
   5342     }
   5343 
   5344     /*
   5345      * The pkg name and app id have to be specified.
   5346      */
   5347     @Override
   5348     public void killApplicationWithAppId(String pkg, int appid, String reason) {
   5349         if (pkg == null) {
   5350             return;
   5351         }
   5352         // Make sure the uid is valid.
   5353         if (appid < 0) {
   5354             Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
   5355             return;
   5356         }
   5357         int callerUid = Binder.getCallingUid();
   5358         // Only the system server can kill an application
   5359         if (callerUid == Process.SYSTEM_UID) {
   5360             // Post an aysnc message to kill the application
   5361             Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
   5362             msg.arg1 = appid;
   5363             msg.arg2 = 0;
   5364             Bundle bundle = new Bundle();
   5365             bundle.putString("pkg", pkg);
   5366             bundle.putString("reason", reason);
   5367             msg.obj = bundle;
   5368             mHandler.sendMessage(msg);
   5369         } else {
   5370             throw new SecurityException(callerUid + " cannot kill pkg: " +
   5371                     pkg);
   5372         }
   5373     }
   5374 
   5375     @Override
   5376     public void closeSystemDialogs(String reason) {
   5377         enforceNotIsolatedCaller("closeSystemDialogs");
   5378 
   5379         final int pid = Binder.getCallingPid();
   5380         final int uid = Binder.getCallingUid();
   5381         final long origId = Binder.clearCallingIdentity();
   5382         try {
   5383             synchronized (this) {
   5384                 // Only allow this from foreground processes, so that background
   5385                 // applications can't abuse it to prevent system UI from being shown.
   5386                 if (uid >= Process.FIRST_APPLICATION_UID) {
   5387                     ProcessRecord proc;
   5388                     synchronized (mPidsSelfLocked) {
   5389                         proc = mPidsSelfLocked.get(pid);
   5390                     }
   5391                     if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
   5392                         Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
   5393                                 + " from background process " + proc);
   5394                         return;
   5395                     }
   5396                 }
   5397                 closeSystemDialogsLocked(reason);
   5398             }
   5399         } finally {
   5400             Binder.restoreCallingIdentity(origId);
   5401         }
   5402     }
   5403 
   5404     void closeSystemDialogsLocked(String reason) {
   5405         Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
   5406         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   5407                 | Intent.FLAG_RECEIVER_FOREGROUND);
   5408         if (reason != null) {
   5409             intent.putExtra("reason", reason);
   5410         }
   5411         mWindowManager.closeSystemDialogs(reason);
   5412 
   5413         mStackSupervisor.closeSystemDialogsLocked();
   5414 
   5415         broadcastIntentLocked(null, null, intent, null,
   5416                 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1,
   5417                 Process.SYSTEM_UID, UserHandle.USER_ALL);
   5418     }
   5419 
   5420     @Override
   5421     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
   5422         enforceNotIsolatedCaller("getProcessMemoryInfo");
   5423         Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
   5424         for (int i=pids.length-1; i>=0; i--) {
   5425             ProcessRecord proc;
   5426             int oomAdj;
   5427             synchronized (this) {
   5428                 synchronized (mPidsSelfLocked) {
   5429                     proc = mPidsSelfLocked.get(pids[i]);
   5430                     oomAdj = proc != null ? proc.setAdj : 0;
   5431                 }
   5432             }
   5433             infos[i] = new Debug.MemoryInfo();
   5434             Debug.getMemoryInfo(pids[i], infos[i]);
   5435             if (proc != null) {
   5436                 synchronized (this) {
   5437                     if (proc.thread != null && proc.setAdj == oomAdj) {
   5438                         // Record this for posterity if the process has been stable.
   5439                         proc.baseProcessTracker.addPss(infos[i].getTotalPss(),
   5440                                 infos[i].getTotalUss(), false, proc.pkgList);
   5441                     }
   5442                 }
   5443             }
   5444         }
   5445         return infos;
   5446     }
   5447 
   5448     @Override
   5449     public long[] getProcessPss(int[] pids) {
   5450         enforceNotIsolatedCaller("getProcessPss");
   5451         long[] pss = new long[pids.length];
   5452         for (int i=pids.length-1; i>=0; i--) {
   5453             ProcessRecord proc;
   5454             int oomAdj;
   5455             synchronized (this) {
   5456                 synchronized (mPidsSelfLocked) {
   5457                     proc = mPidsSelfLocked.get(pids[i]);
   5458                     oomAdj = proc != null ? proc.setAdj : 0;
   5459                 }
   5460             }
   5461             long[] tmpUss = new long[1];
   5462             pss[i] = Debug.getPss(pids[i], tmpUss, null);
   5463             if (proc != null) {
   5464                 synchronized (this) {
   5465                     if (proc.thread != null && proc.setAdj == oomAdj) {
   5466                         // Record this for posterity if the process has been stable.
   5467                         proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList);
   5468                     }
   5469                 }
   5470             }
   5471         }
   5472         return pss;
   5473     }
   5474 
   5475     @Override
   5476     public void killApplicationProcess(String processName, int uid) {
   5477         if (processName == null) {
   5478             return;
   5479         }
   5480 
   5481         int callerUid = Binder.getCallingUid();
   5482         // Only the system server can kill an application
   5483         if (callerUid == Process.SYSTEM_UID) {
   5484             synchronized (this) {
   5485                 ProcessRecord app = getProcessRecordLocked(processName, uid, true);
   5486                 if (app != null && app.thread != null) {
   5487                     try {
   5488                         app.thread.scheduleSuicide();
   5489                     } catch (RemoteException e) {
   5490                         // If the other end already died, then our work here is done.
   5491                     }
   5492                 } else {
   5493                     Slog.w(TAG, "Process/uid not found attempting kill of "
   5494                             + processName + " / " + uid);
   5495                 }
   5496             }
   5497         } else {
   5498             throw new SecurityException(callerUid + " cannot kill app process: " +
   5499                     processName);
   5500         }
   5501     }
   5502 
   5503     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
   5504         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
   5505                 false, true, false, false, UserHandle.getUserId(uid), reason);
   5506         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
   5507                 Uri.fromParts("package", packageName, null));
   5508         if (!mProcessesReady) {
   5509             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   5510                     | Intent.FLAG_RECEIVER_FOREGROUND);
   5511         }
   5512         intent.putExtra(Intent.EXTRA_UID, uid);
   5513         intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
   5514         broadcastIntentLocked(null, null, intent,
   5515                 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
   5516                 false, false,
   5517                 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
   5518     }
   5519 
   5520     private void forceStopUserLocked(int userId, String reason) {
   5521         forceStopPackageLocked(null, -1, false, false, true, false, false, userId, reason);
   5522         Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
   5523         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   5524                 | Intent.FLAG_RECEIVER_FOREGROUND);
   5525         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
   5526         broadcastIntentLocked(null, null, intent,
   5527                 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
   5528                 false, false,
   5529                 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
   5530     }
   5531 
   5532     private final boolean killPackageProcessesLocked(String packageName, int appId,
   5533             int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
   5534             boolean doit, boolean evenPersistent, String reason) {
   5535         ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
   5536 
   5537         // Remove all processes this package may have touched: all with the
   5538         // same UID (except for the system or root user), and all whose name
   5539         // matches the package name.
   5540         final int NP = mProcessNames.getMap().size();
   5541         for (int ip=0; ip<NP; ip++) {
   5542             SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
   5543             final int NA = apps.size();
   5544             for (int ia=0; ia<NA; ia++) {
   5545                 ProcessRecord app = apps.valueAt(ia);
   5546                 if (app.persistent && !evenPersistent) {
   5547                     // we don't kill persistent processes
   5548                     continue;
   5549                 }
   5550                 if (app.removed) {
   5551                     if (doit) {
   5552                         procs.add(app);
   5553                     }
   5554                     continue;
   5555                 }
   5556 
   5557                 // Skip process if it doesn't meet our oom adj requirement.
   5558                 if (app.setAdj < minOomAdj) {
   5559                     continue;
   5560                 }
   5561 
   5562                 // If no package is specified, we call all processes under the
   5563                 // give user id.
   5564                 if (packageName == null) {
   5565                     if (app.userId != userId) {
   5566                         continue;
   5567                     }
   5568                     if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) {
   5569                         continue;
   5570                     }
   5571                 // Package has been specified, we want to hit all processes
   5572                 // that match it.  We need to qualify this by the processes
   5573                 // that are running under the specified app and user ID.
   5574                 } else {
   5575                     final boolean isDep = app.pkgDeps != null
   5576                             && app.pkgDeps.contains(packageName);
   5577                     if (!isDep && UserHandle.getAppId(app.uid) != appId) {
   5578                         continue;
   5579                     }
   5580                     if (userId != UserHandle.USER_ALL && app.userId != userId) {
   5581                         continue;
   5582                     }
   5583                     if (!app.pkgList.containsKey(packageName) && !isDep) {
   5584                         continue;
   5585                     }
   5586                 }
   5587 
   5588                 // Process has passed all conditions, kill it!
   5589                 if (!doit) {
   5590                     return true;
   5591                 }
   5592                 app.removed = true;
   5593                 procs.add(app);
   5594             }
   5595         }
   5596 
   5597         int N = procs.size();
   5598         for (int i=0; i<N; i++) {
   5599             removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
   5600         }
   5601         updateOomAdjLocked();
   5602         return N > 0;
   5603     }
   5604 
   5605     private final boolean forceStopPackageLocked(String name, int appId,
   5606             boolean callerWillRestart, boolean purgeCache, boolean doit,
   5607             boolean evenPersistent, boolean uninstalling, int userId, String reason) {
   5608         int i;
   5609         int N;
   5610 
   5611         if (userId == UserHandle.USER_ALL && name == null) {
   5612             Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
   5613         }
   5614 
   5615         if (appId < 0 && name != null) {
   5616             try {
   5617                 appId = UserHandle.getAppId(
   5618                         AppGlobals.getPackageManager().getPackageUid(name, 0));
   5619             } catch (RemoteException e) {
   5620             }
   5621         }
   5622 
   5623         if (doit) {
   5624             if (name != null) {
   5625                 Slog.i(TAG, "Force stopping " + name + " appid=" + appId
   5626                         + " user=" + userId + ": " + reason);
   5627             } else {
   5628                 Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
   5629             }
   5630 
   5631             final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
   5632             for (int ip=pmap.size()-1; ip>=0; ip--) {
   5633                 SparseArray<Long> ba = pmap.valueAt(ip);
   5634                 for (i=ba.size()-1; i>=0; i--) {
   5635                     boolean remove = false;
   5636                     final int entUid = ba.keyAt(i);
   5637                     if (name != null) {
   5638                         if (userId == UserHandle.USER_ALL) {
   5639                             if (UserHandle.getAppId(entUid) == appId) {
   5640                                 remove = true;
   5641                             }
   5642                         } else {
   5643                             if (entUid == UserHandle.getUid(userId, appId)) {
   5644                                 remove = true;
   5645                             }
   5646                         }
   5647                     } else if (UserHandle.getUserId(entUid) == userId) {
   5648                         remove = true;
   5649                     }
   5650                     if (remove) {
   5651                         ba.removeAt(i);
   5652                     }
   5653                 }
   5654                 if (ba.size() == 0) {
   5655                     pmap.removeAt(ip);
   5656                 }
   5657             }
   5658         }
   5659 
   5660         boolean didSomething = killPackageProcessesLocked(name, appId, userId,
   5661                 -100, callerWillRestart, true, doit, evenPersistent,
   5662                 name == null ? ("stop user " + userId) : ("stop " + name));
   5663 
   5664         if (mStackSupervisor.forceStopPackageLocked(name, doit, evenPersistent, userId)) {
   5665             if (!doit) {
   5666                 return true;
   5667             }
   5668             didSomething = true;
   5669         }
   5670 
   5671         if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
   5672             if (!doit) {
   5673                 return true;
   5674             }
   5675             didSomething = true;
   5676         }
   5677 
   5678         if (name == null) {
   5679             // Remove all sticky broadcasts from this user.
   5680             mStickyBroadcasts.remove(userId);
   5681         }
   5682 
   5683         ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
   5684         if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
   5685                 userId, providers)) {
   5686             if (!doit) {
   5687                 return true;
   5688             }
   5689             didSomething = true;
   5690         }
   5691         N = providers.size();
   5692         for (i=0; i<N; i++) {
   5693             removeDyingProviderLocked(null, providers.get(i), true);
   5694         }
   5695 
   5696         // Remove transient permissions granted from/to this package/user
   5697         removeUriPermissionsForPackageLocked(name, userId, false);
   5698 
   5699         if (name == null || uninstalling) {
   5700             // Remove pending intents.  For now we only do this when force
   5701             // stopping users, because we have some problems when doing this
   5702             // for packages -- app widgets are not currently cleaned up for
   5703             // such packages, so they can be left with bad pending intents.
   5704             if (mIntentSenderRecords.size() > 0) {
   5705                 Iterator<WeakReference<PendingIntentRecord>> it
   5706                         = mIntentSenderRecords.values().iterator();
   5707                 while (it.hasNext()) {
   5708                     WeakReference<PendingIntentRecord> wpir = it.next();
   5709                     if (wpir == null) {
   5710                         it.remove();
   5711                         continue;
   5712                     }
   5713                     PendingIntentRecord pir = wpir.get();
   5714                     if (pir == null) {
   5715                         it.remove();
   5716                         continue;
   5717                     }
   5718                     if (name == null) {
   5719                         // Stopping user, remove all objects for the user.
   5720                         if (pir.key.userId != userId) {
   5721                             // Not the same user, skip it.
   5722                             continue;
   5723                         }
   5724                     } else {
   5725                         if (UserHandle.getAppId(pir.uid) != appId) {
   5726                             // Different app id, skip it.
   5727                             continue;
   5728                         }
   5729                         if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
   5730                             // Different user, skip it.
   5731                             continue;
   5732                         }
   5733                         if (!pir.key.packageName.equals(name)) {
   5734                             // Different package, skip it.
   5735                             continue;
   5736                         }
   5737                     }
   5738                     if (!doit) {
   5739                         return true;
   5740                     }
   5741                     didSomething = true;
   5742                     it.remove();
   5743                     pir.canceled = true;
   5744                     if (pir.key.activity != null && pir.key.activity.pendingResults != null) {
   5745                         pir.key.activity.pendingResults.remove(pir.ref);
   5746                     }
   5747                 }
   5748             }
   5749         }
   5750 
   5751         if (doit) {
   5752             if (purgeCache && name != null) {
   5753                 AttributeCache ac = AttributeCache.instance();
   5754                 if (ac != null) {
   5755                     ac.removePackage(name);
   5756                 }
   5757             }
   5758             if (mBooted) {
   5759                 mStackSupervisor.resumeTopActivitiesLocked();
   5760                 mStackSupervisor.scheduleIdleLocked();
   5761             }
   5762         }
   5763 
   5764         return didSomething;
   5765     }
   5766 
   5767     private final boolean removeProcessLocked(ProcessRecord app,
   5768             boolean callerWillRestart, boolean allowRestart, String reason) {
   5769         final String name = app.processName;
   5770         final int uid = app.uid;
   5771         if (DEBUG_PROCESSES) Slog.d(
   5772             TAG, "Force removing proc " + app.toShortString() + " (" + name
   5773             + "/" + uid + ")");
   5774 
   5775         mProcessNames.remove(name, uid);
   5776         mIsolatedProcesses.remove(app.uid);
   5777         if (mHeavyWeightProcess == app) {
   5778             mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
   5779                     mHeavyWeightProcess.userId, 0));
   5780             mHeavyWeightProcess = null;
   5781         }
   5782         boolean needRestart = false;
   5783         if (app.pid > 0 && app.pid != MY_PID) {
   5784             int pid = app.pid;
   5785             synchronized (mPidsSelfLocked) {
   5786                 mPidsSelfLocked.remove(pid);
   5787                 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
   5788             }
   5789             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
   5790             if (app.isolated) {
   5791                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
   5792             }
   5793             app.kill(reason, true);
   5794             handleAppDiedLocked(app, true, allowRestart);
   5795             removeLruProcessLocked(app);
   5796 
   5797             if (app.persistent && !app.isolated) {
   5798                 if (!callerWillRestart) {
   5799                     addAppLocked(app.info, false, null /* ABI override */);
   5800                 } else {
   5801                     needRestart = true;
   5802                 }
   5803             }
   5804         } else {
   5805             mRemovedProcesses.add(app);
   5806         }
   5807 
   5808         return needRestart;
   5809     }
   5810 
   5811     private final void processStartTimedOutLocked(ProcessRecord app) {
   5812         final int pid = app.pid;
   5813         boolean gone = false;
   5814         synchronized (mPidsSelfLocked) {
   5815             ProcessRecord knownApp = mPidsSelfLocked.get(pid);
   5816             if (knownApp != null && knownApp.thread == null) {
   5817                 mPidsSelfLocked.remove(pid);
   5818                 gone = true;
   5819             }
   5820         }
   5821 
   5822         if (gone) {
   5823             Slog.w(TAG, "Process " + app + " failed to attach");
   5824             EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
   5825                     pid, app.uid, app.processName);
   5826             mProcessNames.remove(app.processName, app.uid);
   5827             mIsolatedProcesses.remove(app.uid);
   5828             if (mHeavyWeightProcess == app) {
   5829                 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
   5830                         mHeavyWeightProcess.userId, 0));
   5831                 mHeavyWeightProcess = null;
   5832             }
   5833             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
   5834             if (app.isolated) {
   5835                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
   5836             }
   5837             // Take care of any launching providers waiting for this process.
   5838             checkAppInLaunchingProvidersLocked(app, true);
   5839             // Take care of any services that are waiting for the process.
   5840             mServices.processStartTimedOutLocked(app);
   5841             app.kill("start timeout", true);
   5842             if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
   5843                 Slog.w(TAG, "Unattached app died before backup, skipping");
   5844                 try {
   5845                     IBackupManager bm = IBackupManager.Stub.asInterface(
   5846                             ServiceManager.getService(Context.BACKUP_SERVICE));
   5847                     bm.agentDisconnected(app.info.packageName);
   5848                 } catch (RemoteException e) {
   5849                     // Can't happen; the backup manager is local
   5850                 }
   5851             }
   5852             if (isPendingBroadcastProcessLocked(pid)) {
   5853                 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
   5854                 skipPendingBroadcastLocked(pid);
   5855             }
   5856         } else {
   5857             Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
   5858         }
   5859     }
   5860 
   5861     private final boolean attachApplicationLocked(IApplicationThread thread,
   5862             int pid) {
   5863 
   5864         // Find the application record that is being attached...  either via
   5865         // the pid if we are running in multiple processes, or just pull the
   5866         // next app record if we are emulating process with anonymous threads.
   5867         ProcessRecord app;
   5868         if (pid != MY_PID && pid >= 0) {
   5869             synchronized (mPidsSelfLocked) {
   5870                 app = mPidsSelfLocked.get(pid);
   5871             }
   5872         } else {
   5873             app = null;
   5874         }
   5875 
   5876         if (app == null) {
   5877             Slog.w(TAG, "No pending application record for pid " + pid
   5878                     + " (IApplicationThread " + thread + "); dropping process");
   5879             EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
   5880             if (pid > 0 && pid != MY_PID) {
   5881                 Process.killProcessQuiet(pid);
   5882                 //TODO: Process.killProcessGroup(app.info.uid, pid);
   5883             } else {
   5884                 try {
   5885                     thread.scheduleExit();
   5886                 } catch (Exception e) {
   5887                     // Ignore exceptions.
   5888                 }
   5889             }
   5890             return false;
   5891         }
   5892 
   5893         // If this application record is still attached to a previous
   5894         // process, clean it up now.
   5895         if (app.thread != null) {
   5896             handleAppDiedLocked(app, true, true);
   5897         }
   5898 
   5899         // Tell the process all about itself.
   5900 
   5901         if (localLOGV) Slog.v(
   5902                 TAG, "Binding process pid " + pid + " to record " + app);
   5903 
   5904         final String processName = app.processName;
   5905         try {
   5906             AppDeathRecipient adr = new AppDeathRecipient(
   5907                     app, pid, thread);
   5908             thread.asBinder().linkToDeath(adr, 0);
   5909             app.deathRecipient = adr;
   5910         } catch (RemoteException e) {
   5911             app.resetPackageList(mProcessStats);
   5912             startProcessLocked(app, "link fail", processName);
   5913             return false;
   5914         }
   5915 
   5916         EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
   5917 
   5918         app.makeActive(thread, mProcessStats);
   5919         app.curAdj = app.setAdj = -100;
   5920         app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT;
   5921         app.forcingToForeground = null;
   5922         updateProcessForegroundLocked(app, false, false);
   5923         app.hasShownUi = false;
   5924         app.debugging = false;
   5925         app.cached = false;
   5926         app.killedByAm = false;
   5927 
   5928         mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
   5929 
   5930         boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
   5931         List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
   5932 
   5933         if (!normalMode) {
   5934             Slog.i(TAG, "Launching preboot mode app: " + app);
   5935         }
   5936 
   5937         if (localLOGV) Slog.v(
   5938             TAG, "New app record " + app
   5939             + " thread=" + thread.asBinder() + " pid=" + pid);
   5940         try {
   5941             int testMode = IApplicationThread.DEBUG_OFF;
   5942             if (mDebugApp != null && mDebugApp.equals(processName)) {
   5943                 testMode = mWaitForDebugger
   5944                     ? IApplicationThread.DEBUG_WAIT
   5945                     : IApplicationThread.DEBUG_ON;
   5946                 app.debugging = true;
   5947                 if (mDebugTransient) {
   5948                     mDebugApp = mOrigDebugApp;
   5949                     mWaitForDebugger = mOrigWaitForDebugger;
   5950                 }
   5951             }
   5952             String profileFile = app.instrumentationProfileFile;
   5953             ParcelFileDescriptor profileFd = null;
   5954             int samplingInterval = 0;
   5955             boolean profileAutoStop = false;
   5956             if (mProfileApp != null && mProfileApp.equals(processName)) {
   5957                 mProfileProc = app;
   5958                 profileFile = mProfileFile;
   5959                 profileFd = mProfileFd;
   5960                 samplingInterval = mSamplingInterval;
   5961                 profileAutoStop = mAutoStopProfiler;
   5962             }
   5963             boolean enableOpenGlTrace = false;
   5964             if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
   5965                 enableOpenGlTrace = true;
   5966                 mOpenGlTraceApp = null;
   5967             }
   5968 
   5969             // If the app is being launched for restore or full backup, set it up specially
   5970             boolean isRestrictedBackupMode = false;
   5971             if (mBackupTarget != null && mBackupAppName.equals(processName)) {
   5972                 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
   5973                         || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
   5974                         || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
   5975             }
   5976 
   5977             ensurePackageDexOpt(app.instrumentationInfo != null
   5978                     ? app.instrumentationInfo.packageName
   5979                     : app.info.packageName);
   5980             if (app.instrumentationClass != null) {
   5981                 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
   5982             }
   5983             if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
   5984                     + processName + " with config " + mConfiguration);
   5985             ApplicationInfo appInfo = app.instrumentationInfo != null
   5986                     ? app.instrumentationInfo : app.info;
   5987             app.compat = compatibilityInfoForPackageLocked(appInfo);
   5988             if (profileFd != null) {
   5989                 profileFd = profileFd.dup();
   5990             }
   5991             ProfilerInfo profilerInfo = profileFile == null ? null
   5992                     : new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop);
   5993             thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
   5994                     profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
   5995                     app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
   5996                     isRestrictedBackupMode || !normalMode, app.persistent,
   5997                     new Configuration(mConfiguration), app.compat,
   5998                     getCommonServicesLocked(app.isolated),
   5999                     mCoreSettingsObserver.getCoreSettingsLocked());
   6000             updateLruProcessLocked(app, false, null);
   6001             app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
   6002         } catch (Exception e) {
   6003             // todo: Yikes!  What should we do?  For now we will try to
   6004             // start another process, but that could easily get us in
   6005             // an infinite loop of restarting processes...
   6006             Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
   6007 
   6008             app.resetPackageList(mProcessStats);
   6009             app.unlinkDeathRecipient();
   6010             startProcessLocked(app, "bind fail", processName);
   6011             return false;
   6012         }
   6013 
   6014         // Remove this record from the list of starting applications.
   6015         mPersistentStartingProcesses.remove(app);
   6016         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
   6017                 "Attach application locked removing on hold: " + app);
   6018         mProcessesOnHold.remove(app);
   6019 
   6020         boolean badApp = false;
   6021         boolean didSomething = false;
   6022 
   6023         // See if the top visible activity is waiting to run in this process...
   6024         if (normalMode) {
   6025             try {
   6026                 if (mStackSupervisor.attachApplicationLocked(app)) {
   6027                     didSomething = true;
   6028                 }
   6029             } catch (Exception e) {
   6030                 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
   6031                 badApp = true;
   6032             }
   6033         }
   6034 
   6035         // Find any services that should be running in this process...
   6036         if (!badApp) {
   6037             try {
   6038                 didSomething |= mServices.attachApplicationLocked(app, processName);
   6039             } catch (Exception e) {
   6040                 Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
   6041                 badApp = true;
   6042             }
   6043         }
   6044 
   6045         // Check if a next-broadcast receiver is in this process...
   6046         if (!badApp && isPendingBroadcastProcessLocked(pid)) {
   6047             try {
   6048                 didSomething |= sendPendingBroadcastsLocked(app);
   6049             } catch (Exception e) {
   6050                 // If the app died trying to launch the receiver we declare it 'bad'
   6051                 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
   6052                 badApp = true;
   6053             }
   6054         }
   6055 
   6056         // Check whether the next backup agent is in this process...
   6057         if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
   6058             if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
   6059             ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
   6060             try {
   6061                 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
   6062                         compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
   6063                         mBackupTarget.backupMode);
   6064             } catch (Exception e) {
   6065                 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
   6066                 badApp = true;
   6067             }
   6068         }
   6069 
   6070         if (badApp) {
   6071             app.kill("error during init", true);
   6072             handleAppDiedLocked(app, false, true);
   6073             return false;
   6074         }
   6075 
   6076         if (!didSomething) {
   6077             updateOomAdjLocked();
   6078         }
   6079 
   6080         return true;
   6081     }
   6082 
   6083     @Override
   6084     public final void attachApplication(IApplicationThread thread) {
   6085         synchronized (this) {
   6086             int callingPid = Binder.getCallingPid();
   6087             final long origId = Binder.clearCallingIdentity();
   6088             attachApplicationLocked(thread, callingPid);
   6089             Binder.restoreCallingIdentity(origId);
   6090         }
   6091     }
   6092 
   6093     @Override
   6094     public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
   6095         final long origId = Binder.clearCallingIdentity();
   6096         synchronized (this) {
   6097             ActivityStack stack = ActivityRecord.getStackLocked(token);
   6098             if (stack != null) {
   6099                 ActivityRecord r =
   6100                         mStackSupervisor.activityIdleInternalLocked(token, false, config);
   6101                 if (stopProfiling) {
   6102                     if ((mProfileProc == r.app) && (mProfileFd != null)) {
   6103                         try {
   6104                             mProfileFd.close();
   6105                         } catch (IOException e) {
   6106                         }
   6107                         clearProfilerLocked();
   6108                     }
   6109                 }
   6110             }
   6111         }
   6112         Binder.restoreCallingIdentity(origId);
   6113     }
   6114 
   6115     void postFinishBooting(boolean finishBooting, boolean enableScreen) {
   6116         mHandler.sendMessage(mHandler.obtainMessage(FINISH_BOOTING_MSG,
   6117                 finishBooting? 1 : 0, enableScreen ? 1 : 0));
   6118     }
   6119 
   6120     void enableScreenAfterBoot() {
   6121         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
   6122                 SystemClock.uptimeMillis());
   6123         mWindowManager.enableScreenAfterBoot();
   6124 
   6125         synchronized (this) {
   6126             updateEventDispatchingLocked();
   6127         }
   6128     }
   6129 
   6130     @Override
   6131     public void showBootMessage(final CharSequence msg, final boolean always) {
   6132         enforceNotIsolatedCaller("showBootMessage");
   6133         mWindowManager.showBootMessage(msg, always);
   6134     }
   6135 
   6136     @Override
   6137     public void keyguardWaitingForActivityDrawn() {
   6138         enforceNotIsolatedCaller("keyguardWaitingForActivityDrawn");
   6139         final long token = Binder.clearCallingIdentity();
   6140         try {
   6141             synchronized (this) {
   6142                 if (DEBUG_LOCKSCREEN) logLockScreen("");
   6143                 mWindowManager.keyguardWaitingForActivityDrawn();
   6144                 if (mLockScreenShown == LOCK_SCREEN_SHOWN) {
   6145                     mLockScreenShown = LOCK_SCREEN_LEAVING;
   6146                     updateSleepIfNeededLocked();
   6147                 }
   6148             }
   6149         } finally {
   6150             Binder.restoreCallingIdentity(token);
   6151         }
   6152     }
   6153 
   6154     final void finishBooting() {
   6155         synchronized (this) {
   6156             if (!mBootAnimationComplete) {
   6157                 mCallFinishBooting = true;
   6158                 return;
   6159             }
   6160             mCallFinishBooting = false;
   6161         }
   6162 
   6163         ArraySet<String> completedIsas = new ArraySet<String>();
   6164         for (String abi : Build.SUPPORTED_ABIS) {
   6165             Process.establishZygoteConnectionForAbi(abi);
   6166             final String instructionSet = VMRuntime.getInstructionSet(abi);
   6167             if (!completedIsas.contains(instructionSet)) {
   6168                 if (mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi)) != 0) {
   6169                     Slog.e(TAG, "Unable to mark boot complete for abi: " + abi);
   6170                 }
   6171                 completedIsas.add(instructionSet);
   6172             }
   6173         }
   6174 
   6175         IntentFilter pkgFilter = new IntentFilter();
   6176         pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
   6177         pkgFilter.addDataScheme("package");
   6178         mContext.registerReceiver(new BroadcastReceiver() {
   6179             @Override
   6180             public void onReceive(Context context, Intent intent) {
   6181                 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
   6182                 if (pkgs != null) {
   6183                     for (String pkg : pkgs) {
   6184                         synchronized (ActivityManagerService.this) {
   6185                             if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
   6186                                     0, "finished booting")) {
   6187                                 setResultCode(Activity.RESULT_OK);
   6188                                 return;
   6189                             }
   6190                         }
   6191                     }
   6192                 }
   6193             }
   6194         }, pkgFilter);
   6195 
   6196         // Let system services know.
   6197         mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
   6198 
   6199         synchronized (this) {
   6200             // Ensure that any processes we had put on hold are now started
   6201             // up.
   6202             final int NP = mProcessesOnHold.size();
   6203             if (NP > 0) {
   6204                 ArrayList<ProcessRecord> procs =
   6205                     new ArrayList<ProcessRecord>(mProcessesOnHold);
   6206                 for (int ip=0; ip<NP; ip++) {
   6207                     if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
   6208                             + procs.get(ip));
   6209                     startProcessLocked(procs.get(ip), "on-hold", null);
   6210                 }
   6211             }
   6212 
   6213             if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
   6214                 // Start looking for apps that are abusing wake locks.
   6215                 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   6216                 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
   6217                 // Tell anyone interested that we are done booting!
   6218                 SystemProperties.set("sys.boot_completed", "1");
   6219 
   6220                 // And trigger dev.bootcomplete if we are not showing encryption progress
   6221                 if (!"trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt"))
   6222                     || "".equals(SystemProperties.get("vold.encrypt_progress"))) {
   6223                     SystemProperties.set("dev.bootcomplete", "1");
   6224                 }
   6225                 for (int i=0; i<mStartedUsers.size(); i++) {
   6226                     UserStartedState uss = mStartedUsers.valueAt(i);
   6227                     if (uss.mState == UserStartedState.STATE_BOOTING) {
   6228                         uss.mState = UserStartedState.STATE_RUNNING;
   6229                         final int userId = mStartedUsers.keyAt(i);
   6230                         Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
   6231                         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
   6232                         intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
   6233                         broadcastIntentLocked(null, null, intent, null,
   6234                                 new IIntentReceiver.Stub() {
   6235                                     @Override
   6236                                     public void performReceive(Intent intent, int resultCode,
   6237                                             String data, Bundle extras, boolean ordered,
   6238                                             boolean sticky, int sendingUser) {
   6239                                         synchronized (ActivityManagerService.this) {
   6240                                             requestPssAllProcsLocked(SystemClock.uptimeMillis(),
   6241                                                     true, false);
   6242                                         }
   6243                                     }
   6244                                 },
   6245                                 0, null, null,
   6246                                 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
   6247                                 AppOpsManager.OP_NONE, true, false, MY_PID, Process.SYSTEM_UID,
   6248                                 userId);
   6249                     }
   6250                 }
   6251                 scheduleStartProfilesLocked();
   6252             }
   6253         }
   6254     }
   6255 
   6256     @Override
   6257     public void bootAnimationComplete() {
   6258         final boolean callFinishBooting;
   6259         synchronized (this) {
   6260             callFinishBooting = mCallFinishBooting;
   6261             mBootAnimationComplete = true;
   6262         }
   6263         if (callFinishBooting) {
   6264             finishBooting();
   6265         }
   6266     }
   6267 
   6268     @Override
   6269     public void systemBackupRestored() {
   6270         synchronized (this) {
   6271             if (mSystemReady) {
   6272                 mTaskPersister.restoreTasksFromOtherDeviceLocked();
   6273             } else {
   6274                 Slog.w(TAG, "System backup restored before system is ready");
   6275             }
   6276         }
   6277     }
   6278 
   6279     final void ensureBootCompleted() {
   6280         boolean booting;
   6281         boolean enableScreen;
   6282         synchronized (this) {
   6283             booting = mBooting;
   6284             mBooting = false;
   6285             enableScreen = !mBooted;
   6286             mBooted = true;
   6287         }
   6288 
   6289         if (booting) {
   6290             finishBooting();
   6291         }
   6292 
   6293         if (enableScreen) {
   6294             enableScreenAfterBoot();
   6295         }
   6296     }
   6297 
   6298     @Override
   6299     public final void activityResumed(IBinder token) {
   6300         final long origId = Binder.clearCallingIdentity();
   6301         synchronized(this) {
   6302             ActivityStack stack = ActivityRecord.getStackLocked(token);
   6303             if (stack != null) {
   6304                 ActivityRecord.activityResumedLocked(token);
   6305             }
   6306         }
   6307         Binder.restoreCallingIdentity(origId);
   6308     }
   6309 
   6310     @Override
   6311     public final void activityPaused(IBinder token) {
   6312         final long origId = Binder.clearCallingIdentity();
   6313         synchronized(this) {
   6314             ActivityStack stack = ActivityRecord.getStackLocked(token);
   6315             if (stack != null) {
   6316                 stack.activityPausedLocked(token, false);
   6317             }
   6318         }
   6319         Binder.restoreCallingIdentity(origId);
   6320     }
   6321 
   6322     @Override
   6323     public final void activityStopped(IBinder token, Bundle icicle,
   6324             PersistableBundle persistentState, CharSequence description) {
   6325         if (localLOGV) Slog.v(TAG, "Activity stopped: token=" + token);
   6326 
   6327         // Refuse possible leaked file descriptors
   6328         if (icicle != null && icicle.hasFileDescriptors()) {
   6329             throw new IllegalArgumentException("File descriptors passed in Bundle");
   6330         }
   6331 
   6332         final long origId = Binder.clearCallingIdentity();
   6333 
   6334         synchronized (this) {
   6335             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   6336             if (r != null) {
   6337                 r.task.stack.activityStoppedLocked(r, icicle, persistentState, description);
   6338             }
   6339         }
   6340 
   6341         trimApplications();
   6342 
   6343         Binder.restoreCallingIdentity(origId);
   6344     }
   6345 
   6346     @Override
   6347     public final void activityDestroyed(IBinder token) {
   6348         if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
   6349         synchronized (this) {
   6350             ActivityStack stack = ActivityRecord.getStackLocked(token);
   6351             if (stack != null) {
   6352                 stack.activityDestroyedLocked(token, "activityDestroyed");
   6353             }
   6354         }
   6355     }
   6356 
   6357     @Override
   6358     public final void backgroundResourcesReleased(IBinder token) {
   6359         final long origId = Binder.clearCallingIdentity();
   6360         try {
   6361             synchronized (this) {
   6362                 ActivityStack stack = ActivityRecord.getStackLocked(token);
   6363                 if (stack != null) {
   6364                     stack.backgroundResourcesReleased();
   6365                 }
   6366             }
   6367         } finally {
   6368             Binder.restoreCallingIdentity(origId);
   6369         }
   6370     }
   6371 
   6372     @Override
   6373     public final void notifyLaunchTaskBehindComplete(IBinder token) {
   6374         mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
   6375     }
   6376 
   6377     @Override
   6378     public final void notifyEnterAnimationComplete(IBinder token) {
   6379         mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token));
   6380     }
   6381 
   6382     @Override
   6383     public String getCallingPackage(IBinder token) {
   6384         synchronized (this) {
   6385             ActivityRecord r = getCallingRecordLocked(token);
   6386             return r != null ? r.info.packageName : null;
   6387         }
   6388     }
   6389 
   6390     @Override
   6391     public ComponentName getCallingActivity(IBinder token) {
   6392         synchronized (this) {
   6393             ActivityRecord r = getCallingRecordLocked(token);
   6394             return r != null ? r.intent.getComponent() : null;
   6395         }
   6396     }
   6397 
   6398     private ActivityRecord getCallingRecordLocked(IBinder token) {
   6399         ActivityRecord r = ActivityRecord.isInStackLocked(token);
   6400         if (r == null) {
   6401             return null;
   6402         }
   6403         return r.resultTo;
   6404     }
   6405 
   6406     @Override
   6407     public ComponentName getActivityClassForToken(IBinder token) {
   6408         synchronized(this) {
   6409             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   6410             if (r == null) {
   6411                 return null;
   6412             }
   6413             return r.intent.getComponent();
   6414         }
   6415     }
   6416 
   6417     @Override
   6418     public String getPackageForToken(IBinder token) {
   6419         synchronized(this) {
   6420             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   6421             if (r == null) {
   6422                 return null;
   6423             }
   6424             return r.packageName;
   6425         }
   6426     }
   6427 
   6428     @Override
   6429     public IIntentSender getIntentSender(int type,
   6430             String packageName, IBinder token, String resultWho,
   6431             int requestCode, Intent[] intents, String[] resolvedTypes,
   6432             int flags, Bundle options, int userId) {
   6433         enforceNotIsolatedCaller("getIntentSender");
   6434         // Refuse possible leaked file descriptors
   6435         if (intents != null) {
   6436             if (intents.length < 1) {
   6437                 throw new IllegalArgumentException("Intents array length must be >= 1");
   6438             }
   6439             for (int i=0; i<intents.length; i++) {
   6440                 Intent intent = intents[i];
   6441                 if (intent != null) {
   6442                     if (intent.hasFileDescriptors()) {
   6443                         throw new IllegalArgumentException("File descriptors passed in Intent");
   6444                     }
   6445                     if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
   6446                             (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
   6447                         throw new IllegalArgumentException(
   6448                                 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
   6449                     }
   6450                     intents[i] = new Intent(intent);
   6451                 }
   6452             }
   6453             if (resolvedTypes != null && resolvedTypes.length != intents.length) {
   6454                 throw new IllegalArgumentException(
   6455                         "Intent array length does not match resolvedTypes length");
   6456             }
   6457         }
   6458         if (options != null) {
   6459             if (options.hasFileDescriptors()) {
   6460                 throw new IllegalArgumentException("File descriptors passed in options");
   6461             }
   6462         }
   6463 
   6464         synchronized(this) {
   6465             int callingUid = Binder.getCallingUid();
   6466             int origUserId = userId;
   6467             userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
   6468                     type == ActivityManager.INTENT_SENDER_BROADCAST,
   6469                     ALLOW_NON_FULL, "getIntentSender", null);
   6470             if (origUserId == UserHandle.USER_CURRENT) {
   6471                 // We don't want to evaluate this until the pending intent is
   6472                 // actually executed.  However, we do want to always do the
   6473                 // security checking for it above.
   6474                 userId = UserHandle.USER_CURRENT;
   6475             }
   6476             try {
   6477                 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
   6478                     int uid = AppGlobals.getPackageManager()
   6479                             .getPackageUid(packageName, UserHandle.getUserId(callingUid));
   6480                     if (!UserHandle.isSameApp(callingUid, uid)) {
   6481                         String msg = "Permission Denial: getIntentSender() from pid="
   6482                             + Binder.getCallingPid()
   6483                             + ", uid=" + Binder.getCallingUid()
   6484                             + ", (need uid=" + uid + ")"
   6485                             + " is not allowed to send as package " + packageName;
   6486                         Slog.w(TAG, msg);
   6487                         throw new SecurityException(msg);
   6488                     }
   6489                 }
   6490 
   6491                 return getIntentSenderLocked(type, packageName, callingUid, userId,
   6492                         token, resultWho, requestCode, intents, resolvedTypes, flags, options);
   6493 
   6494             } catch (RemoteException e) {
   6495                 throw new SecurityException(e);
   6496             }
   6497         }
   6498     }
   6499 
   6500     IIntentSender getIntentSenderLocked(int type, String packageName,
   6501             int callingUid, int userId, IBinder token, String resultWho,
   6502             int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
   6503             Bundle options) {
   6504         if (DEBUG_MU)
   6505             Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
   6506         ActivityRecord activity = null;
   6507         if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
   6508             activity = ActivityRecord.isInStackLocked(token);
   6509             if (activity == null) {
   6510                 return null;
   6511             }
   6512             if (activity.finishing) {
   6513                 return null;
   6514             }
   6515         }
   6516 
   6517         final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
   6518         final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
   6519         final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
   6520         flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
   6521                 |PendingIntent.FLAG_UPDATE_CURRENT);
   6522 
   6523         PendingIntentRecord.Key key = new PendingIntentRecord.Key(
   6524                 type, packageName, activity, resultWho,
   6525                 requestCode, intents, resolvedTypes, flags, options, userId);
   6526         WeakReference<PendingIntentRecord> ref;
   6527         ref = mIntentSenderRecords.get(key);
   6528         PendingIntentRecord rec = ref != null ? ref.get() : null;
   6529         if (rec != null) {
   6530             if (!cancelCurrent) {
   6531                 if (updateCurrent) {
   6532                     if (rec.key.requestIntent != null) {
   6533                         rec.key.requestIntent.replaceExtras(intents != null ?
   6534                                 intents[intents.length - 1] : null);
   6535                     }
   6536                     if (intents != null) {
   6537                         intents[intents.length-1] = rec.key.requestIntent;
   6538                         rec.key.allIntents = intents;
   6539                         rec.key.allResolvedTypes = resolvedTypes;
   6540                     } else {
   6541                         rec.key.allIntents = null;
   6542                         rec.key.allResolvedTypes = null;
   6543                     }
   6544                 }
   6545                 return rec;
   6546             }
   6547             rec.canceled = true;
   6548             mIntentSenderRecords.remove(key);
   6549         }
   6550         if (noCreate) {
   6551             return rec;
   6552         }
   6553         rec = new PendingIntentRecord(this, key, callingUid);
   6554         mIntentSenderRecords.put(key, rec.ref);
   6555         if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
   6556             if (activity.pendingResults == null) {
   6557                 activity.pendingResults
   6558                         = new HashSet<WeakReference<PendingIntentRecord>>();
   6559             }
   6560             activity.pendingResults.add(rec.ref);
   6561         }
   6562         return rec;
   6563     }
   6564 
   6565     @Override
   6566     public void cancelIntentSender(IIntentSender sender) {
   6567         if (!(sender instanceof PendingIntentRecord)) {
   6568             return;
   6569         }
   6570         synchronized(this) {
   6571             PendingIntentRecord rec = (PendingIntentRecord)sender;
   6572             try {
   6573                 int uid = AppGlobals.getPackageManager()
   6574                         .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
   6575                 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
   6576                     String msg = "Permission Denial: cancelIntentSender() from pid="
   6577                         + Binder.getCallingPid()
   6578                         + ", uid=" + Binder.getCallingUid()
   6579                         + " is not allowed to cancel packges "
   6580                         + rec.key.packageName;
   6581                     Slog.w(TAG, msg);
   6582                     throw new SecurityException(msg);
   6583                 }
   6584             } catch (RemoteException e) {
   6585                 throw new SecurityException(e);
   6586             }
   6587             cancelIntentSenderLocked(rec, true);
   6588         }
   6589     }
   6590 
   6591     void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
   6592         rec.canceled = true;
   6593         mIntentSenderRecords.remove(rec.key);
   6594         if (cleanActivity && rec.key.activity != null) {
   6595             rec.key.activity.pendingResults.remove(rec.ref);
   6596         }
   6597     }
   6598 
   6599     @Override
   6600     public String getPackageForIntentSender(IIntentSender pendingResult) {
   6601         if (!(pendingResult instanceof PendingIntentRecord)) {
   6602             return null;
   6603         }
   6604         try {
   6605             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
   6606             return res.key.packageName;
   6607         } catch (ClassCastException e) {
   6608         }
   6609         return null;
   6610     }
   6611 
   6612     @Override
   6613     public int getUidForIntentSender(IIntentSender sender) {
   6614         if (sender instanceof PendingIntentRecord) {
   6615             try {
   6616                 PendingIntentRecord res = (PendingIntentRecord)sender;
   6617                 return res.uid;
   6618             } catch (ClassCastException e) {
   6619             }
   6620         }
   6621         return -1;
   6622     }
   6623 
   6624     @Override
   6625     public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
   6626         if (!(pendingResult instanceof PendingIntentRecord)) {
   6627             return false;
   6628         }
   6629         try {
   6630             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
   6631             if (res.key.allIntents == null) {
   6632                 return false;
   6633             }
   6634             for (int i=0; i<res.key.allIntents.length; i++) {
   6635                 Intent intent = res.key.allIntents[i];
   6636                 if (intent.getPackage() != null && intent.getComponent() != null) {
   6637                     return false;
   6638                 }
   6639             }
   6640             return true;
   6641         } catch (ClassCastException e) {
   6642         }
   6643         return false;
   6644     }
   6645 
   6646     @Override
   6647     public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
   6648         if (!(pendingResult instanceof PendingIntentRecord)) {
   6649             return false;
   6650         }
   6651         try {
   6652             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
   6653             if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
   6654                 return true;
   6655             }
   6656             return false;
   6657         } catch (ClassCastException e) {
   6658         }
   6659         return false;
   6660     }
   6661 
   6662     @Override
   6663     public Intent getIntentForIntentSender(IIntentSender pendingResult) {
   6664         if (!(pendingResult instanceof PendingIntentRecord)) {
   6665             return null;
   6666         }
   6667         try {
   6668             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
   6669             return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
   6670         } catch (ClassCastException e) {
   6671         }
   6672         return null;
   6673     }
   6674 
   6675     @Override
   6676     public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
   6677         if (!(pendingResult instanceof PendingIntentRecord)) {
   6678             return null;
   6679         }
   6680         try {
   6681             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
   6682             Intent intent = res.key.requestIntent;
   6683             if (intent != null) {
   6684                 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
   6685                         || res.lastTagPrefix.equals(prefix))) {
   6686                     return res.lastTag;
   6687                 }
   6688                 res.lastTagPrefix = prefix;
   6689                 StringBuilder sb = new StringBuilder(128);
   6690                 if (prefix != null) {
   6691                     sb.append(prefix);
   6692                 }
   6693                 if (intent.getAction() != null) {
   6694                     sb.append(intent.getAction());
   6695                 } else if (intent.getComponent() != null) {
   6696                     intent.getComponent().appendShortString(sb);
   6697                 } else {
   6698                     sb.append("?");
   6699                 }
   6700                 return res.lastTag = sb.toString();
   6701             }
   6702         } catch (ClassCastException e) {
   6703         }
   6704         return null;
   6705     }
   6706 
   6707     @Override
   6708     public void setProcessLimit(int max) {
   6709         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
   6710                 "setProcessLimit()");
   6711         synchronized (this) {
   6712             mProcessLimit = max < 0 ? ProcessList.MAX_CACHED_APPS : max;
   6713             mProcessLimitOverride = max;
   6714         }
   6715         trimApplications();
   6716     }
   6717 
   6718     @Override
   6719     public int getProcessLimit() {
   6720         synchronized (this) {
   6721             return mProcessLimitOverride;
   6722         }
   6723     }
   6724 
   6725     void foregroundTokenDied(ForegroundToken token) {
   6726         synchronized (ActivityManagerService.this) {
   6727             synchronized (mPidsSelfLocked) {
   6728                 ForegroundToken cur
   6729                     = mForegroundProcesses.get(token.pid);
   6730                 if (cur != token) {
   6731                     return;
   6732                 }
   6733                 mForegroundProcesses.remove(token.pid);
   6734                 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
   6735                 if (pr == null) {
   6736                     return;
   6737                 }
   6738                 pr.forcingToForeground = null;
   6739                 updateProcessForegroundLocked(pr, false, false);
   6740             }
   6741             updateOomAdjLocked();
   6742         }
   6743     }
   6744 
   6745     @Override
   6746     public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
   6747         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
   6748                 "setProcessForeground()");
   6749         synchronized(this) {
   6750             boolean changed = false;
   6751 
   6752             synchronized (mPidsSelfLocked) {
   6753                 ProcessRecord pr = mPidsSelfLocked.get(pid);
   6754                 if (pr == null && isForeground) {
   6755                     Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
   6756                     return;
   6757                 }
   6758                 ForegroundToken oldToken = mForegroundProcesses.get(pid);
   6759                 if (oldToken != null) {
   6760                     oldToken.token.unlinkToDeath(oldToken, 0);
   6761                     mForegroundProcesses.remove(pid);
   6762                     if (pr != null) {
   6763                         pr.forcingToForeground = null;
   6764                     }
   6765                     changed = true;
   6766                 }
   6767                 if (isForeground && token != null) {
   6768                     ForegroundToken newToken = new ForegroundToken() {
   6769                         @Override
   6770                         public void binderDied() {
   6771                             foregroundTokenDied(this);
   6772                         }
   6773                     };
   6774                     newToken.pid = pid;
   6775                     newToken.token = token;
   6776                     try {
   6777                         token.linkToDeath(newToken, 0);
   6778                         mForegroundProcesses.put(pid, newToken);
   6779                         pr.forcingToForeground = token;
   6780                         changed = true;
   6781                     } catch (RemoteException e) {
   6782                         // If the process died while doing this, we will later
   6783                         // do the cleanup with the process death link.
   6784                     }
   6785                 }
   6786             }
   6787 
   6788             if (changed) {
   6789                 updateOomAdjLocked();
   6790             }
   6791         }
   6792     }
   6793 
   6794     // =========================================================
   6795     // PERMISSIONS
   6796     // =========================================================
   6797 
   6798     static class PermissionController extends IPermissionController.Stub {
   6799         ActivityManagerService mActivityManagerService;
   6800         PermissionController(ActivityManagerService activityManagerService) {
   6801             mActivityManagerService = activityManagerService;
   6802         }
   6803 
   6804         @Override
   6805         public boolean checkPermission(String permission, int pid, int uid) {
   6806             return mActivityManagerService.checkPermission(permission, pid,
   6807                     uid) == PackageManager.PERMISSION_GRANTED;
   6808         }
   6809     }
   6810 
   6811     class IntentFirewallInterface implements IntentFirewall.AMSInterface {
   6812         @Override
   6813         public int checkComponentPermission(String permission, int pid, int uid,
   6814                 int owningUid, boolean exported) {
   6815             return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
   6816                     owningUid, exported);
   6817         }
   6818 
   6819         @Override
   6820         public Object getAMSLock() {
   6821             return ActivityManagerService.this;
   6822         }
   6823     }
   6824 
   6825     /**
   6826      * This can be called with or without the global lock held.
   6827      */
   6828     int checkComponentPermission(String permission, int pid, int uid,
   6829             int owningUid, boolean exported) {
   6830         if (pid == MY_PID) {
   6831             return PackageManager.PERMISSION_GRANTED;
   6832         }
   6833         return ActivityManager.checkComponentPermission(permission, uid,
   6834                 owningUid, exported);
   6835     }
   6836 
   6837     /**
   6838      * As the only public entry point for permissions checking, this method
   6839      * can enforce the semantic that requesting a check on a null global
   6840      * permission is automatically denied.  (Internally a null permission
   6841      * string is used when calling {@link #checkComponentPermission} in cases
   6842      * when only uid-based security is needed.)
   6843      *
   6844      * This can be called with or without the global lock held.
   6845      */
   6846     @Override
   6847     public int checkPermission(String permission, int pid, int uid) {
   6848         if (permission == null) {
   6849             return PackageManager.PERMISSION_DENIED;
   6850         }
   6851         return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
   6852     }
   6853 
   6854     @Override
   6855     public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) {
   6856         if (permission == null) {
   6857             return PackageManager.PERMISSION_DENIED;
   6858         }
   6859 
   6860         // We might be performing an operation on behalf of an indirect binder
   6861         // invocation, e.g. via {@link #openContentUri}.  Check and adjust the
   6862         // client identity accordingly before proceeding.
   6863         Identity tlsIdentity = sCallerIdentity.get();
   6864         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
   6865             Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
   6866                     + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
   6867             uid = tlsIdentity.uid;
   6868             pid = tlsIdentity.pid;
   6869         }
   6870 
   6871         return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
   6872     }
   6873 
   6874     /**
   6875      * Binder IPC calls go through the public entry point.
   6876      * This can be called with or without the global lock held.
   6877      */
   6878     int checkCallingPermission(String permission) {
   6879         return checkPermission(permission,
   6880                 Binder.getCallingPid(),
   6881                 UserHandle.getAppId(Binder.getCallingUid()));
   6882     }
   6883 
   6884     /**
   6885      * This can be called with or without the global lock held.
   6886      */
   6887     void enforceCallingPermission(String permission, String func) {
   6888         if (checkCallingPermission(permission)
   6889                 == PackageManager.PERMISSION_GRANTED) {
   6890             return;
   6891         }
   6892 
   6893         String msg = "Permission Denial: " + func + " from pid="
   6894                 + Binder.getCallingPid()
   6895                 + ", uid=" + Binder.getCallingUid()
   6896                 + " requires " + permission;
   6897         Slog.w(TAG, msg);
   6898         throw new SecurityException(msg);
   6899     }
   6900 
   6901     /**
   6902      * Determine if UID is holding permissions required to access {@link Uri} in
   6903      * the given {@link ProviderInfo}. Final permission checking is always done
   6904      * in {@link ContentProvider}.
   6905      */
   6906     private final boolean checkHoldingPermissionsLocked(
   6907             IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) {
   6908         if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   6909                 "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid);
   6910         if (UserHandle.getUserId(uid) != grantUri.sourceUserId) {
   6911             if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true)
   6912                     != PERMISSION_GRANTED) {
   6913                 return false;
   6914             }
   6915         }
   6916         return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true);
   6917     }
   6918 
   6919     private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi,
   6920             GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) {
   6921         if (pi.applicationInfo.uid == uid) {
   6922             return true;
   6923         } else if (!pi.exported) {
   6924             return false;
   6925         }
   6926 
   6927         boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
   6928         boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
   6929         try {
   6930             // check if target holds top-level <provider> permissions
   6931             if (!readMet && pi.readPermission != null && considerUidPermissions
   6932                     && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
   6933                 readMet = true;
   6934             }
   6935             if (!writeMet && pi.writePermission != null && considerUidPermissions
   6936                     && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
   6937                 writeMet = true;
   6938             }
   6939 
   6940             // track if unprotected read/write is allowed; any denied
   6941             // <path-permission> below removes this ability
   6942             boolean allowDefaultRead = pi.readPermission == null;
   6943             boolean allowDefaultWrite = pi.writePermission == null;
   6944 
   6945             // check if target holds any <path-permission> that match uri
   6946             final PathPermission[] pps = pi.pathPermissions;
   6947             if (pps != null) {
   6948                 final String path = grantUri.uri.getPath();
   6949                 int i = pps.length;
   6950                 while (i > 0 && (!readMet || !writeMet)) {
   6951                     i--;
   6952                     PathPermission pp = pps[i];
   6953                     if (pp.match(path)) {
   6954                         if (!readMet) {
   6955                             final String pprperm = pp.getReadPermission();
   6956                             if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
   6957                                     + pprperm + " for " + pp.getPath()
   6958                                     + ": match=" + pp.match(path)
   6959                                     + " check=" + pm.checkUidPermission(pprperm, uid));
   6960                             if (pprperm != null) {
   6961                                 if (considerUidPermissions && pm.checkUidPermission(pprperm, uid)
   6962                                         == PERMISSION_GRANTED) {
   6963                                     readMet = true;
   6964                                 } else {
   6965                                     allowDefaultRead = false;
   6966                                 }
   6967                             }
   6968                         }
   6969                         if (!writeMet) {
   6970                             final String ppwperm = pp.getWritePermission();
   6971                             if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
   6972                                     + ppwperm + " for " + pp.getPath()
   6973                                     + ": match=" + pp.match(path)
   6974                                     + " check=" + pm.checkUidPermission(ppwperm, uid));
   6975                             if (ppwperm != null) {
   6976                                 if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid)
   6977                                         == PERMISSION_GRANTED) {
   6978                                     writeMet = true;
   6979                                 } else {
   6980                                     allowDefaultWrite = false;
   6981                                 }
   6982                             }
   6983                         }
   6984                     }
   6985                 }
   6986             }
   6987 
   6988             // grant unprotected <provider> read/write, if not blocked by
   6989             // <path-permission> above
   6990             if (allowDefaultRead) readMet = true;
   6991             if (allowDefaultWrite) writeMet = true;
   6992 
   6993         } catch (RemoteException e) {
   6994             return false;
   6995         }
   6996 
   6997         return readMet && writeMet;
   6998     }
   6999 
   7000     private ProviderInfo getProviderInfoLocked(String authority, int userHandle) {
   7001         ProviderInfo pi = null;
   7002         ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle);
   7003         if (cpr != null) {
   7004             pi = cpr.info;
   7005         } else {
   7006             try {
   7007                 pi = AppGlobals.getPackageManager().resolveContentProvider(
   7008                         authority, PackageManager.GET_URI_PERMISSION_PATTERNS, userHandle);
   7009             } catch (RemoteException ex) {
   7010             }
   7011         }
   7012         return pi;
   7013     }
   7014 
   7015     private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) {
   7016         final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
   7017         if (targetUris != null) {
   7018             return targetUris.get(grantUri);
   7019         }
   7020         return null;
   7021     }
   7022 
   7023     private UriPermission findOrCreateUriPermissionLocked(String sourcePkg,
   7024             String targetPkg, int targetUid, GrantUri grantUri) {
   7025         ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
   7026         if (targetUris == null) {
   7027             targetUris = Maps.newArrayMap();
   7028             mGrantedUriPermissions.put(targetUid, targetUris);
   7029         }
   7030 
   7031         UriPermission perm = targetUris.get(grantUri);
   7032         if (perm == null) {
   7033             perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri);
   7034             targetUris.put(grantUri, perm);
   7035         }
   7036 
   7037         return perm;
   7038     }
   7039 
   7040     private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid,
   7041             final int modeFlags) {
   7042         final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0;
   7043         final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE
   7044                 : UriPermission.STRENGTH_OWNED;
   7045 
   7046         // Root gets to do everything.
   7047         if (uid == 0) {
   7048             return true;
   7049         }
   7050 
   7051         final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
   7052         if (perms == null) return false;
   7053 
   7054         // First look for exact match
   7055         final UriPermission exactPerm = perms.get(grantUri);
   7056         if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) {
   7057             return true;
   7058         }
   7059 
   7060         // No exact match, look for prefixes
   7061         final int N = perms.size();
   7062         for (int i = 0; i < N; i++) {
   7063             final UriPermission perm = perms.valueAt(i);
   7064             if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri)
   7065                     && perm.getStrength(modeFlags) >= minStrength) {
   7066                 return true;
   7067             }
   7068         }
   7069 
   7070         return false;
   7071     }
   7072 
   7073     /**
   7074      * @param uri This uri must NOT contain an embedded userId.
   7075      * @param userId The userId in which the uri is to be resolved.
   7076      */
   7077     @Override
   7078     public int checkUriPermission(Uri uri, int pid, int uid,
   7079             final int modeFlags, int userId, IBinder callerToken) {
   7080         enforceNotIsolatedCaller("checkUriPermission");
   7081 
   7082         // Another redirected-binder-call permissions check as in
   7083         // {@link checkPermissionWithToken}.
   7084         Identity tlsIdentity = sCallerIdentity.get();
   7085         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
   7086             uid = tlsIdentity.uid;
   7087             pid = tlsIdentity.pid;
   7088         }
   7089 
   7090         // Our own process gets to do everything.
   7091         if (pid == MY_PID) {
   7092             return PackageManager.PERMISSION_GRANTED;
   7093         }
   7094         synchronized (this) {
   7095             return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags)
   7096                     ? PackageManager.PERMISSION_GRANTED
   7097                     : PackageManager.PERMISSION_DENIED;
   7098         }
   7099     }
   7100 
   7101     /**
   7102      * Check if the targetPkg can be granted permission to access uri by
   7103      * the callingUid using the given modeFlags.  Throws a security exception
   7104      * if callingUid is not allowed to do this.  Returns the uid of the target
   7105      * if the URI permission grant should be performed; returns -1 if it is not
   7106      * needed (for example targetPkg already has permission to access the URI).
   7107      * If you already know the uid of the target, you can supply it in
   7108      * lastTargetUid else set that to -1.
   7109      */
   7110     int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
   7111             final int modeFlags, int lastTargetUid) {
   7112         if (!Intent.isAccessUriMode(modeFlags)) {
   7113             return -1;
   7114         }
   7115 
   7116         if (targetPkg != null) {
   7117             if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   7118                     "Checking grant " + targetPkg + " permission to " + grantUri);
   7119         }
   7120 
   7121         final IPackageManager pm = AppGlobals.getPackageManager();
   7122 
   7123         // If this is not a content: uri, we can't do anything with it.
   7124         if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) {
   7125             if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   7126                     "Can't grant URI permission for non-content URI: " + grantUri);
   7127             return -1;
   7128         }
   7129 
   7130         final String authority = grantUri.uri.getAuthority();
   7131         final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
   7132         if (pi == null) {
   7133             Slog.w(TAG, "No content provider found for permission check: " +
   7134                     grantUri.uri.toSafeString());
   7135             return -1;
   7136         }
   7137 
   7138         int targetUid = lastTargetUid;
   7139         if (targetUid < 0 && targetPkg != null) {
   7140             try {
   7141                 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
   7142                 if (targetUid < 0) {
   7143                     if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   7144                             "Can't grant URI permission no uid for: " + targetPkg);
   7145                     return -1;
   7146                 }
   7147             } catch (RemoteException ex) {
   7148                 return -1;
   7149             }
   7150         }
   7151 
   7152         if (targetUid >= 0) {
   7153             // First...  does the target actually need this permission?
   7154             if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) {
   7155                 // No need to grant the target this permission.
   7156                 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   7157                         "Target " + targetPkg + " already has full permission to " + grantUri);
   7158                 return -1;
   7159             }
   7160         } else {
   7161             // First...  there is no target package, so can anyone access it?
   7162             boolean allowed = pi.exported;
   7163             if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
   7164                 if (pi.readPermission != null) {
   7165                     allowed = false;
   7166                 }
   7167             }
   7168             if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
   7169                 if (pi.writePermission != null) {
   7170                     allowed = false;
   7171                 }
   7172             }
   7173             if (allowed) {
   7174                 return -1;
   7175             }
   7176         }
   7177 
   7178         /* There is a special cross user grant if:
   7179          * - The target is on another user.
   7180          * - Apps on the current user can access the uri without any uid permissions.
   7181          * In this case, we grant a uri permission, even if the ContentProvider does not normally
   7182          * grant uri permissions.
   7183          */
   7184         boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId
   7185                 && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid,
   7186                 modeFlags, false /*without considering the uid permissions*/);
   7187 
   7188         // Second...  is the provider allowing granting of URI permissions?
   7189         if (!specialCrossUserGrant) {
   7190             if (!pi.grantUriPermissions) {
   7191                 throw new SecurityException("Provider " + pi.packageName
   7192                         + "/" + pi.name
   7193                         + " does not allow granting of Uri permissions (uri "
   7194                         + grantUri + ")");
   7195             }
   7196             if (pi.uriPermissionPatterns != null) {
   7197                 final int N = pi.uriPermissionPatterns.length;
   7198                 boolean allowed = false;
   7199                 for (int i=0; i<N; i++) {
   7200                     if (pi.uriPermissionPatterns[i] != null
   7201                             && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) {
   7202                         allowed = true;
   7203                         break;
   7204                     }
   7205                 }
   7206                 if (!allowed) {
   7207                     throw new SecurityException("Provider " + pi.packageName
   7208                             + "/" + pi.name
   7209                             + " does not allow granting of permission to path of Uri "
   7210                             + grantUri);
   7211                 }
   7212             }
   7213         }
   7214 
   7215         // Third...  does the caller itself have permission to access
   7216         // this uri?
   7217         if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
   7218             if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
   7219                 // Require they hold a strong enough Uri permission
   7220                 if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) {
   7221                     throw new SecurityException("Uid " + callingUid
   7222                             + " does not have permission to uri " + grantUri);
   7223                 }
   7224             }
   7225         }
   7226         return targetUid;
   7227     }
   7228 
   7229     /**
   7230      * @param uri This uri must NOT contain an embedded userId.
   7231      * @param userId The userId in which the uri is to be resolved.
   7232      */
   7233     @Override
   7234     public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri,
   7235             final int modeFlags, int userId) {
   7236         enforceNotIsolatedCaller("checkGrantUriPermission");
   7237         synchronized(this) {
   7238             return checkGrantUriPermissionLocked(callingUid, targetPkg,
   7239                     new GrantUri(userId, uri, false), modeFlags, -1);
   7240         }
   7241     }
   7242 
   7243     void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri,
   7244             final int modeFlags, UriPermissionOwner owner) {
   7245         if (!Intent.isAccessUriMode(modeFlags)) {
   7246             return;
   7247         }
   7248 
   7249         // So here we are: the caller has the assumed permission
   7250         // to the uri, and the target doesn't.  Let's now give this to
   7251         // the target.
   7252 
   7253         if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   7254                 "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri);
   7255 
   7256         final String authority = grantUri.uri.getAuthority();
   7257         final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
   7258         if (pi == null) {
   7259             Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString());
   7260             return;
   7261         }
   7262 
   7263         if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
   7264             grantUri.prefix = true;
   7265         }
   7266         final UriPermission perm = findOrCreateUriPermissionLocked(
   7267                 pi.packageName, targetPkg, targetUid, grantUri);
   7268         perm.grantModes(modeFlags, owner);
   7269     }
   7270 
   7271     void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
   7272             final int modeFlags, UriPermissionOwner owner, int targetUserId) {
   7273         if (targetPkg == null) {
   7274             throw new NullPointerException("targetPkg");
   7275         }
   7276         int targetUid;
   7277         final IPackageManager pm = AppGlobals.getPackageManager();
   7278         try {
   7279             targetUid = pm.getPackageUid(targetPkg, targetUserId);
   7280         } catch (RemoteException ex) {
   7281             return;
   7282         }
   7283 
   7284         targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags,
   7285                 targetUid);
   7286         if (targetUid < 0) {
   7287             return;
   7288         }
   7289 
   7290         grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags,
   7291                 owner);
   7292     }
   7293 
   7294     static class NeededUriGrants extends ArrayList<GrantUri> {
   7295         final String targetPkg;
   7296         final int targetUid;
   7297         final int flags;
   7298 
   7299         NeededUriGrants(String targetPkg, int targetUid, int flags) {
   7300             this.targetPkg = targetPkg;
   7301             this.targetUid = targetUid;
   7302             this.flags = flags;
   7303         }
   7304     }
   7305 
   7306     /**
   7307      * Like checkGrantUriPermissionLocked, but takes an Intent.
   7308      */
   7309     NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
   7310             String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) {
   7311         if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   7312                 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
   7313                 + " clip=" + (intent != null ? intent.getClipData() : null)
   7314                 + " from " + intent + "; flags=0x"
   7315                 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
   7316 
   7317         if (targetPkg == null) {
   7318             throw new NullPointerException("targetPkg");
   7319         }
   7320 
   7321         if (intent == null) {
   7322             return null;
   7323         }
   7324         Uri data = intent.getData();
   7325         ClipData clip = intent.getClipData();
   7326         if (data == null && clip == null) {
   7327             return null;
   7328         }
   7329         // Default userId for uris in the intent (if they don't specify it themselves)
   7330         int contentUserHint = intent.getContentUserHint();
   7331         if (contentUserHint == UserHandle.USER_CURRENT) {
   7332             contentUserHint = UserHandle.getUserId(callingUid);
   7333         }
   7334         final IPackageManager pm = AppGlobals.getPackageManager();
   7335         int targetUid;
   7336         if (needed != null) {
   7337             targetUid = needed.targetUid;
   7338         } else {
   7339             try {
   7340                 targetUid = pm.getPackageUid(targetPkg, targetUserId);
   7341             } catch (RemoteException ex) {
   7342                 return null;
   7343             }
   7344             if (targetUid < 0) {
   7345                 if (DEBUG_URI_PERMISSION) {
   7346                     Slog.v(TAG, "Can't grant URI permission no uid for: " + targetPkg
   7347                             + " on user " + targetUserId);
   7348                 }
   7349                 return null;
   7350             }
   7351         }
   7352         if (data != null) {
   7353             GrantUri grantUri = GrantUri.resolve(contentUserHint, data);
   7354             targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
   7355                     targetUid);
   7356             if (targetUid > 0) {
   7357                 if (needed == null) {
   7358                     needed = new NeededUriGrants(targetPkg, targetUid, mode);
   7359                 }
   7360                 needed.add(grantUri);
   7361             }
   7362         }
   7363         if (clip != null) {
   7364             for (int i=0; i<clip.getItemCount(); i++) {
   7365                 Uri uri = clip.getItemAt(i).getUri();
   7366                 if (uri != null) {
   7367                     GrantUri grantUri = GrantUri.resolve(contentUserHint, uri);
   7368                     targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
   7369                             targetUid);
   7370                     if (targetUid > 0) {
   7371                         if (needed == null) {
   7372                             needed = new NeededUriGrants(targetPkg, targetUid, mode);
   7373                         }
   7374                         needed.add(grantUri);
   7375                     }
   7376                 } else {
   7377                     Intent clipIntent = clip.getItemAt(i).getIntent();
   7378                     if (clipIntent != null) {
   7379                         NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
   7380                                 callingUid, targetPkg, clipIntent, mode, needed, targetUserId);
   7381                         if (newNeeded != null) {
   7382                             needed = newNeeded;
   7383                         }
   7384                     }
   7385                 }
   7386             }
   7387         }
   7388 
   7389         return needed;
   7390     }
   7391 
   7392     /**
   7393      * Like grantUriPermissionUncheckedLocked, but takes an Intent.
   7394      */
   7395     void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
   7396             UriPermissionOwner owner) {
   7397         if (needed != null) {
   7398             for (int i=0; i<needed.size(); i++) {
   7399                 GrantUri grantUri = needed.get(i);
   7400                 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
   7401                         grantUri, needed.flags, owner);
   7402             }
   7403         }
   7404     }
   7405 
   7406     void grantUriPermissionFromIntentLocked(int callingUid,
   7407             String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) {
   7408         NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
   7409                 intent, intent != null ? intent.getFlags() : 0, null, targetUserId);
   7410         if (needed == null) {
   7411             return;
   7412         }
   7413 
   7414         grantUriPermissionUncheckedFromIntentLocked(needed, owner);
   7415     }
   7416 
   7417     /**
   7418      * @param uri This uri must NOT contain an embedded userId.
   7419      * @param userId The userId in which the uri is to be resolved.
   7420      */
   7421     @Override
   7422     public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
   7423             final int modeFlags, int userId) {
   7424         enforceNotIsolatedCaller("grantUriPermission");
   7425         GrantUri grantUri = new GrantUri(userId, uri, false);
   7426         synchronized(this) {
   7427             final ProcessRecord r = getRecordForAppLocked(caller);
   7428             if (r == null) {
   7429                 throw new SecurityException("Unable to find app for caller "
   7430                         + caller
   7431                         + " when granting permission to uri " + grantUri);
   7432             }
   7433             if (targetPkg == null) {
   7434                 throw new IllegalArgumentException("null target");
   7435             }
   7436             if (grantUri == null) {
   7437                 throw new IllegalArgumentException("null uri");
   7438             }
   7439 
   7440             Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
   7441                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
   7442                     | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
   7443                     | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
   7444 
   7445             grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null,
   7446                     UserHandle.getUserId(r.uid));
   7447         }
   7448     }
   7449 
   7450     void removeUriPermissionIfNeededLocked(UriPermission perm) {
   7451         if (perm.modeFlags == 0) {
   7452             final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
   7453                     perm.targetUid);
   7454             if (perms != null) {
   7455                 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
   7456                         "Removing " + perm.targetUid + " permission to " + perm.uri);
   7457 
   7458                 perms.remove(perm.uri);
   7459                 if (perms.isEmpty()) {
   7460                     mGrantedUriPermissions.remove(perm.targetUid);
   7461                 }
   7462             }
   7463         }
   7464     }
   7465 
   7466     private void revokeUriPermissionLocked(int callingUid, GrantUri grantUri, final int modeFlags) {
   7467         if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Revoking all granted permissions to " + grantUri);
   7468 
   7469         final IPackageManager pm = AppGlobals.getPackageManager();
   7470         final String authority = grantUri.uri.getAuthority();
   7471         final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
   7472         if (pi == null) {
   7473             Slog.w(TAG, "No content provider found for permission revoke: "
   7474                     + grantUri.toSafeString());
   7475             return;
   7476         }
   7477 
   7478         // Does the caller have this permission on the URI?
   7479         if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
   7480             // If they don't have direct access to the URI, then revoke any
   7481             // ownerless URI permissions that have been granted to them.
   7482             final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
   7483             if (perms != null) {
   7484                 boolean persistChanged = false;
   7485                 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
   7486                     final UriPermission perm = it.next();
   7487                     if (perm.uri.sourceUserId == grantUri.sourceUserId
   7488                             && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) {
   7489                         if (DEBUG_URI_PERMISSION)
   7490                             Slog.v(TAG, "Revoking non-owned " + perm.targetUid +
   7491                                     " permission to " + perm.uri);
   7492                         persistChanged |= perm.revokeModes(
   7493                                 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, false);
   7494                         if (perm.modeFlags == 0) {
   7495                             it.remove();
   7496                         }
   7497                     }
   7498                 }
   7499                 if (perms.isEmpty()) {
   7500                     mGrantedUriPermissions.remove(callingUid);
   7501                 }
   7502                 if (persistChanged) {
   7503                     schedulePersistUriGrants();
   7504                 }
   7505             }
   7506             return;
   7507         }
   7508 
   7509         boolean persistChanged = false;
   7510 
   7511         // Go through all of the permissions and remove any that match.
   7512         int N = mGrantedUriPermissions.size();
   7513         for (int i = 0; i < N; i++) {
   7514             final int targetUid = mGrantedUriPermissions.keyAt(i);
   7515             final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
   7516 
   7517             for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
   7518                 final UriPermission perm = it.next();
   7519                 if (perm.uri.sourceUserId == grantUri.sourceUserId
   7520                         && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) {
   7521                     if (DEBUG_URI_PERMISSION)
   7522                         Slog.v(TAG,
   7523                                 "Revoking " + perm.targetUid + " permission to " + perm.uri);
   7524                     persistChanged |= perm.revokeModes(
   7525                             modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, true);
   7526                     if (perm.modeFlags == 0) {
   7527                         it.remove();
   7528                     }
   7529                 }
   7530             }
   7531 
   7532             if (perms.isEmpty()) {
   7533                 mGrantedUriPermissions.remove(targetUid);
   7534                 N--;
   7535                 i--;
   7536             }
   7537         }
   7538 
   7539         if (persistChanged) {
   7540             schedulePersistUriGrants();
   7541         }
   7542     }
   7543 
   7544     /**
   7545      * @param uri This uri must NOT contain an embedded userId.
   7546      * @param userId The userId in which the uri is to be resolved.
   7547      */
   7548     @Override
   7549     public void revokeUriPermission(IApplicationThread caller, Uri uri, final int modeFlags,
   7550             int userId) {
   7551         enforceNotIsolatedCaller("revokeUriPermission");
   7552         synchronized(this) {
   7553             final ProcessRecord r = getRecordForAppLocked(caller);
   7554             if (r == null) {
   7555                 throw new SecurityException("Unable to find app for caller "
   7556                         + caller
   7557                         + " when revoking permission to uri " + uri);
   7558             }
   7559             if (uri == null) {
   7560                 Slog.w(TAG, "revokeUriPermission: null uri");
   7561                 return;
   7562             }
   7563 
   7564             if (!Intent.isAccessUriMode(modeFlags)) {
   7565                 return;
   7566             }
   7567 
   7568             final IPackageManager pm = AppGlobals.getPackageManager();
   7569             final String authority = uri.getAuthority();
   7570             final ProviderInfo pi = getProviderInfoLocked(authority, userId);
   7571             if (pi == null) {
   7572                 Slog.w(TAG, "No content provider found for permission revoke: "
   7573                         + uri.toSafeString());
   7574                 return;
   7575             }
   7576 
   7577             revokeUriPermissionLocked(r.uid, new GrantUri(userId, uri, false), modeFlags);
   7578         }
   7579     }
   7580 
   7581     /**
   7582      * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the
   7583      * given package.
   7584      *
   7585      * @param packageName Package name to match, or {@code null} to apply to all
   7586      *            packages.
   7587      * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply
   7588      *            to all users.
   7589      * @param persistable If persistable grants should be removed.
   7590      */
   7591     private void removeUriPermissionsForPackageLocked(
   7592             String packageName, int userHandle, boolean persistable) {
   7593         if (userHandle == UserHandle.USER_ALL && packageName == null) {
   7594             throw new IllegalArgumentException("Must narrow by either package or user");
   7595         }
   7596 
   7597         boolean persistChanged = false;
   7598 
   7599         int N = mGrantedUriPermissions.size();
   7600         for (int i = 0; i < N; i++) {
   7601             final int targetUid = mGrantedUriPermissions.keyAt(i);
   7602             final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
   7603 
   7604             // Only inspect grants matching user
   7605             if (userHandle == UserHandle.USER_ALL
   7606                     || userHandle == UserHandle.getUserId(targetUid)) {
   7607                 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
   7608                     final UriPermission perm = it.next();
   7609 
   7610                     // Only inspect grants matching package
   7611                     if (packageName == null || perm.sourcePkg.equals(packageName)
   7612                             || perm.targetPkg.equals(packageName)) {
   7613                         persistChanged |= perm.revokeModes(persistable
   7614                                 ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, true);
   7615 
   7616                         // Only remove when no modes remain; any persisted grants
   7617                         // will keep this alive.
   7618                         if (perm.modeFlags == 0) {
   7619                             it.remove();
   7620                         }
   7621                     }
   7622                 }
   7623 
   7624                 if (perms.isEmpty()) {
   7625                     mGrantedUriPermissions.remove(targetUid);
   7626                     N--;
   7627                     i--;
   7628                 }
   7629             }
   7630         }
   7631 
   7632         if (persistChanged) {
   7633             schedulePersistUriGrants();
   7634         }
   7635     }
   7636 
   7637     @Override
   7638     public IBinder newUriPermissionOwner(String name) {
   7639         enforceNotIsolatedCaller("newUriPermissionOwner");
   7640         synchronized(this) {
   7641             UriPermissionOwner owner = new UriPermissionOwner(this, name);
   7642             return owner.getExternalTokenLocked();
   7643         }
   7644     }
   7645 
   7646     /**
   7647      * @param uri This uri must NOT contain an embedded userId.
   7648      * @param sourceUserId The userId in which the uri is to be resolved.
   7649      * @param targetUserId The userId of the app that receives the grant.
   7650      */
   7651     @Override
   7652     public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri,
   7653             final int modeFlags, int sourceUserId, int targetUserId) {
   7654         targetUserId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   7655                 targetUserId, false, ALLOW_FULL_ONLY, "grantUriPermissionFromOwner", null);
   7656         synchronized(this) {
   7657             UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
   7658             if (owner == null) {
   7659                 throw new IllegalArgumentException("Unknown owner: " + token);
   7660             }
   7661             if (fromUid != Binder.getCallingUid()) {
   7662                 if (Binder.getCallingUid() != Process.myUid()) {
   7663                     // Only system code can grant URI permissions on behalf
   7664                     // of other users.
   7665                     throw new SecurityException("nice try");
   7666                 }
   7667             }
   7668             if (targetPkg == null) {
   7669                 throw new IllegalArgumentException("null target");
   7670             }
   7671             if (uri == null) {
   7672                 throw new IllegalArgumentException("null uri");
   7673             }
   7674 
   7675             grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false),
   7676                     modeFlags, owner, targetUserId);
   7677         }
   7678     }
   7679 
   7680     /**
   7681      * @param uri This uri must NOT contain an embedded userId.
   7682      * @param userId The userId in which the uri is to be resolved.
   7683      */
   7684     @Override
   7685     public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) {
   7686         synchronized(this) {
   7687             UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
   7688             if (owner == null) {
   7689                 throw new IllegalArgumentException("Unknown owner: " + token);
   7690             }
   7691 
   7692             if (uri == null) {
   7693                 owner.removeUriPermissionsLocked(mode);
   7694             } else {
   7695                 owner.removeUriPermissionLocked(new GrantUri(userId, uri, false), mode);
   7696             }
   7697         }
   7698     }
   7699 
   7700     private void schedulePersistUriGrants() {
   7701         if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) {
   7702             mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG),
   7703                     10 * DateUtils.SECOND_IN_MILLIS);
   7704         }
   7705     }
   7706 
   7707     private void writeGrantedUriPermissions() {
   7708         if (DEBUG_URI_PERMISSION) Slog.v(TAG, "writeGrantedUriPermissions()");
   7709 
   7710         // Snapshot permissions so we can persist without lock
   7711         ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList();
   7712         synchronized (this) {
   7713             final int size = mGrantedUriPermissions.size();
   7714             for (int i = 0; i < size; i++) {
   7715                 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
   7716                 for (UriPermission perm : perms.values()) {
   7717                     if (perm.persistedModeFlags != 0) {
   7718                         persist.add(perm.snapshot());
   7719                     }
   7720                 }
   7721             }
   7722         }
   7723 
   7724         FileOutputStream fos = null;
   7725         try {
   7726             fos = mGrantFile.startWrite();
   7727 
   7728             XmlSerializer out = new FastXmlSerializer();
   7729             out.setOutput(fos, "utf-8");
   7730             out.startDocument(null, true);
   7731             out.startTag(null, TAG_URI_GRANTS);
   7732             for (UriPermission.Snapshot perm : persist) {
   7733                 out.startTag(null, TAG_URI_GRANT);
   7734                 writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId);
   7735                 writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId);
   7736                 out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg);
   7737                 out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg);
   7738                 out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri));
   7739                 writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix);
   7740                 writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags);
   7741                 writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime);
   7742                 out.endTag(null, TAG_URI_GRANT);
   7743             }
   7744             out.endTag(null, TAG_URI_GRANTS);
   7745             out.endDocument();
   7746 
   7747             mGrantFile.finishWrite(fos);
   7748         } catch (IOException e) {
   7749             if (fos != null) {
   7750                 mGrantFile.failWrite(fos);
   7751             }
   7752         }
   7753     }
   7754 
   7755     private void readGrantedUriPermissionsLocked() {
   7756         if (DEBUG_URI_PERMISSION) Slog.v(TAG, "readGrantedUriPermissions()");
   7757 
   7758         final long now = System.currentTimeMillis();
   7759 
   7760         FileInputStream fis = null;
   7761         try {
   7762             fis = mGrantFile.openRead();
   7763             final XmlPullParser in = Xml.newPullParser();
   7764             in.setInput(fis, null);
   7765 
   7766             int type;
   7767             while ((type = in.next()) != END_DOCUMENT) {
   7768                 final String tag = in.getName();
   7769                 if (type == START_TAG) {
   7770                     if (TAG_URI_GRANT.equals(tag)) {
   7771                         final int sourceUserId;
   7772                         final int targetUserId;
   7773                         final int userHandle = readIntAttribute(in,
   7774                                 ATTR_USER_HANDLE, UserHandle.USER_NULL);
   7775                         if (userHandle != UserHandle.USER_NULL) {
   7776                             // For backwards compatibility.
   7777                             sourceUserId = userHandle;
   7778                             targetUserId = userHandle;
   7779                         } else {
   7780                             sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID);
   7781                             targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID);
   7782                         }
   7783                         final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG);
   7784                         final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG);
   7785                         final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI));
   7786                         final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX);
   7787                         final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS);
   7788                         final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now);
   7789 
   7790                         // Sanity check that provider still belongs to source package
   7791                         final ProviderInfo pi = getProviderInfoLocked(
   7792                                 uri.getAuthority(), sourceUserId);
   7793                         if (pi != null && sourcePkg.equals(pi.packageName)) {
   7794                             int targetUid = -1;
   7795                             try {
   7796                                 targetUid = AppGlobals.getPackageManager()
   7797                                         .getPackageUid(targetPkg, targetUserId);
   7798                             } catch (RemoteException e) {
   7799                             }
   7800                             if (targetUid != -1) {
   7801                                 final UriPermission perm = findOrCreateUriPermissionLocked(
   7802                                         sourcePkg, targetPkg, targetUid,
   7803                                         new GrantUri(sourceUserId, uri, prefix));
   7804                                 perm.initPersistedModes(modeFlags, createdTime);
   7805                             }
   7806                         } else {
   7807                             Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg
   7808                                     + " but instead found " + pi);
   7809                         }
   7810                     }
   7811                 }
   7812             }
   7813         } catch (FileNotFoundException e) {
   7814             // Missing grants is okay
   7815         } catch (IOException e) {
   7816             Slog.wtf(TAG, "Failed reading Uri grants", e);
   7817         } catch (XmlPullParserException e) {
   7818             Slog.wtf(TAG, "Failed reading Uri grants", e);
   7819         } finally {
   7820             IoUtils.closeQuietly(fis);
   7821         }
   7822     }
   7823 
   7824     /**
   7825      * @param uri This uri must NOT contain an embedded userId.
   7826      * @param userId The userId in which the uri is to be resolved.
   7827      */
   7828     @Override
   7829     public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
   7830         enforceNotIsolatedCaller("takePersistableUriPermission");
   7831 
   7832         Preconditions.checkFlagsArgument(modeFlags,
   7833                 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
   7834 
   7835         synchronized (this) {
   7836             final int callingUid = Binder.getCallingUid();
   7837             boolean persistChanged = false;
   7838             GrantUri grantUri = new GrantUri(userId, uri, false);
   7839 
   7840             UriPermission exactPerm = findUriPermissionLocked(callingUid,
   7841                     new GrantUri(userId, uri, false));
   7842             UriPermission prefixPerm = findUriPermissionLocked(callingUid,
   7843                     new GrantUri(userId, uri, true));
   7844 
   7845             final boolean exactValid = (exactPerm != null)
   7846                     && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags);
   7847             final boolean prefixValid = (prefixPerm != null)
   7848                     && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags);
   7849 
   7850             if (!(exactValid || prefixValid)) {
   7851                 throw new SecurityException("No persistable permission grants found for UID "
   7852                         + callingUid + " and Uri " + grantUri.toSafeString());
   7853             }
   7854 
   7855             if (exactValid) {
   7856                 persistChanged |= exactPerm.takePersistableModes(modeFlags);
   7857             }
   7858             if (prefixValid) {
   7859                 persistChanged |= prefixPerm.takePersistableModes(modeFlags);
   7860             }
   7861 
   7862             persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid);
   7863 
   7864             if (persistChanged) {
   7865                 schedulePersistUriGrants();
   7866             }
   7867         }
   7868     }
   7869 
   7870     /**
   7871      * @param uri This uri must NOT contain an embedded userId.
   7872      * @param userId The userId in which the uri is to be resolved.
   7873      */
   7874     @Override
   7875     public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
   7876         enforceNotIsolatedCaller("releasePersistableUriPermission");
   7877 
   7878         Preconditions.checkFlagsArgument(modeFlags,
   7879                 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
   7880 
   7881         synchronized (this) {
   7882             final int callingUid = Binder.getCallingUid();
   7883             boolean persistChanged = false;
   7884 
   7885             UriPermission exactPerm = findUriPermissionLocked(callingUid,
   7886                     new GrantUri(userId, uri, false));
   7887             UriPermission prefixPerm = findUriPermissionLocked(callingUid,
   7888                     new GrantUri(userId, uri, true));
   7889             if (exactPerm == null && prefixPerm == null) {
   7890                 throw new SecurityException("No permission grants found for UID " + callingUid
   7891                         + " and Uri " + uri.toSafeString());
   7892             }
   7893 
   7894             if (exactPerm != null) {
   7895                 persistChanged |= exactPerm.releasePersistableModes(modeFlags);
   7896                 removeUriPermissionIfNeededLocked(exactPerm);
   7897             }
   7898             if (prefixPerm != null) {
   7899                 persistChanged |= prefixPerm.releasePersistableModes(modeFlags);
   7900                 removeUriPermissionIfNeededLocked(prefixPerm);
   7901             }
   7902 
   7903             if (persistChanged) {
   7904                 schedulePersistUriGrants();
   7905             }
   7906         }
   7907     }
   7908 
   7909     /**
   7910      * Prune any older {@link UriPermission} for the given UID until outstanding
   7911      * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}.
   7912      *
   7913      * @return if any mutations occured that require persisting.
   7914      */
   7915     private boolean maybePrunePersistedUriGrantsLocked(int uid) {
   7916         final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
   7917         if (perms == null) return false;
   7918         if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false;
   7919 
   7920         final ArrayList<UriPermission> persisted = Lists.newArrayList();
   7921         for (UriPermission perm : perms.values()) {
   7922             if (perm.persistedModeFlags != 0) {
   7923                 persisted.add(perm);
   7924             }
   7925         }
   7926 
   7927         final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS;
   7928         if (trimCount <= 0) return false;
   7929 
   7930         Collections.sort(persisted, new UriPermission.PersistedTimeComparator());
   7931         for (int i = 0; i < trimCount; i++) {
   7932             final UriPermission perm = persisted.get(i);
   7933 
   7934             if (DEBUG_URI_PERMISSION) {
   7935                 Slog.v(TAG, "Trimming grant created at " + perm.persistedCreateTime);
   7936             }
   7937 
   7938             perm.releasePersistableModes(~0);
   7939             removeUriPermissionIfNeededLocked(perm);
   7940         }
   7941 
   7942         return true;
   7943     }
   7944 
   7945     @Override
   7946     public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions(
   7947             String packageName, boolean incoming) {
   7948         enforceNotIsolatedCaller("getPersistedUriPermissions");
   7949         Preconditions.checkNotNull(packageName, "packageName");
   7950 
   7951         final int callingUid = Binder.getCallingUid();
   7952         final IPackageManager pm = AppGlobals.getPackageManager();
   7953         try {
   7954             final int packageUid = pm.getPackageUid(packageName, UserHandle.getUserId(callingUid));
   7955             if (packageUid != callingUid) {
   7956                 throw new SecurityException(
   7957                         "Package " + packageName + " does not belong to calling UID " + callingUid);
   7958             }
   7959         } catch (RemoteException e) {
   7960             throw new SecurityException("Failed to verify package name ownership");
   7961         }
   7962 
   7963         final ArrayList<android.content.UriPermission> result = Lists.newArrayList();
   7964         synchronized (this) {
   7965             if (incoming) {
   7966                 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
   7967                         callingUid);
   7968                 if (perms == null) {
   7969                     Slog.w(TAG, "No permission grants found for " + packageName);
   7970                 } else {
   7971                     for (UriPermission perm : perms.values()) {
   7972                         if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) {
   7973                             result.add(perm.buildPersistedPublicApiObject());
   7974                         }
   7975                     }
   7976                 }
   7977             } else {
   7978                 final int size = mGrantedUriPermissions.size();
   7979                 for (int i = 0; i < size; i++) {
   7980                     final ArrayMap<GrantUri, UriPermission> perms =
   7981                             mGrantedUriPermissions.valueAt(i);
   7982                     for (UriPermission perm : perms.values()) {
   7983                         if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) {
   7984                             result.add(perm.buildPersistedPublicApiObject());
   7985                         }
   7986                     }
   7987                 }
   7988             }
   7989         }
   7990         return new ParceledListSlice<android.content.UriPermission>(result);
   7991     }
   7992 
   7993     @Override
   7994     public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
   7995         synchronized (this) {
   7996             ProcessRecord app =
   7997                 who != null ? getRecordForAppLocked(who) : null;
   7998             if (app == null) return;
   7999 
   8000             Message msg = Message.obtain();
   8001             msg.what = WAIT_FOR_DEBUGGER_MSG;
   8002             msg.obj = app;
   8003             msg.arg1 = waiting ? 1 : 0;
   8004             mHandler.sendMessage(msg);
   8005         }
   8006     }
   8007 
   8008     @Override
   8009     public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
   8010         final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
   8011         final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ);
   8012         outInfo.availMem = Process.getFreeMemory();
   8013         outInfo.totalMem = Process.getTotalMemory();
   8014         outInfo.threshold = homeAppMem;
   8015         outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2));
   8016         outInfo.hiddenAppThreshold = cachedAppMem;
   8017         outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
   8018                 ProcessList.SERVICE_ADJ);
   8019         outInfo.visibleAppThreshold = mProcessList.getMemLevel(
   8020                 ProcessList.VISIBLE_APP_ADJ);
   8021         outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
   8022                 ProcessList.FOREGROUND_APP_ADJ);
   8023     }
   8024 
   8025     // =========================================================
   8026     // TASK MANAGEMENT
   8027     // =========================================================
   8028 
   8029     @Override
   8030     public List<IAppTask> getAppTasks(String callingPackage) {
   8031         int callingUid = Binder.getCallingUid();
   8032         long ident = Binder.clearCallingIdentity();
   8033 
   8034         synchronized(this) {
   8035             ArrayList<IAppTask> list = new ArrayList<IAppTask>();
   8036             try {
   8037                 if (localLOGV) Slog.v(TAG, "getAppTasks");
   8038 
   8039                 final int N = mRecentTasks.size();
   8040                 for (int i = 0; i < N; i++) {
   8041                     TaskRecord tr = mRecentTasks.get(i);
   8042                     // Skip tasks that do not match the caller.  We don't need to verify
   8043                     // callingPackage, because we are also limiting to callingUid and know
   8044                     // that will limit to the correct security sandbox.
   8045                     if (tr.effectiveUid != callingUid) {
   8046                         continue;
   8047                     }
   8048                     Intent intent = tr.getBaseIntent();
   8049                     if (intent == null ||
   8050                             !callingPackage.equals(intent.getComponent().getPackageName())) {
   8051                         continue;
   8052                     }
   8053                     ActivityManager.RecentTaskInfo taskInfo =
   8054                             createRecentTaskInfoFromTaskRecord(tr);
   8055                     AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid);
   8056                     list.add(taskImpl);
   8057                 }
   8058             } finally {
   8059                 Binder.restoreCallingIdentity(ident);
   8060             }
   8061             return list;
   8062         }
   8063     }
   8064 
   8065     @Override
   8066     public List<RunningTaskInfo> getTasks(int maxNum, int flags) {
   8067         final int callingUid = Binder.getCallingUid();
   8068         ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>();
   8069 
   8070         synchronized(this) {
   8071             if (localLOGV) Slog.v(
   8072                 TAG, "getTasks: max=" + maxNum + ", flags=" + flags);
   8073 
   8074             final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
   8075                     callingUid);
   8076 
   8077             // TODO: Improve with MRU list from all ActivityStacks.
   8078             mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed);
   8079         }
   8080 
   8081         return list;
   8082     }
   8083 
   8084     /**
   8085      * Creates a new RecentTaskInfo from a TaskRecord.
   8086      */
   8087     private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) {
   8088         // Update the task description to reflect any changes in the task stack
   8089         tr.updateTaskDescription();
   8090 
   8091         // Compose the recent task info
   8092         ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
   8093         rti.id = tr.getTopActivity() == null ? INVALID_TASK_ID : tr.taskId;
   8094         rti.persistentId = tr.taskId;
   8095         rti.baseIntent = new Intent(tr.getBaseIntent());
   8096         rti.origActivity = tr.origActivity;
   8097         rti.description = tr.lastDescription;
   8098         rti.stackId = tr.stack != null ? tr.stack.mStackId : -1;
   8099         rti.userId = tr.userId;
   8100         rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription);
   8101         rti.firstActiveTime = tr.firstActiveTime;
   8102         rti.lastActiveTime = tr.lastActiveTime;
   8103         rti.affiliatedTaskId = tr.mAffiliatedTaskId;
   8104         rti.affiliatedTaskColor = tr.mAffiliatedTaskColor;
   8105         return rti;
   8106     }
   8107 
   8108     private boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
   8109         boolean allowed = checkPermission(android.Manifest.permission.REAL_GET_TASKS,
   8110                 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
   8111         if (!allowed) {
   8112             if (checkPermission(android.Manifest.permission.GET_TASKS,
   8113                     callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
   8114                 // Temporary compatibility: some existing apps on the system image may
   8115                 // still be requesting the old permission and not switched to the new
   8116                 // one; if so, we'll still allow them full access.  This means we need
   8117                 // to see if they are holding the old permission and are a system app.
   8118                 try {
   8119                     if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
   8120                         allowed = true;
   8121                         Slog.w(TAG, caller + ": caller " + callingUid
   8122                                 + " is using old GET_TASKS but privileged; allowing");
   8123                     }
   8124                 } catch (RemoteException e) {
   8125                 }
   8126             }
   8127         }
   8128         if (!allowed) {
   8129             Slog.w(TAG, caller + ": caller " + callingUid
   8130                     + " does not hold REAL_GET_TASKS; limiting output");
   8131         }
   8132         return allowed;
   8133     }
   8134 
   8135     @Override
   8136     public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) {
   8137         final int callingUid = Binder.getCallingUid();
   8138         userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
   8139                 false, ALLOW_FULL_ONLY, "getRecentTasks", null);
   8140 
   8141         final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0;
   8142         final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0;
   8143         synchronized (this) {
   8144             final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
   8145                     callingUid);
   8146             final boolean detailed = checkCallingPermission(
   8147                     android.Manifest.permission.GET_DETAILED_TASKS)
   8148                     == PackageManager.PERMISSION_GRANTED;
   8149 
   8150             final int N = mRecentTasks.size();
   8151             ArrayList<ActivityManager.RecentTaskInfo> res
   8152                     = new ArrayList<ActivityManager.RecentTaskInfo>(
   8153                             maxNum < N ? maxNum : N);
   8154 
   8155             final Set<Integer> includedUsers;
   8156             if (includeProfiles) {
   8157                 includedUsers = getProfileIdsLocked(userId);
   8158             } else {
   8159                 includedUsers = new HashSet<Integer>();
   8160             }
   8161             includedUsers.add(Integer.valueOf(userId));
   8162 
   8163             for (int i=0; i<N && maxNum > 0; i++) {
   8164                 TaskRecord tr = mRecentTasks.get(i);
   8165                 // Only add calling user or related users recent tasks
   8166                 if (!includedUsers.contains(Integer.valueOf(tr.userId))) {
   8167                     if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, not user: " + tr);
   8168                     continue;
   8169                 }
   8170 
   8171                 // Return the entry if desired by the caller.  We always return
   8172                 // the first entry, because callers always expect this to be the
   8173                 // foreground app.  We may filter others if the caller has
   8174                 // not supplied RECENT_WITH_EXCLUDED and there is some reason
   8175                 // we should exclude the entry.
   8176 
   8177                 if (i == 0
   8178                         || withExcluded
   8179                         || (tr.intent == null)
   8180                         || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
   8181                                 == 0)) {
   8182                     if (!allowed) {
   8183                         // If the caller doesn't have the GET_TASKS permission, then only
   8184                         // allow them to see a small subset of tasks -- their own and home.
   8185                         if (!tr.isHomeTask() && tr.effectiveUid != callingUid) {
   8186                             if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, not allowed: " + tr);
   8187                             continue;
   8188                         }
   8189                     }
   8190                     if ((flags & ActivityManager.RECENT_IGNORE_HOME_STACK_TASKS) != 0) {
   8191                         if (tr.stack != null && tr.stack.isHomeStack()) {
   8192                             if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, home stack task: " + tr);
   8193                             continue;
   8194                         }
   8195                     }
   8196                     if (tr.autoRemoveRecents && tr.getTopActivity() == null) {
   8197                         // Don't include auto remove tasks that are finished or finishing.
   8198                         if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, auto-remove without activity: "
   8199                                 + tr);
   8200                         continue;
   8201                     }
   8202                     if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0
   8203                             && !tr.isAvailable) {
   8204                         if (DEBUG_RECENTS) Slog.d(TAG, "Skipping, unavail real act: " + tr);
   8205                         continue;
   8206                     }
   8207 
   8208                     ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr);
   8209                     if (!detailed) {
   8210                         rti.baseIntent.replaceExtras((Bundle)null);
   8211                     }
   8212 
   8213                     res.add(rti);
   8214                     maxNum--;
   8215                 }
   8216             }
   8217             return res;
   8218         }
   8219     }
   8220 
   8221     TaskRecord recentTaskForIdLocked(int id) {
   8222         final int N = mRecentTasks.size();
   8223             for (int i=0; i<N; i++) {
   8224                 TaskRecord tr = mRecentTasks.get(i);
   8225                 if (tr.taskId == id) {
   8226                     return tr;
   8227                 }
   8228             }
   8229             return null;
   8230     }
   8231 
   8232     @Override
   8233     public ActivityManager.TaskThumbnail getTaskThumbnail(int id) {
   8234         synchronized (this) {
   8235             enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
   8236                     "getTaskThumbnail()");
   8237             TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id);
   8238             if (tr != null) {
   8239                 return tr.getTaskThumbnailLocked();
   8240             }
   8241         }
   8242         return null;
   8243     }
   8244 
   8245     @Override
   8246     public int addAppTask(IBinder activityToken, Intent intent,
   8247             ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
   8248         final int callingUid = Binder.getCallingUid();
   8249         final long callingIdent = Binder.clearCallingIdentity();
   8250 
   8251         try {
   8252             synchronized (this) {
   8253                 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
   8254                 if (r == null) {
   8255                     throw new IllegalArgumentException("Activity does not exist; token="
   8256                             + activityToken);
   8257                 }
   8258                 ComponentName comp = intent.getComponent();
   8259                 if (comp == null) {
   8260                     throw new IllegalArgumentException("Intent " + intent
   8261                             + " must specify explicit component");
   8262                 }
   8263                 if (thumbnail.getWidth() != mThumbnailWidth
   8264                         || thumbnail.getHeight() != mThumbnailHeight) {
   8265                     throw new IllegalArgumentException("Bad thumbnail size: got "
   8266                             + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
   8267                             + mThumbnailWidth + "x" + mThumbnailHeight);
   8268                 }
   8269                 if (intent.getSelector() != null) {
   8270                     intent.setSelector(null);
   8271                 }
   8272                 if (intent.getSourceBounds() != null) {
   8273                     intent.setSourceBounds(null);
   8274                 }
   8275                 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
   8276                     if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
   8277                         // The caller has added this as an auto-remove task...  that makes no
   8278                         // sense, so turn off auto-remove.
   8279                         intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
   8280                     }
   8281                 } else if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
   8282                     // Must be a new task.
   8283                     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   8284                 }
   8285                 if (!comp.equals(mLastAddedTaskComponent) || callingUid != mLastAddedTaskUid) {
   8286                     mLastAddedTaskActivity = null;
   8287                 }
   8288                 ActivityInfo ainfo = mLastAddedTaskActivity;
   8289                 if (ainfo == null) {
   8290                     ainfo = mLastAddedTaskActivity = AppGlobals.getPackageManager().getActivityInfo(
   8291                             comp, 0, UserHandle.getUserId(callingUid));
   8292                     if (ainfo.applicationInfo.uid != callingUid) {
   8293                         throw new SecurityException(
   8294                                 "Can't add task for another application: target uid="
   8295                                 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
   8296                     }
   8297                 }
   8298 
   8299                 TaskRecord task = new TaskRecord(this, mStackSupervisor.getNextTaskId(), ainfo,
   8300                         intent, description);
   8301 
   8302                 int trimIdx = trimRecentsForTaskLocked(task, false);
   8303                 if (trimIdx >= 0) {
   8304                     // If this would have caused a trim, then we'll abort because that
   8305                     // means it would be added at the end of the list but then just removed.
   8306                     return INVALID_TASK_ID;
   8307                 }
   8308 
   8309                 final int N = mRecentTasks.size();
   8310                 if (N >= (ActivityManager.getMaxRecentTasksStatic()-1)) {
   8311                     final TaskRecord tr = mRecentTasks.remove(N - 1);
   8312                     tr.removedFromRecents();
   8313                 }
   8314 
   8315                 task.inRecents = true;
   8316                 mRecentTasks.add(task);
   8317                 r.task.stack.addTask(task, false, false);
   8318 
   8319                 task.setLastThumbnail(thumbnail);
   8320                 task.freeLastThumbnail();
   8321 
   8322                 return task.taskId;
   8323             }
   8324         } finally {
   8325             Binder.restoreCallingIdentity(callingIdent);
   8326         }
   8327     }
   8328 
   8329     @Override
   8330     public Point getAppTaskThumbnailSize() {
   8331         synchronized (this) {
   8332             return new Point(mThumbnailWidth,  mThumbnailHeight);
   8333         }
   8334     }
   8335 
   8336     @Override
   8337     public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
   8338         synchronized (this) {
   8339             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   8340             if (r != null) {
   8341                 r.setTaskDescription(td);
   8342                 r.task.updateTaskDescription();
   8343             }
   8344         }
   8345     }
   8346 
   8347     @Override
   8348     public Bitmap getTaskDescriptionIcon(String filename) {
   8349         if (!FileUtils.isValidExtFilename(filename)
   8350                 || !filename.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
   8351             throw new IllegalArgumentException("Bad filename: " + filename);
   8352         }
   8353         return mTaskPersister.getTaskDescriptionIcon(filename);
   8354     }
   8355 
   8356     @Override
   8357     public void startInPlaceAnimationOnFrontMostApplication(ActivityOptions opts)
   8358             throws RemoteException {
   8359         if (opts.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE ||
   8360