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 com.android.internal.R;
     20 import com.android.internal.os.BatteryStatsImpl;
     21 import com.android.internal.os.ProcessStats;
     22 import com.android.server.AttributeCache;
     23 import com.android.server.IntentResolver;
     24 import com.android.server.ProcessMap;
     25 import com.android.server.SystemServer;
     26 import com.android.server.Watchdog;
     27 import com.android.server.am.ActivityStack.ActivityState;
     28 import com.android.server.wm.WindowManagerService;
     29 
     30 import dalvik.system.Zygote;
     31 
     32 import android.app.Activity;
     33 import android.app.ActivityManager;
     34 import android.app.ActivityManagerNative;
     35 import android.app.ActivityThread;
     36 import android.app.AlertDialog;
     37 import android.app.AppGlobals;
     38 import android.app.ApplicationErrorReport;
     39 import android.app.Dialog;
     40 import android.app.IActivityController;
     41 import android.app.IActivityWatcher;
     42 import android.app.IApplicationThread;
     43 import android.app.IInstrumentationWatcher;
     44 import android.app.INotificationManager;
     45 import android.app.IProcessObserver;
     46 import android.app.IServiceConnection;
     47 import android.app.IThumbnailReceiver;
     48 import android.app.Instrumentation;
     49 import android.app.Notification;
     50 import android.app.NotificationManager;
     51 import android.app.PendingIntent;
     52 import android.app.Service;
     53 import android.app.backup.IBackupManager;
     54 import android.content.ActivityNotFoundException;
     55 import android.content.BroadcastReceiver;
     56 import android.content.ComponentCallbacks2;
     57 import android.content.ComponentName;
     58 import android.content.ContentResolver;
     59 import android.content.Context;
     60 import android.content.DialogInterface;
     61 import android.content.Intent;
     62 import android.content.IntentFilter;
     63 import android.content.IIntentReceiver;
     64 import android.content.IIntentSender;
     65 import android.content.IntentSender;
     66 import android.content.pm.ActivityInfo;
     67 import android.content.pm.ApplicationInfo;
     68 import android.content.pm.ConfigurationInfo;
     69 import android.content.pm.IPackageDataObserver;
     70 import android.content.pm.IPackageManager;
     71 import android.content.pm.InstrumentationInfo;
     72 import android.content.pm.PackageInfo;
     73 import android.content.pm.PackageManager;
     74 import android.content.pm.PathPermission;
     75 import android.content.pm.ProviderInfo;
     76 import android.content.pm.ResolveInfo;
     77 import android.content.pm.ServiceInfo;
     78 import android.content.pm.PackageManager.NameNotFoundException;
     79 import android.content.res.CompatibilityInfo;
     80 import android.content.res.Configuration;
     81 import android.graphics.Bitmap;
     82 import android.net.Proxy;
     83 import android.net.ProxyProperties;
     84 import android.net.Uri;
     85 import android.os.Binder;
     86 import android.os.Build;
     87 import android.os.Bundle;
     88 import android.os.Debug;
     89 import android.os.DropBoxManager;
     90 import android.os.Environment;
     91 import android.os.FileObserver;
     92 import android.os.FileUtils;
     93 import android.os.Handler;
     94 import android.os.IBinder;
     95 import android.os.IPermissionController;
     96 import android.os.Looper;
     97 import android.os.Message;
     98 import android.os.Parcel;
     99 import android.os.ParcelFileDescriptor;
    100 import android.os.Process;
    101 import android.os.RemoteCallbackList;
    102 import android.os.RemoteException;
    103 import android.os.ServiceManager;
    104 import android.os.StrictMode;
    105 import android.os.SystemClock;
    106 import android.os.SystemProperties;
    107 import android.provider.Settings;
    108 import android.text.format.Time;
    109 import android.util.EventLog;
    110 import android.util.Pair;
    111 import android.util.Slog;
    112 import android.util.Log;
    113 import android.util.PrintWriterPrinter;
    114 import android.util.SparseArray;
    115 import android.util.TimeUtils;
    116 import android.view.Gravity;
    117 import android.view.LayoutInflater;
    118 import android.view.View;
    119 import android.view.WindowManager;
    120 import android.view.WindowManagerPolicy;
    121 
    122 import java.io.BufferedInputStream;
    123 import java.io.BufferedOutputStream;
    124 import java.io.BufferedReader;
    125 import java.io.DataInputStream;
    126 import java.io.DataOutputStream;
    127 import java.io.File;
    128 import java.io.FileDescriptor;
    129 import java.io.FileInputStream;
    130 import java.io.FileNotFoundException;
    131 import java.io.FileOutputStream;
    132 import java.io.IOException;
    133 import java.io.InputStreamReader;
    134 import java.io.PrintWriter;
    135 import java.io.StringWriter;
    136 import java.lang.IllegalStateException;
    137 import java.lang.ref.WeakReference;
    138 import java.util.ArrayList;
    139 import java.util.Collections;
    140 import java.util.Comparator;
    141 import java.util.HashMap;
    142 import java.util.HashSet;
    143 import java.util.Iterator;
    144 import java.util.List;
    145 import java.util.Locale;
    146 import java.util.Map;
    147 import java.util.Set;
    148 import java.util.concurrent.atomic.AtomicBoolean;
    149 import java.util.concurrent.atomic.AtomicLong;
    150 
    151 public final class ActivityManagerService extends ActivityManagerNative
    152         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    153     static final String TAG = "ActivityManager";
    154     static final boolean DEBUG = false;
    155     static final boolean localLOGV = DEBUG;
    156     static final boolean DEBUG_SWITCH = localLOGV || false;
    157     static final boolean DEBUG_TASKS = localLOGV || false;
    158     static final boolean DEBUG_PAUSE = localLOGV || false;
    159     static final boolean DEBUG_OOM_ADJ = localLOGV || false;
    160     static final boolean DEBUG_TRANSITION = localLOGV || false;
    161     static final boolean DEBUG_BROADCAST = localLOGV || false;
    162     static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
    163     static final boolean DEBUG_SERVICE = localLOGV || false;
    164     static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
    165     static final boolean DEBUG_VISBILITY = localLOGV || false;
    166     static final boolean DEBUG_PROCESSES = localLOGV || false;
    167     static final boolean DEBUG_PROVIDER = localLOGV || false;
    168     static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
    169     static final boolean DEBUG_USER_LEAVING = localLOGV || false;
    170     static final boolean DEBUG_RESULTS = localLOGV || false;
    171     static final boolean DEBUG_BACKUP = localLOGV || false;
    172     static final boolean DEBUG_CONFIGURATION = localLOGV || false;
    173     static final boolean DEBUG_POWER = localLOGV || false;
    174     static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
    175     static final boolean VALIDATE_TOKENS = false;
    176     static final boolean SHOW_ACTIVITY_START_TIME = true;
    177 
    178     // Control over CPU and battery monitoring.
    179     static final long BATTERY_STATS_TIME = 30*60*1000;      // write battery stats every 30 minutes.
    180     static final boolean MONITOR_CPU_USAGE = true;
    181     static final long MONITOR_CPU_MIN_TIME = 5*1000;        // don't sample cpu less than every 5 seconds.
    182     static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;    // wait possibly forever for next cpu sample.
    183     static final boolean MONITOR_THREAD_CPU_USAGE = false;
    184 
    185     // The flags that are set for all calls we make to the package manager.
    186     static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
    187 
    188     private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
    189 
    190     static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
    191 
    192     // Maximum number of recent tasks that we can remember.
    193     static final int MAX_RECENT_TASKS = 20;
    194 
    195     // Amount of time after a call to stopAppSwitches() during which we will
    196     // prevent further untrusted switches from happening.
    197     static final long APP_SWITCH_DELAY_TIME = 5*1000;
    198 
    199     // How long we wait for a launched process to attach to the activity manager
    200     // before we decide it's never going to come up for real.
    201     static final int PROC_START_TIMEOUT = 10*1000;
    202 
    203     // How long we wait for a launched process to attach to the activity manager
    204     // before we decide it's never going to come up for real, when the process was
    205     // started with a wrapper for instrumentation (such as Valgrind) because it
    206     // could take much longer than usual.
    207     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
    208 
    209     // How long to wait after going idle before forcing apps to GC.
    210     static final int GC_TIMEOUT = 5*1000;
    211 
    212     // The minimum amount of time between successive GC requests for a process.
    213     static final int GC_MIN_INTERVAL = 60*1000;
    214 
    215     // The rate at which we check for apps using excessive power -- 15 mins.
    216     static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
    217 
    218     // The minimum sample duration we will allow before deciding we have
    219     // enough data on wake locks to start killing things.
    220     static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    221 
    222     // The minimum sample duration we will allow before deciding we have
    223     // enough data on CPU usage to start killing things.
    224     static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    225 
    226     // How long we allow a receiver to run before giving up on it.
    227     static final int BROADCAST_TIMEOUT = 10*1000;
    228 
    229     // How long we wait for a service to finish executing.
    230     static final int SERVICE_TIMEOUT = 20*1000;
    231 
    232     // How long a service needs to be running until restarting its process
    233     // is no longer considered to be a relaunch of the service.
    234     static final int SERVICE_RESTART_DURATION = 5*1000;
    235 
    236     // How long a service needs to be running until it will start back at
    237     // SERVICE_RESTART_DURATION after being killed.
    238     static final int SERVICE_RESET_RUN_DURATION = 60*1000;
    239 
    240     // Multiplying factor to increase restart duration time by, for each time
    241     // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
    242     static final int SERVICE_RESTART_DURATION_FACTOR = 4;
    243 
    244     // The minimum amount of time between restarting services that we allow.
    245     // That is, when multiple services are restarting, we won't allow each
    246     // to restart less than this amount of time from the last one.
    247     static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
    248 
    249     // Maximum amount of time for there to be no activity on a service before
    250     // we consider it non-essential and allow its process to go on the
    251     // LRU background list.
    252     static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
    253 
    254     // How long we wait until we timeout on key dispatching.
    255     static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
    256 
    257     // How long we wait until we timeout on key dispatching during instrumentation.
    258     static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
    259 
    260     static final int MY_PID = Process.myPid();
    261 
    262     static final String[] EMPTY_STRING_ARRAY = new String[0];
    263 
    264     public ActivityStack mMainStack;
    265 
    266     /**
    267      * Description of a request to start a new activity, which has been held
    268      * due to app switches being disabled.
    269      */
    270     static class PendingActivityLaunch {
    271         ActivityRecord r;
    272         ActivityRecord sourceRecord;
    273         Uri[] grantedUriPermissions;
    274         int grantedMode;
    275         boolean onlyIfNeeded;
    276     }
    277 
    278     final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
    279             = new ArrayList<PendingActivityLaunch>();
    280 
    281     /**
    282      * List of all active broadcasts that are to be executed immediately
    283      * (without waiting for another broadcast to finish).  Currently this only
    284      * contains broadcasts to registered receivers, to avoid spinning up
    285      * a bunch of processes to execute IntentReceiver components.
    286      */
    287     final ArrayList<BroadcastRecord> mParallelBroadcasts
    288             = new ArrayList<BroadcastRecord>();
    289 
    290     /**
    291      * List of all active broadcasts that are to be executed one at a time.
    292      * The object at the top of the list is the currently activity broadcasts;
    293      * those after it are waiting for the top to finish..
    294      */
    295     final ArrayList<BroadcastRecord> mOrderedBroadcasts
    296             = new ArrayList<BroadcastRecord>();
    297 
    298     /**
    299      * Historical data of past broadcasts, for debugging.
    300      */
    301     static final int MAX_BROADCAST_HISTORY = 25;
    302     final BroadcastRecord[] mBroadcastHistory
    303             = new BroadcastRecord[MAX_BROADCAST_HISTORY];
    304 
    305     /**
    306      * Set when we current have a BROADCAST_INTENT_MSG in flight.
    307      */
    308     boolean mBroadcastsScheduled = false;
    309 
    310     /**
    311      * Activity we have told the window manager to have key focus.
    312      */
    313     ActivityRecord mFocusedActivity = null;
    314     /**
    315      * List of intents that were used to start the most recent tasks.
    316      */
    317     final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
    318 
    319     /**
    320      * Process management.
    321      */
    322     final ProcessList mProcessList = new ProcessList();
    323 
    324     /**
    325      * All of the applications we currently have running organized by name.
    326      * The keys are strings of the application package name (as
    327      * returned by the package manager), and the keys are ApplicationRecord
    328      * objects.
    329      */
    330     final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
    331 
    332     /**
    333      * The currently running heavy-weight process, if any.
    334      */
    335     ProcessRecord mHeavyWeightProcess = null;
    336 
    337     /**
    338      * The last time that various processes have crashed.
    339      */
    340     final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
    341 
    342     /**
    343      * Set of applications that we consider to be bad, and will reject
    344      * incoming broadcasts from (which the user has no control over).
    345      * Processes are added to this set when they have crashed twice within
    346      * a minimum amount of time; they are removed from it when they are
    347      * later restarted (hopefully due to some user action).  The value is the
    348      * time it was added to the list.
    349      */
    350     final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
    351 
    352     /**
    353      * All of the processes we currently have running organized by pid.
    354      * The keys are the pid running the application.
    355      *
    356      * <p>NOTE: This object is protected by its own lock, NOT the global
    357      * activity manager lock!
    358      */
    359     final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
    360 
    361     /**
    362      * All of the processes that have been forced to be foreground.  The key
    363      * is the pid of the caller who requested it (we hold a death
    364      * link on it).
    365      */
    366     abstract class ForegroundToken implements IBinder.DeathRecipient {
    367         int pid;
    368         IBinder token;
    369     }
    370     final SparseArray<ForegroundToken> mForegroundProcesses
    371             = new SparseArray<ForegroundToken>();
    372 
    373     /**
    374      * List of records for processes that someone had tried to start before the
    375      * system was ready.  We don't start them at that point, but ensure they
    376      * are started by the time booting is complete.
    377      */
    378     final ArrayList<ProcessRecord> mProcessesOnHold
    379             = new ArrayList<ProcessRecord>();
    380 
    381     /**
    382      * List of persistent applications that are in the process
    383      * of being started.
    384      */
    385     final ArrayList<ProcessRecord> mPersistentStartingProcesses
    386             = new ArrayList<ProcessRecord>();
    387 
    388     /**
    389      * Processes that are being forcibly torn down.
    390      */
    391     final ArrayList<ProcessRecord> mRemovedProcesses
    392             = new ArrayList<ProcessRecord>();
    393 
    394     /**
    395      * List of running applications, sorted by recent usage.
    396      * The first entry in the list is the least recently used.
    397      * It contains ApplicationRecord objects.  This list does NOT include
    398      * any persistent application records (since we never want to exit them).
    399      */
    400     final ArrayList<ProcessRecord> mLruProcesses
    401             = new ArrayList<ProcessRecord>();
    402 
    403     /**
    404      * List of processes that should gc as soon as things are idle.
    405      */
    406     final ArrayList<ProcessRecord> mProcessesToGc
    407             = new ArrayList<ProcessRecord>();
    408 
    409     /**
    410      * This is the process holding what we currently consider to be
    411      * the "home" activity.
    412      */
    413     ProcessRecord mHomeProcess;
    414 
    415     /**
    416      * This is the process holding the activity the user last visited that
    417      * is in a different process from the one they are currently in.
    418      */
    419     ProcessRecord mPreviousProcess;
    420 
    421     /**
    422      * The time at which the previous process was last visible.
    423      */
    424     long mPreviousProcessVisibleTime;
    425 
    426     /**
    427      * Packages that the user has asked to have run in screen size
    428      * compatibility mode instead of filling the screen.
    429      */
    430     final CompatModePackages mCompatModePackages;
    431 
    432     /**
    433      * Set of PendingResultRecord objects that are currently active.
    434      */
    435     final HashSet mPendingResultRecords = new HashSet();
    436 
    437     /**
    438      * Set of IntentSenderRecord objects that are currently active.
    439      */
    440     final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
    441             = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
    442 
    443     /**
    444      * Fingerprints (hashCode()) of stack traces that we've
    445      * already logged DropBox entries for.  Guarded by itself.  If
    446      * something (rogue user app) forces this over
    447      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
    448      */
    449     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
    450     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
    451 
    452     /**
    453      * Strict Mode background batched logging state.
    454      *
    455      * The string buffer is guarded by itself, and its lock is also
    456      * used to determine if another batched write is already
    457      * in-flight.
    458      */
    459     private final StringBuilder mStrictModeBuffer = new StringBuilder();
    460 
    461     /**
    462      * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
    463      */
    464     private boolean mPendingBroadcastTimeoutMessage;
    465 
    466     /**
    467      * Intent broadcast that we have tried to start, but are
    468      * waiting for its application's process to be created.  We only
    469      * need one (instead of a list) because we always process broadcasts
    470      * one at a time, so no others can be started while waiting for this
    471      * one.
    472      */
    473     BroadcastRecord mPendingBroadcast = null;
    474 
    475     /**
    476      * The receiver index that is pending, to restart the broadcast if needed.
    477      */
    478     int mPendingBroadcastRecvIndex;
    479 
    480     /**
    481      * Keeps track of all IIntentReceivers that have been registered for
    482      * broadcasts.  Hash keys are the receiver IBinder, hash value is
    483      * a ReceiverList.
    484      */
    485     final HashMap mRegisteredReceivers = new HashMap();
    486 
    487     /**
    488      * Resolver for broadcast intents to registered receivers.
    489      * Holds BroadcastFilter (subclass of IntentFilter).
    490      */
    491     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
    492             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
    493         @Override
    494         protected boolean allowFilterResult(
    495                 BroadcastFilter filter, List<BroadcastFilter> dest) {
    496             IBinder target = filter.receiverList.receiver.asBinder();
    497             for (int i=dest.size()-1; i>=0; i--) {
    498                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
    499                     return false;
    500                 }
    501             }
    502             return true;
    503         }
    504 
    505         @Override
    506         protected String packageForFilter(BroadcastFilter filter) {
    507             return filter.packageName;
    508         }
    509     };
    510 
    511     /**
    512      * State of all active sticky broadcasts.  Keys are the action of the
    513      * sticky Intent, values are an ArrayList of all broadcasted intents with
    514      * that action (which should usually be one).
    515      */
    516     final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
    517             new HashMap<String, ArrayList<Intent>>();
    518 
    519     /**
    520      * All currently running services.
    521      */
    522     final HashMap<ComponentName, ServiceRecord> mServices =
    523         new HashMap<ComponentName, ServiceRecord>();
    524 
    525     /**
    526      * All currently running services indexed by the Intent used to start them.
    527      */
    528     final HashMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent =
    529         new HashMap<Intent.FilterComparison, ServiceRecord>();
    530 
    531     /**
    532      * All currently bound service connections.  Keys are the IBinder of
    533      * the client's IServiceConnection.
    534      */
    535     final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
    536             = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
    537 
    538     /**
    539      * List of services that we have been asked to start,
    540      * but haven't yet been able to.  It is used to hold start requests
    541      * while waiting for their corresponding application thread to get
    542      * going.
    543      */
    544     final ArrayList<ServiceRecord> mPendingServices
    545             = new ArrayList<ServiceRecord>();
    546 
    547     /**
    548      * List of services that are scheduled to restart following a crash.
    549      */
    550     final ArrayList<ServiceRecord> mRestartingServices
    551             = new ArrayList<ServiceRecord>();
    552 
    553     /**
    554      * List of services that are in the process of being stopped.
    555      */
    556     final ArrayList<ServiceRecord> mStoppingServices
    557             = new ArrayList<ServiceRecord>();
    558 
    559     /**
    560      * Backup/restore process management
    561      */
    562     String mBackupAppName = null;
    563     BackupRecord mBackupTarget = null;
    564 
    565     /**
    566      * List of PendingThumbnailsRecord objects of clients who are still
    567      * waiting to receive all of the thumbnails for a task.
    568      */
    569     final ArrayList mPendingThumbnails = new ArrayList();
    570 
    571     /**
    572      * List of HistoryRecord objects that have been finished and must
    573      * still report back to a pending thumbnail receiver.
    574      */
    575     final ArrayList mCancelledThumbnails = new ArrayList();
    576 
    577     /**
    578      * All of the currently running global content providers.  Keys are a
    579      * string containing the provider name and values are a
    580      * ContentProviderRecord object containing the data about it.  Note
    581      * that a single provider may be published under multiple names, so
    582      * there may be multiple entries here for a single one in mProvidersByClass.
    583      */
    584     final HashMap<String, ContentProviderRecord> mProvidersByName
    585             = new HashMap<String, ContentProviderRecord>();
    586 
    587     /**
    588      * All of the currently running global content providers.  Keys are a
    589      * string containing the provider's implementation class and values are a
    590      * ContentProviderRecord object containing the data about it.
    591      */
    592     final HashMap<ComponentName, ContentProviderRecord> mProvidersByClass
    593             = new HashMap<ComponentName, ContentProviderRecord>();
    594 
    595     /**
    596      * List of content providers who have clients waiting for them.  The
    597      * application is currently being launched and the provider will be
    598      * removed from this list once it is published.
    599      */
    600     final ArrayList<ContentProviderRecord> mLaunchingProviders
    601             = new ArrayList<ContentProviderRecord>();
    602 
    603     /**
    604      * Global set of specific Uri permissions that have been granted.
    605      */
    606     final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
    607             = new SparseArray<HashMap<Uri, UriPermission>>();
    608 
    609     CoreSettingsObserver mCoreSettingsObserver;
    610 
    611     /**
    612      * Thread-local storage used to carry caller permissions over through
    613      * indirect content-provider access.
    614      * @see #ActivityManagerService.openContentUri()
    615      */
    616     private class Identity {
    617         public int pid;
    618         public int uid;
    619 
    620         Identity(int _pid, int _uid) {
    621             pid = _pid;
    622             uid = _uid;
    623         }
    624     }
    625     private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
    626 
    627     /**
    628      * All information we have collected about the runtime performance of
    629      * any user id that can impact battery performance.
    630      */
    631     final BatteryStatsService mBatteryStatsService;
    632 
    633     /**
    634      * information about component usage
    635      */
    636     final UsageStatsService mUsageStatsService;
    637 
    638     /**
    639      * Current configuration information.  HistoryRecord objects are given
    640      * a reference to this object to indicate which configuration they are
    641      * currently running in, so this object must be kept immutable.
    642      */
    643     Configuration mConfiguration = new Configuration();
    644 
    645     /**
    646      * Current sequencing integer of the configuration, for skipping old
    647      * configurations.
    648      */
    649     int mConfigurationSeq = 0;
    650 
    651     /**
    652      * Hardware-reported OpenGLES version.
    653      */
    654     final int GL_ES_VERSION;
    655 
    656     /**
    657      * List of initialization arguments to pass to all processes when binding applications to them.
    658      * For example, references to the commonly used services.
    659      */
    660     HashMap<String, IBinder> mAppBindArgs;
    661 
    662     /**
    663      * Temporary to avoid allocations.  Protected by main lock.
    664      */
    665     final StringBuilder mStringBuilder = new StringBuilder(256);
    666 
    667     /**
    668      * Used to control how we initialize the service.
    669      */
    670     boolean mStartRunning = false;
    671     ComponentName mTopComponent;
    672     String mTopAction;
    673     String mTopData;
    674     boolean mProcessesReady = false;
    675     boolean mSystemReady = false;
    676     boolean mBooting = false;
    677     boolean mWaitingUpdate = false;
    678     boolean mDidUpdate = false;
    679     boolean mOnBattery = false;
    680     boolean mLaunchWarningShown = false;
    681 
    682     Context mContext;
    683 
    684     int mFactoryTest;
    685 
    686     boolean mCheckedForSetup;
    687 
    688     /**
    689      * The time at which we will allow normal application switches again,
    690      * after a call to {@link #stopAppSwitches()}.
    691      */
    692     long mAppSwitchesAllowedTime;
    693 
    694     /**
    695      * This is set to true after the first switch after mAppSwitchesAllowedTime
    696      * is set; any switches after that will clear the time.
    697      */
    698     boolean mDidAppSwitch;
    699 
    700     /**
    701      * Last time (in realtime) at which we checked for power usage.
    702      */
    703     long mLastPowerCheckRealtime;
    704 
    705     /**
    706      * Last time (in uptime) at which we checked for power usage.
    707      */
    708     long mLastPowerCheckUptime;
    709 
    710     /**
    711      * Set while we are wanting to sleep, to prevent any
    712      * activities from being started/resumed.
    713      */
    714     boolean mSleeping = false;
    715 
    716     /**
    717      * Set if we are shutting down the system, similar to sleeping.
    718      */
    719     boolean mShuttingDown = false;
    720 
    721     /**
    722      * Task identifier that activities are currently being started
    723      * in.  Incremented each time a new task is created.
    724      * todo: Replace this with a TokenSpace class that generates non-repeating
    725      * integers that won't wrap.
    726      */
    727     int mCurTask = 1;
    728 
    729     /**
    730      * Current sequence id for oom_adj computation traversal.
    731      */
    732     int mAdjSeq = 0;
    733 
    734     /**
    735      * Current sequence id for process LRU updating.
    736      */
    737     int mLruSeq = 0;
    738 
    739     /**
    740      * Keep track of the number of service processes we last found, to
    741      * determine on the next iteration which should be B services.
    742      */
    743     int mNumServiceProcs = 0;
    744     int mNewNumServiceProcs = 0;
    745 
    746     /**
    747      * System monitoring: number of processes that died since the last
    748      * N procs were started.
    749      */
    750     int[] mProcDeaths = new int[20];
    751 
    752     /**
    753      * This is set if we had to do a delayed dexopt of an app before launching
    754      * it, to increasing the ANR timeouts in that case.
    755      */
    756     boolean mDidDexOpt;
    757 
    758     String mDebugApp = null;
    759     boolean mWaitForDebugger = false;
    760     boolean mDebugTransient = false;
    761     String mOrigDebugApp = null;
    762     boolean mOrigWaitForDebugger = false;
    763     boolean mAlwaysFinishActivities = false;
    764     IActivityController mController = null;
    765     String mProfileApp = null;
    766     ProcessRecord mProfileProc = null;
    767     String mProfileFile;
    768     ParcelFileDescriptor mProfileFd;
    769     int mProfileType = 0;
    770     boolean mAutoStopProfiler = false;
    771 
    772     final RemoteCallbackList<IActivityWatcher> mWatchers
    773             = new RemoteCallbackList<IActivityWatcher>();
    774 
    775     final RemoteCallbackList<IProcessObserver> mProcessObservers
    776             = new RemoteCallbackList<IProcessObserver>();
    777 
    778     /**
    779      * Callback of last caller to {@link #requestPss}.
    780      */
    781     Runnable mRequestPssCallback;
    782 
    783     /**
    784      * Remaining processes for which we are waiting results from the last
    785      * call to {@link #requestPss}.
    786      */
    787     final ArrayList<ProcessRecord> mRequestPssList
    788             = new ArrayList<ProcessRecord>();
    789 
    790     /**
    791      * Runtime statistics collection thread.  This object's lock is used to
    792      * protect all related state.
    793      */
    794     final Thread mProcessStatsThread;
    795 
    796     /**
    797      * Used to collect process stats when showing not responding dialog.
    798      * Protected by mProcessStatsThread.
    799      */
    800     final ProcessStats mProcessStats = new ProcessStats(
    801             MONITOR_THREAD_CPU_USAGE);
    802     final AtomicLong mLastCpuTime = new AtomicLong(0);
    803     final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
    804 
    805     long mLastWriteTime = 0;
    806 
    807     /**
    808      * Set to true after the system has finished booting.
    809      */
    810     boolean mBooted = false;
    811 
    812     int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
    813     int mProcessLimitOverride = -1;
    814 
    815     WindowManagerService mWindowManager;
    816 
    817     static ActivityManagerService mSelf;
    818     static ActivityThread mSystemThread;
    819 
    820     private final class AppDeathRecipient implements IBinder.DeathRecipient {
    821         final ProcessRecord mApp;
    822         final int mPid;
    823         final IApplicationThread mAppThread;
    824 
    825         AppDeathRecipient(ProcessRecord app, int pid,
    826                 IApplicationThread thread) {
    827             if (localLOGV) Slog.v(
    828                 TAG, "New death recipient " + this
    829                 + " for thread " + thread.asBinder());
    830             mApp = app;
    831             mPid = pid;
    832             mAppThread = thread;
    833         }
    834 
    835         public void binderDied() {
    836             if (localLOGV) Slog.v(
    837                 TAG, "Death received in " + this
    838                 + " for thread " + mAppThread.asBinder());
    839             synchronized(ActivityManagerService.this) {
    840                 appDiedLocked(mApp, mPid, mAppThread);
    841             }
    842         }
    843     }
    844 
    845     static final int SHOW_ERROR_MSG = 1;
    846     static final int SHOW_NOT_RESPONDING_MSG = 2;
    847     static final int SHOW_FACTORY_ERROR_MSG = 3;
    848     static final int UPDATE_CONFIGURATION_MSG = 4;
    849     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
    850     static final int WAIT_FOR_DEBUGGER_MSG = 6;
    851     static final int BROADCAST_INTENT_MSG = 7;
    852     static final int BROADCAST_TIMEOUT_MSG = 8;
    853     static final int SERVICE_TIMEOUT_MSG = 12;
    854     static final int UPDATE_TIME_ZONE = 13;
    855     static final int SHOW_UID_ERROR_MSG = 14;
    856     static final int IM_FEELING_LUCKY_MSG = 15;
    857     static final int PROC_START_TIMEOUT_MSG = 20;
    858     static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
    859     static final int KILL_APPLICATION_MSG = 22;
    860     static final int FINALIZE_PENDING_INTENT_MSG = 23;
    861     static final int POST_HEAVY_NOTIFICATION_MSG = 24;
    862     static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
    863     static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
    864     static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
    865     static final int CLEAR_DNS_CACHE = 28;
    866     static final int UPDATE_HTTP_PROXY = 29;
    867     static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
    868     static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
    869     static final int DISPATCH_PROCESS_DIED = 32;
    870     static final int REPORT_MEM_USAGE = 33;
    871 
    872     AlertDialog mUidAlert;
    873     CompatModeDialog mCompatModeDialog;
    874     long mLastMemUsageReportTime = 0;
    875 
    876     final Handler mHandler = new Handler() {
    877         //public Handler() {
    878         //    if (localLOGV) Slog.v(TAG, "Handler started!");
    879         //}
    880 
    881         public void handleMessage(Message msg) {
    882             switch (msg.what) {
    883             case SHOW_ERROR_MSG: {
    884                 HashMap data = (HashMap) msg.obj;
    885                 synchronized (ActivityManagerService.this) {
    886                     ProcessRecord proc = (ProcessRecord)data.get("app");
    887                     if (proc != null && proc.crashDialog != null) {
    888                         Slog.e(TAG, "App already has crash dialog: " + proc);
    889                         return;
    890                     }
    891                     AppErrorResult res = (AppErrorResult) data.get("result");
    892                     if (!mSleeping && !mShuttingDown) {
    893                         Dialog d = new AppErrorDialog(mContext, res, proc);
    894                         d.show();
    895                         proc.crashDialog = d;
    896                     } else {
    897                         // The device is asleep, so just pretend that the user
    898                         // saw a crash dialog and hit "force quit".
    899                         res.set(0);
    900                     }
    901                 }
    902 
    903                 ensureBootCompleted();
    904             } break;
    905             case SHOW_NOT_RESPONDING_MSG: {
    906                 synchronized (ActivityManagerService.this) {
    907                     HashMap data = (HashMap) msg.obj;
    908                     ProcessRecord proc = (ProcessRecord)data.get("app");
    909                     if (proc != null && proc.anrDialog != null) {
    910                         Slog.e(TAG, "App already has anr dialog: " + proc);
    911                         return;
    912                     }
    913 
    914                     Intent intent = new Intent("android.intent.action.ANR");
    915                     if (!mProcessesReady) {
    916                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    917                     }
    918                     broadcastIntentLocked(null, null, intent,
    919                             null, null, 0, null, null, null,
    920                             false, false, MY_PID, Process.SYSTEM_UID);
    921 
    922                     Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
    923                             mContext, proc, (ActivityRecord)data.get("activity"));
    924                     d.show();
    925                     proc.anrDialog = d;
    926                 }
    927 
    928                 ensureBootCompleted();
    929             } break;
    930             case SHOW_STRICT_MODE_VIOLATION_MSG: {
    931                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
    932                 synchronized (ActivityManagerService.this) {
    933                     ProcessRecord proc = (ProcessRecord) data.get("app");
    934                     if (proc == null) {
    935                         Slog.e(TAG, "App not found when showing strict mode dialog.");
    936                         break;
    937                     }
    938                     if (proc.crashDialog != null) {
    939                         Slog.e(TAG, "App already has strict mode dialog: " + proc);
    940                         return;
    941                     }
    942                     AppErrorResult res = (AppErrorResult) data.get("result");
    943                     if (!mSleeping && !mShuttingDown) {
    944                         Dialog d = new StrictModeViolationDialog(mContext, res, proc);
    945                         d.show();
    946                         proc.crashDialog = d;
    947                     } else {
    948                         // The device is asleep, so just pretend that the user
    949                         // saw a crash dialog and hit "force quit".
    950                         res.set(0);
    951                     }
    952                 }
    953                 ensureBootCompleted();
    954             } break;
    955             case SHOW_FACTORY_ERROR_MSG: {
    956                 Dialog d = new FactoryErrorDialog(
    957                     mContext, msg.getData().getCharSequence("msg"));
    958                 d.show();
    959                 ensureBootCompleted();
    960             } break;
    961             case UPDATE_CONFIGURATION_MSG: {
    962                 final ContentResolver resolver = mContext.getContentResolver();
    963                 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
    964             } break;
    965             case GC_BACKGROUND_PROCESSES_MSG: {
    966                 synchronized (ActivityManagerService.this) {
    967                     performAppGcsIfAppropriateLocked();
    968                 }
    969             } break;
    970             case WAIT_FOR_DEBUGGER_MSG: {
    971                 synchronized (ActivityManagerService.this) {
    972                     ProcessRecord app = (ProcessRecord)msg.obj;
    973                     if (msg.arg1 != 0) {
    974                         if (!app.waitedForDebugger) {
    975                             Dialog d = new AppWaitingForDebuggerDialog(
    976                                     ActivityManagerService.this,
    977                                     mContext, app);
    978                             app.waitDialog = d;
    979                             app.waitedForDebugger = true;
    980                             d.show();
    981                         }
    982                     } else {
    983                         if (app.waitDialog != null) {
    984                             app.waitDialog.dismiss();
    985                             app.waitDialog = null;
    986                         }
    987                     }
    988                 }
    989             } break;
    990             case BROADCAST_INTENT_MSG: {
    991                 if (DEBUG_BROADCAST) Slog.v(
    992                         TAG, "Received BROADCAST_INTENT_MSG");
    993                 processNextBroadcast(true);
    994             } break;
    995             case BROADCAST_TIMEOUT_MSG: {
    996                 synchronized (ActivityManagerService.this) {
    997                     broadcastTimeoutLocked(true);
    998                 }
    999             } break;
   1000             case SERVICE_TIMEOUT_MSG: {
   1001                 if (mDidDexOpt) {
   1002                     mDidDexOpt = false;
   1003                     Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
   1004                     nmsg.obj = msg.obj;
   1005                     mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
   1006                     return;
   1007                 }
   1008                 serviceTimeout((ProcessRecord)msg.obj);
   1009             } break;
   1010             case UPDATE_TIME_ZONE: {
   1011                 synchronized (ActivityManagerService.this) {
   1012                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1013                         ProcessRecord r = mLruProcesses.get(i);
   1014                         if (r.thread != null) {
   1015                             try {
   1016                                 r.thread.updateTimeZone();
   1017                             } catch (RemoteException ex) {
   1018                                 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
   1019                             }
   1020                         }
   1021                     }
   1022                 }
   1023             } break;
   1024             case CLEAR_DNS_CACHE: {
   1025                 synchronized (ActivityManagerService.this) {
   1026                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1027                         ProcessRecord r = mLruProcesses.get(i);
   1028                         if (r.thread != null) {
   1029                             try {
   1030                                 r.thread.clearDnsCache();
   1031                             } catch (RemoteException ex) {
   1032                                 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
   1033                             }
   1034                         }
   1035                     }
   1036                 }
   1037             } break;
   1038             case UPDATE_HTTP_PROXY: {
   1039                 ProxyProperties proxy = (ProxyProperties)msg.obj;
   1040                 String host = "";
   1041                 String port = "";
   1042                 String exclList = "";
   1043                 if (proxy != null) {
   1044                     host = proxy.getHost();
   1045                     port = Integer.toString(proxy.getPort());
   1046                     exclList = proxy.getExclusionList();
   1047                 }
   1048                 synchronized (ActivityManagerService.this) {
   1049                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1050                         ProcessRecord r = mLruProcesses.get(i);
   1051                         if (r.thread != null) {
   1052                             try {
   1053                                 r.thread.setHttpProxy(host, port, exclList);
   1054                             } catch (RemoteException ex) {
   1055                                 Slog.w(TAG, "Failed to update http proxy for: " +
   1056                                         r.info.processName);
   1057                             }
   1058                         }
   1059                     }
   1060                 }
   1061             } break;
   1062             case SHOW_UID_ERROR_MSG: {
   1063                 // XXX This is a temporary dialog, no need to localize.
   1064                 AlertDialog d = new BaseErrorDialog(mContext);
   1065                 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
   1066                 d.setCancelable(false);
   1067                 d.setTitle("System UIDs Inconsistent");
   1068                 d.setMessage("UIDs on the system are inconsistent, you need to wipe your data partition or your device will be unstable.");
   1069                 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
   1070                         mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
   1071                 mUidAlert = d;
   1072                 d.show();
   1073             } break;
   1074             case IM_FEELING_LUCKY_MSG: {
   1075                 if (mUidAlert != null) {
   1076                     mUidAlert.dismiss();
   1077                     mUidAlert = null;
   1078                 }
   1079             } break;
   1080             case PROC_START_TIMEOUT_MSG: {
   1081                 if (mDidDexOpt) {
   1082                     mDidDexOpt = false;
   1083                     Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
   1084                     nmsg.obj = msg.obj;
   1085                     mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
   1086                     return;
   1087                 }
   1088                 ProcessRecord app = (ProcessRecord)msg.obj;
   1089                 synchronized (ActivityManagerService.this) {
   1090                     processStartTimedOutLocked(app);
   1091                 }
   1092             } break;
   1093             case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
   1094                 synchronized (ActivityManagerService.this) {
   1095                     doPendingActivityLaunchesLocked(true);
   1096                 }
   1097             } break;
   1098             case KILL_APPLICATION_MSG: {
   1099                 synchronized (ActivityManagerService.this) {
   1100                     int uid = msg.arg1;
   1101                     boolean restart = (msg.arg2 == 1);
   1102                     String pkg = (String) msg.obj;
   1103                     forceStopPackageLocked(pkg, uid, restart, false, true, false);
   1104                 }
   1105             } break;
   1106             case FINALIZE_PENDING_INTENT_MSG: {
   1107                 ((PendingIntentRecord)msg.obj).completeFinalize();
   1108             } break;
   1109             case POST_HEAVY_NOTIFICATION_MSG: {
   1110                 INotificationManager inm = NotificationManager.getService();
   1111                 if (inm == null) {
   1112                     return;
   1113                 }
   1114 
   1115                 ActivityRecord root = (ActivityRecord)msg.obj;
   1116                 ProcessRecord process = root.app;
   1117                 if (process == null) {
   1118                     return;
   1119                 }
   1120 
   1121                 try {
   1122                     Context context = mContext.createPackageContext(process.info.packageName, 0);
   1123                     String text = mContext.getString(R.string.heavy_weight_notification,
   1124                             context.getApplicationInfo().loadLabel(context.getPackageManager()));
   1125                     Notification notification = new Notification();
   1126                     notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
   1127                     notification.when = 0;
   1128                     notification.flags = Notification.FLAG_ONGOING_EVENT;
   1129                     notification.tickerText = text;
   1130                     notification.defaults = 0; // please be quiet
   1131                     notification.sound = null;
   1132                     notification.vibrate = null;
   1133                     notification.setLatestEventInfo(context, text,
   1134                             mContext.getText(R.string.heavy_weight_notification_detail),
   1135                             PendingIntent.getActivity(mContext, 0, root.intent,
   1136                                     PendingIntent.FLAG_CANCEL_CURRENT));
   1137 
   1138                     try {
   1139                         int[] outId = new int[1];
   1140                         inm.enqueueNotification("android", R.string.heavy_weight_notification,
   1141                                 notification, outId);
   1142                     } catch (RuntimeException e) {
   1143                         Slog.w(ActivityManagerService.TAG,
   1144                                 "Error showing notification for heavy-weight app", e);
   1145                     } catch (RemoteException e) {
   1146                     }
   1147                 } catch (NameNotFoundException e) {
   1148                     Slog.w(TAG, "Unable to create context for heavy notification", e);
   1149                 }
   1150             } break;
   1151             case CANCEL_HEAVY_NOTIFICATION_MSG: {
   1152                 INotificationManager inm = NotificationManager.getService();
   1153                 if (inm == null) {
   1154                     return;
   1155                 }
   1156                 try {
   1157                     inm.cancelNotification("android",
   1158                             R.string.heavy_weight_notification);
   1159                 } catch (RuntimeException e) {
   1160                     Slog.w(ActivityManagerService.TAG,
   1161                             "Error canceling notification for service", e);
   1162                 } catch (RemoteException e) {
   1163                 }
   1164             } break;
   1165             case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
   1166                 synchronized (ActivityManagerService.this) {
   1167                     checkExcessivePowerUsageLocked(true);
   1168                     removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1169                     Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1170                     sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
   1171                 }
   1172             } break;
   1173             case SHOW_COMPAT_MODE_DIALOG_MSG: {
   1174                 synchronized (ActivityManagerService.this) {
   1175                     ActivityRecord ar = (ActivityRecord)msg.obj;
   1176                     if (mCompatModeDialog != null) {
   1177                         if (mCompatModeDialog.mAppInfo.packageName.equals(
   1178                                 ar.info.applicationInfo.packageName)) {
   1179                             return;
   1180                         }
   1181                         mCompatModeDialog.dismiss();
   1182                         mCompatModeDialog = null;
   1183                     }
   1184                     if (ar != null && false) {
   1185                         if (mCompatModePackages.getPackageAskCompatModeLocked(
   1186                                 ar.packageName)) {
   1187                             int mode = mCompatModePackages.computeCompatModeLocked(
   1188                                     ar.info.applicationInfo);
   1189                             if (mode == ActivityManager.COMPAT_MODE_DISABLED
   1190                                     || mode == ActivityManager.COMPAT_MODE_ENABLED) {
   1191                                 mCompatModeDialog = new CompatModeDialog(
   1192                                         ActivityManagerService.this, mContext,
   1193                                         ar.info.applicationInfo);
   1194                                 mCompatModeDialog.show();
   1195                             }
   1196                         }
   1197                     }
   1198                 }
   1199                 break;
   1200             }
   1201             case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
   1202                 final int pid = msg.arg1;
   1203                 final int uid = msg.arg2;
   1204                 final boolean foregroundActivities = (Boolean) msg.obj;
   1205                 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
   1206                 break;
   1207             }
   1208             case DISPATCH_PROCESS_DIED: {
   1209                 final int pid = msg.arg1;
   1210                 final int uid = msg.arg2;
   1211                 dispatchProcessDied(pid, uid);
   1212                 break;
   1213             }
   1214             case REPORT_MEM_USAGE: {
   1215                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
   1216                 if (!isDebuggable) {
   1217                     return;
   1218                 }
   1219                 synchronized (ActivityManagerService.this) {
   1220                     long now = SystemClock.uptimeMillis();
   1221                     if (now < (mLastMemUsageReportTime+5*60*1000)) {
   1222                         // Don't report more than every 5 minutes to somewhat
   1223                         // avoid spamming.
   1224                         return;
   1225                     }
   1226                     mLastMemUsageReportTime = now;
   1227                 }
   1228                 Thread thread = new Thread() {
   1229                     @Override public void run() {
   1230                         StringBuilder dropBuilder = new StringBuilder(1024);
   1231                         StringBuilder logBuilder = new StringBuilder(1024);
   1232                         StringWriter oomSw = new StringWriter();
   1233                         PrintWriter oomPw = new PrintWriter(oomSw);
   1234                         StringWriter catSw = new StringWriter();
   1235                         PrintWriter catPw = new PrintWriter(catSw);
   1236                         String[] emptyArgs = new String[] { };
   1237                         StringBuilder tag = new StringBuilder(128);
   1238                         StringBuilder stack = new StringBuilder(128);
   1239                         tag.append("Low on memory -- ");
   1240                         dumpApplicationMemoryUsage(null, oomPw, "  ", emptyArgs, true, catPw,
   1241                                 tag, stack);
   1242                         dropBuilder.append(stack);
   1243                         dropBuilder.append('\n');
   1244                         dropBuilder.append('\n');
   1245                         String oomString = oomSw.toString();
   1246                         dropBuilder.append(oomString);
   1247                         dropBuilder.append('\n');
   1248                         logBuilder.append(oomString);
   1249                         try {
   1250                             java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
   1251                                     "procrank", });
   1252                             final InputStreamReader converter = new InputStreamReader(
   1253                                     proc.getInputStream());
   1254                             BufferedReader in = new BufferedReader(converter);
   1255                             String line;
   1256                             while (true) {
   1257                                 line = in.readLine();
   1258                                 if (line == null) {
   1259                                     break;
   1260                                 }
   1261                                 if (line.length() > 0) {
   1262                                     logBuilder.append(line);
   1263                                     logBuilder.append('\n');
   1264                                 }
   1265                                 dropBuilder.append(line);
   1266                                 dropBuilder.append('\n');
   1267                             }
   1268                             converter.close();
   1269                         } catch (IOException e) {
   1270                         }
   1271                         synchronized (ActivityManagerService.this) {
   1272                             catPw.println();
   1273                             dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
   1274                             catPw.println();
   1275                             dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
   1276                             catPw.println();
   1277                             dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
   1278                         }
   1279                         dropBuilder.append(catSw.toString());
   1280                         addErrorToDropBox("lowmem", null, "system_server", null,
   1281                                 null, tag.toString(), dropBuilder.toString(), null, null);
   1282                         Slog.i(TAG, logBuilder.toString());
   1283                         synchronized (ActivityManagerService.this) {
   1284                             long now = SystemClock.uptimeMillis();
   1285                             if (mLastMemUsageReportTime < now) {
   1286                                 mLastMemUsageReportTime = now;
   1287                             }
   1288                         }
   1289                     }
   1290                 };
   1291                 thread.start();
   1292                 break;
   1293             }
   1294             }
   1295         }
   1296     };
   1297 
   1298     public static void setSystemProcess() {
   1299         try {
   1300             ActivityManagerService m = mSelf;
   1301 
   1302             ServiceManager.addService("activity", m);
   1303             ServiceManager.addService("meminfo", new MemBinder(m));
   1304             ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
   1305             if (MONITOR_CPU_USAGE) {
   1306                 ServiceManager.addService("cpuinfo", new CpuBinder(m));
   1307             }
   1308             ServiceManager.addService("permission", new PermissionController(m));
   1309 
   1310             ApplicationInfo info =
   1311                 mSelf.mContext.getPackageManager().getApplicationInfo(
   1312                         "android", STOCK_PM_FLAGS);
   1313             mSystemThread.installSystemApplicationInfo(info);
   1314 
   1315             synchronized (mSelf) {
   1316                 ProcessRecord app = mSelf.newProcessRecordLocked(
   1317                         mSystemThread.getApplicationThread(), info,
   1318                         info.processName);
   1319                 app.persistent = true;
   1320                 app.pid = MY_PID;
   1321                 app.maxAdj = ProcessList.SYSTEM_ADJ;
   1322                 mSelf.mProcessNames.put(app.processName, app.info.uid, app);
   1323                 synchronized (mSelf.mPidsSelfLocked) {
   1324                     mSelf.mPidsSelfLocked.put(app.pid, app);
   1325                 }
   1326                 mSelf.updateLruProcessLocked(app, true, true);
   1327             }
   1328         } catch (PackageManager.NameNotFoundException e) {
   1329             throw new RuntimeException(
   1330                     "Unable to find android system package", e);
   1331         }
   1332     }
   1333 
   1334     public void setWindowManager(WindowManagerService wm) {
   1335         mWindowManager = wm;
   1336     }
   1337 
   1338     public static final Context main(int factoryTest) {
   1339         AThread thr = new AThread();
   1340         thr.start();
   1341 
   1342         synchronized (thr) {
   1343             while (thr.mService == null) {
   1344                 try {
   1345                     thr.wait();
   1346                 } catch (InterruptedException e) {
   1347                 }
   1348             }
   1349         }
   1350 
   1351         ActivityManagerService m = thr.mService;
   1352         mSelf = m;
   1353         ActivityThread at = ActivityThread.systemMain();
   1354         mSystemThread = at;
   1355         Context context = at.getSystemContext();
   1356         context.setTheme(android.R.style.Theme_Holo);
   1357         m.mContext = context;
   1358         m.mFactoryTest = factoryTest;
   1359         m.mMainStack = new ActivityStack(m, context, true);
   1360 
   1361         m.mBatteryStatsService.publish(context);
   1362         m.mUsageStatsService.publish(context);
   1363 
   1364         synchronized (thr) {
   1365             thr.mReady = true;
   1366             thr.notifyAll();
   1367         }
   1368 
   1369         m.startRunning(null, null, null, null);
   1370 
   1371         return context;
   1372     }
   1373 
   1374     public static ActivityManagerService self() {
   1375         return mSelf;
   1376     }
   1377 
   1378     static class AThread extends Thread {
   1379         ActivityManagerService mService;
   1380         boolean mReady = false;
   1381 
   1382         public AThread() {
   1383             super("ActivityManager");
   1384         }
   1385 
   1386         public void run() {
   1387             Looper.prepare();
   1388 
   1389             android.os.Process.setThreadPriority(
   1390                     android.os.Process.THREAD_PRIORITY_FOREGROUND);
   1391             android.os.Process.setCanSelfBackground(false);
   1392 
   1393             ActivityManagerService m = new ActivityManagerService();
   1394 
   1395             synchronized (this) {
   1396                 mService = m;
   1397                 notifyAll();
   1398             }
   1399 
   1400             synchronized (this) {
   1401                 while (!mReady) {
   1402                     try {
   1403                         wait();
   1404                     } catch (InterruptedException e) {
   1405                     }
   1406                 }
   1407             }
   1408 
   1409             // For debug builds, log event loop stalls to dropbox for analysis.
   1410             if (StrictMode.conditionallyEnableDebugLogging()) {
   1411                 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
   1412             }
   1413 
   1414             Looper.loop();
   1415         }
   1416     }
   1417 
   1418     static class MemBinder extends Binder {
   1419         ActivityManagerService mActivityManagerService;
   1420         MemBinder(ActivityManagerService activityManagerService) {
   1421             mActivityManagerService = activityManagerService;
   1422         }
   1423 
   1424         @Override
   1425         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   1426             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   1427                     != PackageManager.PERMISSION_GRANTED) {
   1428                 pw.println("Permission Denial: can't dump meminfo from from pid="
   1429                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   1430                         + " without permission " + android.Manifest.permission.DUMP);
   1431                 return;
   1432             }
   1433 
   1434             mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, "  ", args,
   1435                     false, null, null, null);
   1436         }
   1437     }
   1438 
   1439     static class GraphicsBinder extends Binder {
   1440         ActivityManagerService mActivityManagerService;
   1441         GraphicsBinder(ActivityManagerService activityManagerService) {
   1442             mActivityManagerService = activityManagerService;
   1443         }
   1444 
   1445         @Override
   1446         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   1447             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   1448                     != PackageManager.PERMISSION_GRANTED) {
   1449                 pw.println("Permission Denial: can't dump gfxinfo from from pid="
   1450                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   1451                         + " without permission " + android.Manifest.permission.DUMP);
   1452                 return;
   1453             }
   1454 
   1455             mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
   1456         }
   1457     }
   1458 
   1459     static class CpuBinder extends Binder {
   1460         ActivityManagerService mActivityManagerService;
   1461         CpuBinder(ActivityManagerService activityManagerService) {
   1462             mActivityManagerService = activityManagerService;
   1463         }
   1464 
   1465         @Override
   1466         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   1467             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   1468                     != PackageManager.PERMISSION_GRANTED) {
   1469                 pw.println("Permission Denial: can't dump cpuinfo from from pid="
   1470                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   1471                         + " without permission " + android.Manifest.permission.DUMP);
   1472                 return;
   1473             }
   1474 
   1475             synchronized (mActivityManagerService.mProcessStatsThread) {
   1476                 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
   1477                 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
   1478                         SystemClock.uptimeMillis()));
   1479             }
   1480         }
   1481     }
   1482 
   1483     private ActivityManagerService() {
   1484         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
   1485 
   1486         File dataDir = Environment.getDataDirectory();
   1487         File systemDir = new File(dataDir, "system");
   1488         systemDir.mkdirs();
   1489         mBatteryStatsService = new BatteryStatsService(new File(
   1490                 systemDir, "batterystats.bin").toString());
   1491         mBatteryStatsService.getActiveStatistics().readLocked();
   1492         mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
   1493         mOnBattery = DEBUG_POWER ? true
   1494                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
   1495         mBatteryStatsService.getActiveStatistics().setCallback(this);
   1496 
   1497         mUsageStatsService = new UsageStatsService(new File(
   1498                 systemDir, "usagestats").toString());
   1499 
   1500         GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
   1501             ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
   1502 
   1503         mConfiguration.setToDefaults();
   1504         mConfiguration.locale = Locale.getDefault();
   1505         mConfigurationSeq = mConfiguration.seq = 1;
   1506         mProcessStats.init();
   1507 
   1508         mCompatModePackages = new CompatModePackages(this, systemDir);
   1509 
   1510         // Add ourself to the Watchdog monitors.
   1511         Watchdog.getInstance().addMonitor(this);
   1512 
   1513         mProcessStatsThread = new Thread("ProcessStats") {
   1514             public void run() {
   1515                 while (true) {
   1516                     try {
   1517                         try {
   1518                             synchronized(this) {
   1519                                 final long now = SystemClock.uptimeMillis();
   1520                                 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
   1521                                 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
   1522                                 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
   1523                                 //        + ", write delay=" + nextWriteDelay);
   1524                                 if (nextWriteDelay < nextCpuDelay) {
   1525                                     nextCpuDelay = nextWriteDelay;
   1526                                 }
   1527                                 if (nextCpuDelay > 0) {
   1528                                     mProcessStatsMutexFree.set(true);
   1529                                     this.wait(nextCpuDelay);
   1530                                 }
   1531                             }
   1532                         } catch (InterruptedException e) {
   1533                         }
   1534                         updateCpuStatsNow();
   1535                     } catch (Exception e) {
   1536                         Slog.e(TAG, "Unexpected exception collecting process stats", e);
   1537                     }
   1538                 }
   1539             }
   1540         };
   1541         mProcessStatsThread.start();
   1542     }
   1543 
   1544     @Override
   1545     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
   1546             throws RemoteException {
   1547         try {
   1548             return super.onTransact(code, data, reply, flags);
   1549         } catch (RuntimeException e) {
   1550             // The activity manager only throws security exceptions, so let's
   1551             // log all others.
   1552             if (!(e instanceof SecurityException)) {
   1553                 Slog.e(TAG, "Activity Manager Crash", e);
   1554             }
   1555             throw e;
   1556         }
   1557     }
   1558 
   1559     void updateCpuStats() {
   1560         final long now = SystemClock.uptimeMillis();
   1561         if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
   1562             return;
   1563         }
   1564         if (mProcessStatsMutexFree.compareAndSet(true, false)) {
   1565             synchronized (mProcessStatsThread) {
   1566                 mProcessStatsThread.notify();
   1567             }
   1568         }
   1569     }
   1570 
   1571     void updateCpuStatsNow() {
   1572         synchronized (mProcessStatsThread) {
   1573             mProcessStatsMutexFree.set(false);
   1574             final long now = SystemClock.uptimeMillis();
   1575             boolean haveNewCpuStats = false;
   1576 
   1577             if (MONITOR_CPU_USAGE &&
   1578                     mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
   1579                 mLastCpuTime.set(now);
   1580                 haveNewCpuStats = true;
   1581                 mProcessStats.update();
   1582                 //Slog.i(TAG, mProcessStats.printCurrentState());
   1583                 //Slog.i(TAG, "Total CPU usage: "
   1584                 //        + mProcessStats.getTotalCpuPercent() + "%");
   1585 
   1586                 // Slog the cpu usage if the property is set.
   1587                 if ("true".equals(SystemProperties.get("events.cpu"))) {
   1588                     int user = mProcessStats.getLastUserTime();
   1589                     int system = mProcessStats.getLastSystemTime();
   1590                     int iowait = mProcessStats.getLastIoWaitTime();
   1591                     int irq = mProcessStats.getLastIrqTime();
   1592                     int softIrq = mProcessStats.getLastSoftIrqTime();
   1593                     int idle = mProcessStats.getLastIdleTime();
   1594 
   1595                     int total = user + system + iowait + irq + softIrq + idle;
   1596                     if (total == 0) total = 1;
   1597 
   1598                     EventLog.writeEvent(EventLogTags.CPU,
   1599                             ((user+system+iowait+irq+softIrq) * 100) / total,
   1600                             (user * 100) / total,
   1601                             (system * 100) / total,
   1602                             (iowait * 100) / total,
   1603                             (irq * 100) / total,
   1604                             (softIrq * 100) / total);
   1605                 }
   1606             }
   1607 
   1608             long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
   1609             final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
   1610             synchronized(bstats) {
   1611                 synchronized(mPidsSelfLocked) {
   1612                     if (haveNewCpuStats) {
   1613                         if (mOnBattery) {
   1614                             int perc = bstats.startAddingCpuLocked();
   1615                             int totalUTime = 0;
   1616                             int totalSTime = 0;
   1617                             final int N = mProcessStats.countStats();
   1618                             for (int i=0; i<N; i++) {
   1619                                 ProcessStats.Stats st = mProcessStats.getStats(i);
   1620                                 if (!st.working) {
   1621                                     continue;
   1622                                 }
   1623                                 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
   1624                                 int otherUTime = (st.rel_utime*perc)/100;
   1625                                 int otherSTime = (st.rel_stime*perc)/100;
   1626                                 totalUTime += otherUTime;
   1627                                 totalSTime += otherSTime;
   1628                                 if (pr != null) {
   1629                                     BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
   1630                                     ps.addCpuTimeLocked(st.rel_utime-otherUTime,
   1631                                             st.rel_stime-otherSTime);
   1632                                     ps.addSpeedStepTimes(cpuSpeedTimes);
   1633                                     pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
   1634                                 } else {
   1635                                     BatteryStatsImpl.Uid.Proc ps =
   1636                                             bstats.getProcessStatsLocked(st.name, st.pid);
   1637                                     if (ps != null) {
   1638                                         ps.addCpuTimeLocked(st.rel_utime-otherUTime,
   1639                                                 st.rel_stime-otherSTime);
   1640                                         ps.addSpeedStepTimes(cpuSpeedTimes);
   1641                                     }
   1642                                 }
   1643                             }
   1644                             bstats.finishAddingCpuLocked(perc, totalUTime,
   1645                                     totalSTime, cpuSpeedTimes);
   1646                         }
   1647                     }
   1648                 }
   1649 
   1650                 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
   1651                     mLastWriteTime = now;
   1652                     mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
   1653                 }
   1654             }
   1655         }
   1656     }
   1657 
   1658     @Override
   1659     public void batteryNeedsCpuUpdate() {
   1660         updateCpuStatsNow();
   1661     }
   1662 
   1663     @Override
   1664     public void batteryPowerChanged(boolean onBattery) {
   1665         // When plugging in, update the CPU stats first before changing
   1666         // the plug state.
   1667         updateCpuStatsNow();
   1668         synchronized (this) {
   1669             synchronized(mPidsSelfLocked) {
   1670                 mOnBattery = DEBUG_POWER ? true : onBattery;
   1671             }
   1672         }
   1673     }
   1674 
   1675     /**
   1676      * Initialize the application bind args. These are passed to each
   1677      * process when the bindApplication() IPC is sent to the process. They're
   1678      * lazily setup to make sure the services are running when they're asked for.
   1679      */
   1680     private HashMap<String, IBinder> getCommonServicesLocked() {
   1681         if (mAppBindArgs == null) {
   1682             mAppBindArgs = new HashMap<String, IBinder>();
   1683 
   1684             // Setup the application init args
   1685             mAppBindArgs.put("package", ServiceManager.getService("package"));
   1686             mAppBindArgs.put("window", ServiceManager.getService("window"));
   1687             mAppBindArgs.put(Context.ALARM_SERVICE,
   1688                     ServiceManager.getService(Context.ALARM_SERVICE));
   1689         }
   1690         return mAppBindArgs;
   1691     }
   1692 
   1693     final void setFocusedActivityLocked(ActivityRecord r) {
   1694         if (mFocusedActivity != r) {
   1695             mFocusedActivity = r;
   1696             if (r != null) {
   1697                 mWindowManager.setFocusedApp(r.appToken, true);
   1698             }
   1699         }
   1700     }
   1701 
   1702     private final void updateLruProcessInternalLocked(ProcessRecord app,
   1703             boolean oomAdj, boolean updateActivityTime, int bestPos) {
   1704         // put it on the LRU to keep track of when it should be exited.
   1705         int lrui = mLruProcesses.indexOf(app);
   1706         if (lrui >= 0) mLruProcesses.remove(lrui);
   1707 
   1708         int i = mLruProcesses.size()-1;
   1709         int skipTop = 0;
   1710 
   1711         app.lruSeq = mLruSeq;
   1712 
   1713         // compute the new weight for this process.
   1714         if (updateActivityTime) {
   1715             app.lastActivityTime = SystemClock.uptimeMillis();
   1716         }
   1717         if (app.activities.size() > 0) {
   1718             // If this process has activities, we more strongly want to keep
   1719             // it around.
   1720             app.lruWeight = app.lastActivityTime;
   1721         } else if (app.pubProviders.size() > 0) {
   1722             // If this process contains content providers, we want to keep
   1723             // it a little more strongly.
   1724             app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
   1725             // Also don't let it kick out the first few "real" hidden processes.
   1726             skipTop = ProcessList.MIN_HIDDEN_APPS;
   1727         } else {
   1728             // If this process doesn't have activities, we less strongly
   1729             // want to keep it around, and generally want to avoid getting
   1730             // in front of any very recently used activities.
   1731             app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
   1732             // Also don't let it kick out the first few "real" hidden processes.
   1733             skipTop = ProcessList.MIN_HIDDEN_APPS;
   1734         }
   1735 
   1736         while (i >= 0) {
   1737             ProcessRecord p = mLruProcesses.get(i);
   1738             // If this app shouldn't be in front of the first N background
   1739             // apps, then skip over that many that are currently hidden.
   1740             if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
   1741                 skipTop--;
   1742             }
   1743             if (p.lruWeight <= app.lruWeight || i < bestPos) {
   1744                 mLruProcesses.add(i+1, app);
   1745                 break;
   1746             }
   1747             i--;
   1748         }
   1749         if (i < 0) {
   1750             mLruProcesses.add(0, app);
   1751         }
   1752 
   1753         // If the app is currently using a content provider or service,
   1754         // bump those processes as well.
   1755         if (app.connections.size() > 0) {
   1756             for (ConnectionRecord cr : app.connections) {
   1757                 if (cr.binding != null && cr.binding.service != null
   1758                         && cr.binding.service.app != null
   1759                         && cr.binding.service.app.lruSeq != mLruSeq) {
   1760                     updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
   1761                             updateActivityTime, i+1);
   1762                 }
   1763             }
   1764         }
   1765         if (app.conProviders.size() > 0) {
   1766             for (ContentProviderRecord cpr : app.conProviders.keySet()) {
   1767                 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
   1768                     updateLruProcessInternalLocked(cpr.proc, oomAdj,
   1769                             updateActivityTime, i+1);
   1770                 }
   1771             }
   1772         }
   1773 
   1774         //Slog.i(TAG, "Putting proc to front: " + app.processName);
   1775         if (oomAdj) {
   1776             updateOomAdjLocked();
   1777         }
   1778     }
   1779 
   1780     final void updateLruProcessLocked(ProcessRecord app,
   1781             boolean oomAdj, boolean updateActivityTime) {
   1782         mLruSeq++;
   1783         updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
   1784     }
   1785 
   1786     final ProcessRecord getProcessRecordLocked(
   1787             String processName, int uid) {
   1788         if (uid == Process.SYSTEM_UID) {
   1789             // The system gets to run in any process.  If there are multiple
   1790             // processes with the same uid, just pick the first (this
   1791             // should never happen).
   1792             SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
   1793                     processName);
   1794             return procs != null ? procs.valueAt(0) : null;
   1795         }
   1796         ProcessRecord proc = mProcessNames.get(processName, uid);
   1797         return proc;
   1798     }
   1799 
   1800     void ensurePackageDexOpt(String packageName) {
   1801         IPackageManager pm = AppGlobals.getPackageManager();
   1802         try {
   1803             if (pm.performDexOpt(packageName)) {
   1804                 mDidDexOpt = true;
   1805             }
   1806         } catch (RemoteException e) {
   1807         }
   1808     }
   1809 
   1810     boolean isNextTransitionForward() {
   1811         int transit = mWindowManager.getPendingAppTransition();
   1812         return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
   1813                 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
   1814                 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
   1815     }
   1816 
   1817     final ProcessRecord startProcessLocked(String processName,
   1818             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
   1819             String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
   1820         ProcessRecord app = getProcessRecordLocked(processName, info.uid);
   1821         // We don't have to do anything more if:
   1822         // (1) There is an existing application record; and
   1823         // (2) The caller doesn't think it is dead, OR there is no thread
   1824         //     object attached to it so we know it couldn't have crashed; and
   1825         // (3) There is a pid assigned to it, so it is either starting or
   1826         //     already running.
   1827         if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
   1828                 + " app=" + app + " knownToBeDead=" + knownToBeDead
   1829                 + " thread=" + (app != null ? app.thread : null)
   1830                 + " pid=" + (app != null ? app.pid : -1));
   1831         if (app != null && app.pid > 0) {
   1832             if (!knownToBeDead || app.thread == null) {
   1833                 // We already have the app running, or are waiting for it to
   1834                 // come up (we have a pid but not yet its thread), so keep it.
   1835                 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
   1836                 // If this is a new package in the process, add the package to the list
   1837                 app.addPackage(info.packageName);
   1838                 return app;
   1839             } else {
   1840                 // An application record is attached to a previous process,
   1841                 // clean it up now.
   1842                 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
   1843                 handleAppDiedLocked(app, true, true);
   1844             }
   1845         }
   1846 
   1847         String hostingNameStr = hostingName != null
   1848                 ? hostingName.flattenToShortString() : null;
   1849 
   1850         if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
   1851             // If we are in the background, then check to see if this process
   1852             // is bad.  If so, we will just silently fail.
   1853             if (mBadProcesses.get(info.processName, info.uid) != null) {
   1854                 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
   1855                         + "/" + info.processName);
   1856                 return null;
   1857             }
   1858         } else {
   1859             // When the user is explicitly starting a process, then clear its
   1860             // crash count so that we won't make it bad until they see at
   1861             // least one crash dialog again, and make the process good again
   1862             // if it had been bad.
   1863             if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
   1864                     + "/" + info.processName);
   1865             mProcessCrashTimes.remove(info.processName, info.uid);
   1866             if (mBadProcesses.get(info.processName, info.uid) != null) {
   1867                 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
   1868                         info.processName);
   1869                 mBadProcesses.remove(info.processName, info.uid);
   1870                 if (app != null) {
   1871                     app.bad = false;
   1872                 }
   1873             }
   1874         }
   1875 
   1876         if (app == null) {
   1877             app = newProcessRecordLocked(null, info, processName);
   1878             mProcessNames.put(processName, info.uid, app);
   1879         } else {
   1880             // If this is a new package in the process, add the package to the list
   1881             app.addPackage(info.packageName);
   1882         }
   1883 
   1884         // If the system is not ready yet, then hold off on starting this
   1885         // process until it is.
   1886         if (!mProcessesReady
   1887                 && !isAllowedWhileBooting(info)
   1888                 && !allowWhileBooting) {
   1889             if (!mProcessesOnHold.contains(app)) {
   1890                 mProcessesOnHold.add(app);
   1891             }
   1892             if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
   1893             return app;
   1894         }
   1895 
   1896         startProcessLocked(app, hostingType, hostingNameStr);
   1897         return (app.pid != 0) ? app : null;
   1898     }
   1899 
   1900     boolean isAllowedWhileBooting(ApplicationInfo ai) {
   1901         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
   1902     }
   1903 
   1904     private final void startProcessLocked(ProcessRecord app,
   1905             String hostingType, String hostingNameStr) {
   1906         if (app.pid > 0 && app.pid != MY_PID) {
   1907             synchronized (mPidsSelfLocked) {
   1908                 mPidsSelfLocked.remove(app.pid);
   1909                 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
   1910             }
   1911             app.pid = 0;
   1912         }
   1913 
   1914         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
   1915                 "startProcessLocked removing on hold: " + app);
   1916         mProcessesOnHold.remove(app);
   1917 
   1918         updateCpuStats();
   1919 
   1920         System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
   1921         mProcDeaths[0] = 0;
   1922 
   1923         try {
   1924             int uid = app.info.uid;
   1925             int[] gids = null;
   1926             try {
   1927                 gids = mContext.getPackageManager().getPackageGids(
   1928                         app.info.packageName);
   1929             } catch (PackageManager.NameNotFoundException e) {
   1930                 Slog.w(TAG, "Unable to retrieve gids", e);
   1931             }
   1932             if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
   1933                 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
   1934                         && mTopComponent != null
   1935                         && app.processName.equals(mTopComponent.getPackageName())) {
   1936                     uid = 0;
   1937                 }
   1938                 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
   1939                         && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
   1940                     uid = 0;
   1941                 }
   1942             }
   1943             int debugFlags = 0;
   1944             if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
   1945                 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
   1946                 // Also turn on CheckJNI for debuggable apps. It's quite
   1947                 // awkward to turn on otherwise.
   1948                 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
   1949             }
   1950             // Run the app in safe mode if its manifest requests so or the
   1951             // system is booted in safe mode.
   1952             if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
   1953                 Zygote.systemInSafeMode == true) {
   1954                 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
   1955             }
   1956             if ("1".equals(SystemProperties.get("debug.checkjni"))) {
   1957                 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
   1958             }
   1959             if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
   1960                 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
   1961             }
   1962             if ("1".equals(SystemProperties.get("debug.assert"))) {
   1963                 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
   1964             }
   1965 
   1966             // Start the process.  It will either succeed and return a result containing
   1967             // the PID of the new process, or else throw a RuntimeException.
   1968             Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
   1969                     app.processName, uid, uid, gids, debugFlags,
   1970                     app.info.targetSdkVersion, null);
   1971 
   1972             BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
   1973             synchronized (bs) {
   1974                 if (bs.isOnBattery()) {
   1975                     app.batteryStats.incStartsLocked();
   1976                 }
   1977             }
   1978 
   1979             EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
   1980                     app.processName, hostingType,
   1981                     hostingNameStr != null ? hostingNameStr : "");
   1982 
   1983             if (app.persistent) {
   1984                 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
   1985             }
   1986 
   1987             StringBuilder buf = mStringBuilder;
   1988             buf.setLength(0);
   1989             buf.append("Start proc ");
   1990             buf.append(app.processName);
   1991             buf.append(" for ");
   1992             buf.append(hostingType);
   1993             if (hostingNameStr != null) {
   1994                 buf.append(" ");
   1995                 buf.append(hostingNameStr);
   1996             }
   1997             buf.append(": pid=");
   1998             buf.append(startResult.pid);
   1999             buf.append(" uid=");
   2000             buf.append(uid);
   2001             buf.append(" gids={");
   2002             if (gids != null) {
   2003                 for (int gi=0; gi<gids.length; gi++) {
   2004                     if (gi != 0) buf.append(", ");
   2005                     buf.append(gids[gi]);
   2006 
   2007                 }
   2008             }
   2009             buf.append("}");
   2010             Slog.i(TAG, buf.toString());
   2011             app.pid = startResult.pid;
   2012             app.usingWrapper = startResult.usingWrapper;
   2013             app.removed = false;
   2014             synchronized (mPidsSelfLocked) {
   2015                 this.mPidsSelfLocked.put(startResult.pid, app);
   2016                 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
   2017                 msg.obj = app;
   2018                 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
   2019                         ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
   2020             }
   2021         } catch (RuntimeException e) {
   2022             // XXX do better error recovery.
   2023             app.pid = 0;
   2024             Slog.e(TAG, "Failure starting process " + app.processName, e);
   2025         }
   2026     }
   2027 
   2028     void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
   2029         if (resumed) {
   2030             mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
   2031         } else {
   2032             mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
   2033         }
   2034     }
   2035 
   2036     boolean startHomeActivityLocked() {
   2037         if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
   2038                 && mTopAction == null) {
   2039             // We are running in factory test mode, but unable to find
   2040             // the factory test app, so just sit around displaying the
   2041             // error message and don't try to start anything.
   2042             return false;
   2043         }
   2044         Intent intent = new Intent(
   2045             mTopAction,
   2046             mTopData != null ? Uri.parse(mTopData) : null);
   2047         intent.setComponent(mTopComponent);
   2048         if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
   2049             intent.addCategory(Intent.CATEGORY_HOME);
   2050         }
   2051         ActivityInfo aInfo =
   2052             intent.resolveActivityInfo(mContext.getPackageManager(),
   2053                     STOCK_PM_FLAGS);
   2054         if (aInfo != null) {
   2055             intent.setComponent(new ComponentName(
   2056                     aInfo.applicationInfo.packageName, aInfo.name));
   2057             // Don't do this if the home app is currently being
   2058             // instrumented.
   2059             ProcessRecord app = getProcessRecordLocked(aInfo.processName,
   2060                     aInfo.applicationInfo.uid);
   2061             if (app == null || app.instrumentationClass == null) {
   2062                 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
   2063                 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
   2064                         null, null, 0, 0, 0, false, false, null);
   2065             }
   2066         }
   2067 
   2068 
   2069         return true;
   2070     }
   2071 
   2072     /**
   2073      * Starts the "new version setup screen" if appropriate.
   2074      */
   2075     void startSetupActivityLocked() {
   2076         // Only do this once per boot.
   2077         if (mCheckedForSetup) {
   2078             return;
   2079         }
   2080 
   2081         // We will show this screen if the current one is a different
   2082         // version than the last one shown, and we are not running in
   2083         // low-level factory test mode.
   2084         final ContentResolver resolver = mContext.getContentResolver();
   2085         if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
   2086                 Settings.Secure.getInt(resolver,
   2087                         Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
   2088             mCheckedForSetup = true;
   2089 
   2090             // See if we should be showing the platform update setup UI.
   2091             Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
   2092             List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
   2093                     .queryIntentActivities(intent, PackageManager.GET_META_DATA);
   2094 
   2095             // We don't allow third party apps to replace this.
   2096             ResolveInfo ri = null;
   2097             for (int i=0; ris != null && i<ris.size(); i++) {
   2098                 if ((ris.get(i).activityInfo.applicationInfo.flags
   2099                         & ApplicationInfo.FLAG_SYSTEM) != 0) {
   2100                     ri = ris.get(i);
   2101                     break;
   2102                 }
   2103             }
   2104 
   2105             if (ri != null) {
   2106                 String vers = ri.activityInfo.metaData != null
   2107                         ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
   2108                         : null;
   2109                 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
   2110                     vers = ri.activityInfo.applicationInfo.metaData.getString(
   2111                             Intent.METADATA_SETUP_VERSION);
   2112                 }
   2113                 String lastVers = Settings.Secure.getString(
   2114                         resolver, Settings.Secure.LAST_SETUP_SHOWN);
   2115                 if (vers != null && !vers.equals(lastVers)) {
   2116                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   2117                     intent.setComponent(new ComponentName(
   2118                             ri.activityInfo.packageName, ri.activityInfo.name));
   2119                     mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
   2120                             null, null, 0, 0, 0, false, false, null);
   2121                 }
   2122             }
   2123         }
   2124     }
   2125 
   2126     CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
   2127         return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
   2128     }
   2129 
   2130     public int getFrontActivityScreenCompatMode() {
   2131         synchronized (this) {
   2132             return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
   2133         }
   2134     }
   2135 
   2136     public void setFrontActivityScreenCompatMode(int mode) {
   2137         synchronized (this) {
   2138             mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
   2139         }
   2140     }
   2141 
   2142     public int getPackageScreenCompatMode(String packageName) {
   2143         synchronized (this) {
   2144             return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
   2145         }
   2146     }
   2147 
   2148     public void setPackageScreenCompatMode(String packageName, int mode) {
   2149         synchronized (this) {
   2150             mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
   2151         }
   2152     }
   2153 
   2154     public boolean getPackageAskScreenCompat(String packageName) {
   2155         synchronized (this) {
   2156             return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
   2157         }
   2158     }
   2159 
   2160     public void setPackageAskScreenCompat(String packageName, boolean ask) {
   2161         synchronized (this) {
   2162             mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
   2163         }
   2164     }
   2165 
   2166     void reportResumedActivityLocked(ActivityRecord r) {
   2167         //Slog.i(TAG, "**** REPORT RESUME: " + r);
   2168 
   2169         final int identHash = System.identityHashCode(r);
   2170         updateUsageStats(r, true);
   2171 
   2172         int i = mWatchers.beginBroadcast();
   2173         while (i > 0) {
   2174             i--;
   2175             IActivityWatcher w = mWatchers.getBroadcastItem(i);
   2176             if (w != null) {
   2177                 try {
   2178                     w.activityResuming(identHash);
   2179                 } catch (RemoteException e) {
   2180                 }
   2181             }
   2182         }
   2183         mWatchers.finishBroadcast();
   2184     }
   2185 
   2186     private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
   2187         int i = mProcessObservers.beginBroadcast();
   2188         while (i > 0) {
   2189             i--;
   2190             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
   2191             if (observer != null) {
   2192                 try {
   2193                     observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
   2194                 } catch (RemoteException e) {
   2195                 }
   2196             }
   2197         }
   2198         mProcessObservers.finishBroadcast();
   2199     }
   2200 
   2201     private void dispatchProcessDied(int pid, int uid) {
   2202         int i = mProcessObservers.beginBroadcast();
   2203         while (i > 0) {
   2204             i--;
   2205             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
   2206             if (observer != null) {
   2207                 try {
   2208                     observer.onProcessDied(pid, uid);
   2209                 } catch (RemoteException e) {
   2210                 }
   2211             }
   2212         }
   2213         mProcessObservers.finishBroadcast();
   2214     }
   2215 
   2216     final void doPendingActivityLaunchesLocked(boolean doResume) {
   2217         final int N = mPendingActivityLaunches.size();
   2218         if (N <= 0) {
   2219             return;
   2220         }
   2221         for (int i=0; i<N; i++) {
   2222             PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
   2223             mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
   2224                     pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
   2225                     doResume && i == (N-1));
   2226         }
   2227         mPendingActivityLaunches.clear();
   2228     }
   2229 
   2230     public final int startActivity(IApplicationThread caller,
   2231             Intent intent, String resolvedType, Uri[] grantedUriPermissions,
   2232             int grantedMode, IBinder resultTo,
   2233             String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
   2234             String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
   2235         return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
   2236                 grantedUriPermissions, grantedMode, resultTo, resultWho,
   2237                 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
   2238                 null, null);
   2239     }
   2240 
   2241     public final WaitResult startActivityAndWait(IApplicationThread caller,
   2242             Intent intent, String resolvedType, Uri[] grantedUriPermissions,
   2243             int grantedMode, IBinder resultTo,
   2244             String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
   2245             String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
   2246         WaitResult res = new WaitResult();
   2247         mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
   2248                 grantedUriPermissions, grantedMode, resultTo, resultWho,
   2249                 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
   2250                 res, null);
   2251         return res;
   2252     }
   2253 
   2254     public final int startActivityWithConfig(IApplicationThread caller,
   2255             Intent intent, String resolvedType, Uri[] grantedUriPermissions,
   2256             int grantedMode, IBinder resultTo,
   2257             String resultWho, int requestCode, boolean onlyIfNeeded,
   2258             boolean debug, Configuration config) {
   2259         return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
   2260                 grantedUriPermissions, grantedMode, resultTo, resultWho,
   2261                 requestCode, onlyIfNeeded, debug, null, null, false, null, config);
   2262     }
   2263 
   2264     public int startActivityIntentSender(IApplicationThread caller,
   2265             IntentSender intent, Intent fillInIntent, String resolvedType,
   2266             IBinder resultTo, String resultWho, int requestCode,
   2267             int flagsMask, int flagsValues) {
   2268         // Refuse possible leaked file descriptors
   2269         if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
   2270             throw new IllegalArgumentException("File descriptors passed in Intent");
   2271         }
   2272 
   2273         IIntentSender sender = intent.getTarget();
   2274         if (!(sender instanceof PendingIntentRecord)) {
   2275             throw new IllegalArgumentException("Bad PendingIntent object");
   2276         }
   2277 
   2278         PendingIntentRecord pir = (PendingIntentRecord)sender;
   2279 
   2280         synchronized (this) {
   2281             // If this is coming from the currently resumed activity, it is
   2282             // effectively saying that app switches are allowed at this point.
   2283             if (mMainStack.mResumedActivity != null
   2284                     && mMainStack.mResumedActivity.info.applicationInfo.uid ==
   2285                             Binder.getCallingUid()) {
   2286                 mAppSwitchesAllowedTime = 0;
   2287             }
   2288         }
   2289 
   2290         return pir.sendInner(0, fillInIntent, resolvedType, null,
   2291                 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
   2292     }
   2293 
   2294     public boolean startNextMatchingActivity(IBinder callingActivity,
   2295             Intent intent) {
   2296         // Refuse possible leaked file descriptors
   2297         if (intent != null && intent.hasFileDescriptors() == true) {
   2298             throw new IllegalArgumentException("File descriptors passed in Intent");
   2299         }
   2300 
   2301         synchronized (this) {
   2302             ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
   2303             if (r == null) {
   2304                 return false;
   2305             }
   2306             if (r.app == null || r.app.thread == null) {
   2307                 // The caller is not running...  d'oh!
   2308                 return false;
   2309             }
   2310             intent = new Intent(intent);
   2311             // The caller is not allowed to change the data.
   2312             intent.setDataAndType(r.intent.getData(), r.intent.getType());
   2313             // And we are resetting to find the next component...
   2314             intent.setComponent(null);
   2315 
   2316             ActivityInfo aInfo = null;
   2317             try {
   2318                 List<ResolveInfo> resolves =
   2319                     AppGlobals.getPackageManager().queryIntentActivities(
   2320                             intent, r.resolvedType,
   2321                             PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
   2322 
   2323                 // Look for the original activity in the list...
   2324                 final int N = resolves != null ? resolves.size() : 0;
   2325                 for (int i=0; i<N; i++) {
   2326                     ResolveInfo rInfo = resolves.get(i);
   2327                     if (rInfo.activityInfo.packageName.equals(r.packageName)
   2328                             && rInfo.activityInfo.name.equals(r.info.name)) {
   2329                         // We found the current one...  the next matching is
   2330                         // after it.
   2331                         i++;
   2332                         if (i<N) {
   2333                             aInfo = resolves.get(i).activityInfo;
   2334                         }
   2335                         break;
   2336                     }
   2337                 }
   2338             } catch (RemoteException e) {
   2339             }
   2340 
   2341             if (aInfo == null) {
   2342                 // Nobody who is next!
   2343                 return false;
   2344             }
   2345 
   2346             intent.setComponent(new ComponentName(
   2347                     aInfo.applicationInfo.packageName, aInfo.name));
   2348             intent.setFlags(intent.getFlags()&~(
   2349                     Intent.FLAG_ACTIVITY_FORWARD_RESULT|
   2350                     Intent.FLAG_ACTIVITY_CLEAR_TOP|
   2351                     Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
   2352                     Intent.FLAG_ACTIVITY_NEW_TASK));
   2353 
   2354             // Okay now we need to start the new activity, replacing the
   2355             // currently running activity.  This is a little tricky because
   2356             // we want to start the new one as if the current one is finished,
   2357             // but not finish the current one first so that there is no flicker.
   2358             // And thus...
   2359             final boolean wasFinishing = r.finishing;
   2360             r.finishing = true;
   2361 
   2362             // Propagate reply information over to the new activity.
   2363             final ActivityRecord resultTo = r.resultTo;
   2364             final String resultWho = r.resultWho;
   2365             final int requestCode = r.requestCode;
   2366             r.resultTo = null;
   2367             if (resultTo != null) {
   2368                 resultTo.removeResultsLocked(r, resultWho, requestCode);
   2369             }
   2370 
   2371             final long origId = Binder.clearCallingIdentity();
   2372             // XXX we are not dealing with propagating grantedUriPermissions...
   2373             // those are not yet exposed to user code, so there is no need.
   2374             int res = mMainStack.startActivityLocked(r.app.thread, intent,
   2375                     r.resolvedType, null, 0, aInfo,
   2376                     resultTo != null ? resultTo.appToken : null, resultWho,
   2377                     requestCode, -1, r.launchedFromUid, false, false, null);
   2378             Binder.restoreCallingIdentity(origId);
   2379 
   2380             r.finishing = wasFinishing;
   2381             if (res != START_SUCCESS) {
   2382                 return false;
   2383             }
   2384             return true;
   2385         }
   2386     }
   2387 
   2388     public final int startActivityInPackage(int uid,
   2389             Intent intent, String resolvedType, IBinder resultTo,
   2390             String resultWho, int requestCode, boolean onlyIfNeeded) {
   2391 
   2392         // This is so super not safe, that only the system (or okay root)
   2393         // can do it.
   2394         final int callingUid = Binder.getCallingUid();
   2395         if (callingUid != 0 && callingUid != Process.myUid()) {
   2396             throw new SecurityException(
   2397                     "startActivityInPackage only available to the system");
   2398         }
   2399 
   2400         return mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
   2401                 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
   2402                 null, null, false, null, null);
   2403     }
   2404 
   2405     public final int startActivities(IApplicationThread caller,
   2406             Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
   2407         return mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo);
   2408     }
   2409 
   2410     public final int startActivitiesInPackage(int uid,
   2411             Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
   2412 
   2413         // This is so super not safe, that only the system (or okay root)
   2414         // can do it.
   2415         final int callingUid = Binder.getCallingUid();
   2416         if (callingUid != 0 && callingUid != Process.myUid()) {
   2417             throw new SecurityException(
   2418                     "startActivityInPackage only available to the system");
   2419         }
   2420 
   2421         return mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo);
   2422     }
   2423 
   2424     final void addRecentTaskLocked(TaskRecord task) {
   2425         int N = mRecentTasks.size();
   2426         // Quick case: check if the top-most recent task is the same.
   2427         if (N > 0 && mRecentTasks.get(0) == task) {
   2428             return;
   2429         }
   2430         // Remove any existing entries that are the same kind of task.
   2431         for (int i=0; i<N; i++) {
   2432             TaskRecord tr = mRecentTasks.get(i);
   2433             if ((task.affinity != null && task.affinity.equals(tr.affinity))
   2434                     || (task.intent != null && task.intent.filterEquals(tr.intent))) {
   2435                 mRecentTasks.remove(i);
   2436                 i--;
   2437                 N--;
   2438                 if (task.intent == null) {
   2439                     // If the new recent task we are adding is not fully
   2440                     // specified, then replace it with the existing recent task.
   2441                     task = tr;
   2442                 }
   2443             }
   2444         }
   2445         if (N >= MAX_RECENT_TASKS) {
   2446             mRecentTasks.remove(N-1);
   2447         }
   2448         mRecentTasks.add(0, task);
   2449     }
   2450 
   2451     public void setRequestedOrientation(IBinder token,
   2452             int requestedOrientation) {
   2453         synchronized (this) {
   2454             ActivityRecord r = mMainStack.isInStackLocked(token);
   2455             if (r == null) {
   2456                 return;
   2457             }
   2458             final long origId = Binder.clearCallingIdentity();
   2459             mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
   2460             Configuration config = mWindowManager.updateOrientationFromAppTokens(
   2461                     mConfiguration,
   2462                     r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
   2463             if (config != null) {
   2464                 r.frozenBeforeDestroy = true;
   2465                 if (!updateConfigurationLocked(config, r, false, false)) {
   2466                     mMainStack.resumeTopActivityLocked(null);
   2467                 }
   2468             }
   2469             Binder.restoreCallingIdentity(origId);
   2470         }
   2471     }
   2472 
   2473     public int getRequestedOrientation(IBinder token) {
   2474         synchronized (this) {
   2475             ActivityRecord r = mMainStack.isInStackLocked(token);
   2476             if (r == null) {
   2477                 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
   2478             }
   2479             return mWindowManager.getAppOrientation(r.appToken);
   2480         }
   2481     }
   2482 
   2483     /**
   2484      * This is the internal entry point for handling Activity.finish().
   2485      *
   2486      * @param token The Binder token referencing the Activity we want to finish.
   2487      * @param resultCode Result code, if any, from this Activity.
   2488      * @param resultData Result data (Intent), if any, from this Activity.
   2489      *
   2490      * @return Returns true if the activity successfully finished, or false if it is still running.
   2491      */
   2492     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
   2493         // Refuse possible leaked file descriptors
   2494         if (resultData != null && resultData.hasFileDescriptors() == true) {
   2495             throw new IllegalArgumentException("File descriptors passed in Intent");
   2496         }
   2497 
   2498         synchronized(this) {
   2499             if (mController != null) {
   2500                 // Find the first activity that is not finishing.
   2501                 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
   2502                 if (next != null) {
   2503                     // ask watcher if this is allowed
   2504                     boolean resumeOK = true;
   2505                     try {
   2506                         resumeOK = mController.activityResuming(next.packageName);
   2507                     } catch (RemoteException e) {
   2508                         mController = null;
   2509                     }
   2510 
   2511                     if (!resumeOK) {
   2512                         return false;
   2513                     }
   2514                 }
   2515             }
   2516             final long origId = Binder.clearCallingIdentity();
   2517             boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
   2518                     resultData, "app-request");
   2519             Binder.restoreCallingIdentity(origId);
   2520             return res;
   2521         }
   2522     }
   2523 
   2524     public final void finishHeavyWeightApp() {
   2525         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
   2526                 != PackageManager.PERMISSION_GRANTED) {
   2527             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
   2528                     + Binder.getCallingPid()
   2529                     + ", uid=" + Binder.getCallingUid()
   2530                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
   2531             Slog.w(TAG, msg);
   2532             throw new SecurityException(msg);
   2533         }
   2534 
   2535         synchronized(this) {
   2536             if (mHeavyWeightProcess == null) {
   2537                 return;
   2538             }
   2539 
   2540             ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
   2541                     mHeavyWeightProcess.activities);
   2542             for (int i=0; i<activities.size(); i++) {
   2543                 ActivityRecord r = activities.get(i);
   2544                 if (!r.finishing) {
   2545                     int index = mMainStack.indexOfTokenLocked(r.appToken);
   2546                     if (index >= 0) {
   2547                         mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
   2548                                 null, "finish-heavy");
   2549                     }
   2550                 }
   2551             }
   2552 
   2553             mHeavyWeightProcess = null;
   2554             mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
   2555         }
   2556     }
   2557 
   2558     public void crashApplication(int uid, int initialPid, String packageName,
   2559             String message) {
   2560         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
   2561                 != PackageManager.PERMISSION_GRANTED) {
   2562             String msg = "Permission Denial: crashApplication() from pid="
   2563                     + Binder.getCallingPid()
   2564                     + ", uid=" + Binder.getCallingUid()
   2565                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
   2566             Slog.w(TAG, msg);
   2567             throw new SecurityException(msg);
   2568         }
   2569 
   2570         synchronized(this) {
   2571             ProcessRecord proc = null;
   2572 
   2573             // Figure out which process to kill.  We don't trust that initialPid
   2574             // still has any relation to current pids, so must scan through the
   2575             // list.
   2576             synchronized (mPidsSelfLocked) {
   2577                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
   2578                     ProcessRecord p = mPidsSelfLocked.valueAt(i);
   2579                     if (p.info.uid != uid) {
   2580                         continue;
   2581                     }
   2582                     if (p.pid == initialPid) {
   2583                         proc = p;
   2584                         break;
   2585                     }
   2586                     for (String str : p.pkgList) {
   2587                         if (str.equals(packageName)) {
   2588                             proc = p;
   2589                         }
   2590                     }
   2591                 }
   2592             }
   2593 
   2594             if (proc == null) {
   2595                 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
   2596                         + " initialPid=" + initialPid
   2597                         + " packageName=" + packageName);
   2598                 return;
   2599             }
   2600 
   2601             if (proc.thread != null) {
   2602                 if (proc.pid == Process.myPid()) {
   2603                     Log.w(TAG, "crashApplication: trying to crash self!");
   2604                     return;
   2605                 }
   2606                 long ident = Binder.clearCallingIdentity();
   2607                 try {
   2608                     proc.thread.scheduleCrash(message);
   2609                 } catch (RemoteException e) {
   2610                 }
   2611                 Binder.restoreCallingIdentity(ident);
   2612             }
   2613         }
   2614     }
   2615 
   2616     public final void finishSubActivity(IBinder token, String resultWho,
   2617             int requestCode) {
   2618         synchronized(this) {
   2619             ActivityRecord self = mMainStack.isInStackLocked(token);
   2620             if (self == null) {
   2621                 return;
   2622             }
   2623 
   2624             final long origId = Binder.clearCallingIdentity();
   2625 
   2626             int i;
   2627             for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
   2628                 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
   2629                 if (r.resultTo == self && r.requestCode == requestCode) {
   2630                     if ((r.resultWho == null && resultWho == null) ||
   2631                         (r.resultWho != null && r.resultWho.equals(resultWho))) {
   2632                         mMainStack.finishActivityLocked(r, i,
   2633                                 Activity.RESULT_CANCELED, null, "request-sub");
   2634                     }
   2635                 }
   2636             }
   2637 
   2638             Binder.restoreCallingIdentity(origId);
   2639         }
   2640     }
   2641 
   2642     public boolean willActivityBeVisible(IBinder token) {
   2643         synchronized(this) {
   2644             int i;
   2645             for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
   2646                 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
   2647                 if (r.appToken == token) {
   2648                     return true;
   2649                 }
   2650                 if (r.fullscreen && !r.finishing) {
   2651                     return false;
   2652                 }
   2653             }
   2654             return true;
   2655         }
   2656     }
   2657 
   2658     public void overridePendingTransition(IBinder token, String packageName,
   2659             int enterAnim, int exitAnim) {
   2660         synchronized(this) {
   2661             ActivityRecord self = mMainStack.isInStackLocked(token);
   2662             if (self == null) {
   2663                 return;
   2664             }
   2665 
   2666             final long origId = Binder.clearCallingIdentity();
   2667 
   2668             if (self.state == ActivityState.RESUMED
   2669                     || self.state == ActivityState.PAUSING) {
   2670                 mWindowManager.overridePendingAppTransition(packageName,
   2671                         enterAnim, exitAnim);
   2672             }
   2673 
   2674             Binder.restoreCallingIdentity(origId);
   2675         }
   2676     }
   2677 
   2678     /**
   2679      * Main function for removing an existing process from the activity manager
   2680      * as a result of that process going away.  Clears out all connections
   2681      * to the process.
   2682      */
   2683     private final void handleAppDiedLocked(ProcessRecord app,
   2684             boolean restarting, boolean allowRestart) {
   2685         cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
   2686         if (!restarting) {
   2687             mLruProcesses.remove(app);
   2688         }
   2689 
   2690         if (mProfileProc == app) {
   2691             clearProfilerLocked();
   2692         }
   2693 
   2694         // Just in case...
   2695         if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
   2696             if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
   2697             mMainStack.mPausingActivity = null;
   2698         }
   2699         if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
   2700             mMainStack.mLastPausedActivity = null;
   2701         }
   2702 
   2703         // Remove this application's activities from active lists.
   2704         mMainStack.removeHistoryRecordsForAppLocked(app);
   2705 
   2706         boolean atTop = true;
   2707         boolean hasVisibleActivities = false;
   2708 
   2709         // Clean out the history list.
   2710         int i = mMainStack.mHistory.size();
   2711         if (localLOGV) Slog.v(
   2712             TAG, "Removing app " + app + " from history with " + i + " entries");
   2713         while (i > 0) {
   2714             i--;
   2715             ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
   2716             if (localLOGV) Slog.v(
   2717                 TAG, "Record #" + i + " " + r + ": app=" + r.app);
   2718             if (r.app == app) {
   2719                 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
   2720                     if (ActivityStack.DEBUG_ADD_REMOVE) {
   2721                         RuntimeException here = new RuntimeException("here");
   2722                         here.fillInStackTrace();
   2723                         Slog.i(TAG, "Removing activity " + r + " from stack at " + i
   2724                                 + ": haveState=" + r.haveState
   2725                                 + " stateNotNeeded=" + r.stateNotNeeded
   2726                                 + " finishing=" + r.finishing
   2727                                 + " state=" + r.state, here);
   2728                     }
   2729                     if (!r.finishing) {
   2730                         Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
   2731                         EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
   2732                                 System.identityHashCode(r),
   2733                                 r.task.taskId, r.shortComponentName,
   2734                                 "proc died without state saved");
   2735                     }
   2736                     mMainStack.removeActivityFromHistoryLocked(r);
   2737 
   2738                 } else {
   2739                     // We have the current state for this activity, so
   2740                     // it can be restarted later when needed.
   2741                     if (localLOGV) Slog.v(
   2742                         TAG, "Keeping entry, setting app to null");
   2743                     if (r.visible) {
   2744                         hasVisibleActivities = true;
   2745                     }
   2746                     r.app = null;
   2747                     r.nowVisible = false;
   2748                     if (!r.haveState) {
   2749                         if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
   2750                                 "App died, clearing saved state of " + r);
   2751                         r.icicle = null;
   2752                     }
   2753                 }
   2754 
   2755                 r.stack.cleanUpActivityLocked(r, true, true);
   2756             }
   2757             atTop = false;
   2758         }
   2759 
   2760         app.activities.clear();
   2761 
   2762         if (app.instrumentationClass != null) {
   2763             Slog.w(TAG, "Crash of app " + app.processName
   2764                   + " running instrumentation " + app.instrumentationClass);
   2765             Bundle info = new Bundle();
   2766             info.putString("shortMsg", "Process crashed.");
   2767             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
   2768         }
   2769 
   2770         if (!restarting) {
   2771             if (!mMainStack.resumeTopActivityLocked(null)) {
   2772                 // If there was nothing to resume, and we are not already
   2773                 // restarting this process, but there is a visible activity that
   2774                 // is hosted by the process...  then make sure all visible
   2775                 // activities are running, taking care of restarting this
   2776                 // process.
   2777                 if (hasVisibleActivities) {
   2778                     mMainStack.ensureActivitiesVisibleLocked(null, 0);
   2779                 }
   2780             }
   2781         }
   2782     }
   2783 
   2784     private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
   2785         IBinder threadBinder = thread.asBinder();
   2786 
   2787         // Find the application record.
   2788         for (int i=mLruProcesses.size()-1; i>=0; i--) {
   2789             ProcessRecord rec = mLruProcesses.get(i);
   2790             if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
   2791                 return i;
   2792             }
   2793         }
   2794         return -1;
   2795     }
   2796 
   2797     final ProcessRecord getRecordForAppLocked(
   2798             IApplicationThread thread) {
   2799         if (thread == null) {
   2800             return null;
   2801         }
   2802 
   2803         int appIndex = getLRURecordIndexForAppLocked(thread);
   2804         return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
   2805     }
   2806 
   2807     final void appDiedLocked(ProcessRecord app, int pid,
   2808             IApplicationThread thread) {
   2809 
   2810         mProcDeaths[0]++;
   2811 
   2812         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
   2813         synchronized (stats) {
   2814             stats.noteProcessDiedLocked(app.info.uid, pid);
   2815         }
   2816 
   2817         // Clean up already done if the process has been re-started.
   2818         if (app.pid == pid && app.thread != null &&
   2819                 app.thread.asBinder() == thread.asBinder()) {
   2820             if (!app.killedBackground) {
   2821                 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
   2822                         + ") has died.");
   2823             }
   2824             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
   2825             if (localLOGV) Slog.v(
   2826                 TAG, "Dying app: " + app + ", pid: " + pid
   2827                 + ", thread: " + thread.asBinder());
   2828             boolean doLowMem = app.instrumentationClass == null;
   2829             handleAppDiedLocked(app, false, true);
   2830 
   2831             if (doLowMem) {
   2832                 // If there are no longer any background processes running,
   2833                 // and the app that died was not running instrumentation,
   2834                 // then tell everyone we are now low on memory.
   2835                 boolean haveBg = false;
   2836                 for (int i=mLruProcesses.size()-1; i>=0; i--) {
   2837                     ProcessRecord rec = mLruProcesses.get(i);
   2838                     if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
   2839                         haveBg = true;
   2840                         break;
   2841                     }
   2842                 }
   2843 
   2844                 if (!haveBg) {
   2845                     EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
   2846                     long now = SystemClock.uptimeMillis();
   2847                     for (int i=mLruProcesses.size()-1; i>=0; i--) {
   2848                         ProcessRecord rec = mLruProcesses.get(i);
   2849                         if (rec != app && rec.thread != null &&
   2850                                 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
   2851                             // The low memory report is overriding any current
   2852                             // state for a GC request.  Make sure to do
   2853                             // heavy/important/visible/foreground processes first.
   2854                             if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
   2855                                 rec.lastRequestedGc = 0;
   2856                             } else {
   2857                                 rec.lastRequestedGc = rec.lastLowMemory;
   2858                             }
   2859                             rec.reportLowMemory = true;
   2860                             rec.lastLowMemory = now;
   2861                             mProcessesToGc.remove(rec);
   2862                             addProcessToGcListLocked(rec);
   2863                         }
   2864                     }
   2865                     mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
   2866                     scheduleAppGcsLocked();
   2867                 }
   2868             }
   2869         } else if (app.pid != pid) {
   2870             // A new process has already been started.
   2871             Slog.i(TAG, "Process " + app.processName + " (pid " + pid
   2872                     + ") has died and restarted (pid " + app.pid + ").");
   2873             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
   2874         } else if (DEBUG_PROCESSES) {
   2875             Slog.d(TAG, "Received spurious death notification for thread "
   2876                     + thread.asBinder());
   2877         }
   2878     }
   2879 
   2880     /**
   2881      * If a stack trace dump file is configured, dump process stack traces.
   2882      * @param clearTraces causes the dump file to be erased prior to the new
   2883      *    traces being written, if true; when false, the new traces will be
   2884      *    appended to any existing file content.
   2885      * @param firstPids of dalvik VM processes to dump stack traces for first
   2886      * @param lastPids of dalvik VM processes to dump stack traces for last
   2887      * @return file containing stack traces, or null if no dump file is configured
   2888      */
   2889     public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
   2890             ProcessStats processStats, SparseArray<Boolean> lastPids) {
   2891         String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
   2892         if (tracesPath == null || tracesPath.length() == 0) {
   2893             return null;
   2894         }
   2895 
   2896         File tracesFile = new File(tracesPath);
   2897         try {
   2898             File tracesDir = tracesFile.getParentFile();
   2899             if (!tracesDir.exists()) tracesFile.mkdirs();
   2900             FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
   2901 
   2902             if (clearTraces && tracesFile.exists()) tracesFile.delete();
   2903             tracesFile.createNewFile();
   2904             FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
   2905         } catch (IOException e) {
   2906             Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
   2907             return null;
   2908         }
   2909 
   2910         dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
   2911         return tracesFile;
   2912     }
   2913 
   2914     private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
   2915             ProcessStats processStats, SparseArray<Boolean> lastPids) {
   2916         // Use a FileObserver to detect when traces finish writing.
   2917         // The order of traces is considered important to maintain for legibility.
   2918         FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
   2919             public synchronized void onEvent(int event, String path) { notify(); }
   2920         };
   2921 
   2922         try {
   2923             observer.startWatching();
   2924 
   2925             // First collect all of the stacks of the most important pids.
   2926             if (firstPids != null) {
   2927                 try {
   2928                     int num = firstPids.size();
   2929                     for (int i = 0; i < num; i++) {
   2930                         synchronized (observer) {
   2931                             Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
   2932                             observer.wait(200);  // Wait for write-close, give up after 200msec
   2933                         }
   2934                     }
   2935                 } catch (InterruptedException e) {
   2936                     Log.wtf(TAG, e);
   2937                 }
   2938             }
   2939 
   2940             // Next measure CPU usage.
   2941             if (processStats != null) {
   2942                 processStats.init();
   2943                 System.gc();
   2944                 processStats.update();
   2945                 try {
   2946                     synchronized (processStats) {
   2947                         processStats.wait(500); // measure over 1/2 second.
   2948                     }
   2949                 } catch (InterruptedException e) {
   2950                 }
   2951                 processStats.update();
   2952 
   2953                 // We'll take the stack crawls of just the top apps using CPU.
   2954                 final int N = processStats.countWorkingStats();
   2955                 int numProcs = 0;
   2956                 for (int i=0; i<N && numProcs<5; i++) {
   2957                     ProcessStats.Stats stats = processStats.getWorkingStats(i);
   2958                     if (lastPids.indexOfKey(stats.pid) >= 0) {
   2959                         numProcs++;
   2960                         try {
   2961                             synchronized (observer) {
   2962                                 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
   2963                                 observer.wait(200);  // Wait for write-close, give up after 200msec
   2964                             }
   2965                         } catch (InterruptedException e) {
   2966                             Log.wtf(TAG, e);
   2967                         }
   2968 
   2969                     }
   2970                 }
   2971             }
   2972 
   2973         } finally {
   2974             observer.stopWatching();
   2975         }
   2976     }
   2977 
   2978     private final class AppNotResponding implements Runnable {
   2979         private final ProcessRecord mApp;
   2980         private final String mAnnotation;
   2981 
   2982         public AppNotResponding(ProcessRecord app, String annotation) {
   2983             mApp = app;
   2984             mAnnotation = annotation;
   2985         }
   2986 
   2987         @Override
   2988         public void run() {
   2989             appNotResponding(mApp, null, null, mAnnotation);
   2990         }
   2991     }
   2992 
   2993     final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
   2994         if (IS_USER_BUILD) {
   2995             return;
   2996         }
   2997         String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
   2998         if (tracesPath == null || tracesPath.length() == 0) {
   2999             return;
   3000         }
   3001 
   3002         StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
   3003         StrictMode.allowThreadDiskWrites();
   3004         try {
   3005             final File tracesFile = new File(tracesPath);
   3006             final File tracesDir = tracesFile.getParentFile();
   3007             final File tracesTmp = new File(tracesDir, "__tmp__");
   3008             try {
   3009                 if (!tracesDir.exists()) tracesFile.mkdirs();
   3010                 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
   3011 
   3012                 if (tracesFile.exists()) {
   3013                     tracesTmp.delete();
   3014                     tracesFile.renameTo(tracesTmp);
   3015                 }
   3016                 StringBuilder sb = new StringBuilder();
   3017                 Time tobj = new Time();
   3018                 tobj.set(System.currentTimeMillis());
   3019                 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
   3020                 sb.append(": ");
   3021                 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
   3022                 sb.append(" since ");
   3023                 sb.append(msg);
   3024                 FileOutputStream fos = new FileOutputStream(tracesFile);
   3025                 fos.write(sb.toString().getBytes());
   3026                 if (app == null) {
   3027                     fos.write("\n*** No application process!".getBytes());
   3028                 }
   3029                 fos.close();
   3030                 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
   3031             } catch (IOException e) {
   3032                 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
   3033                 return;
   3034             }
   3035 
   3036             if (app != null) {
   3037                 ArrayList<Integer> firstPids = new ArrayList<Integer>();
   3038                 firstPids.add(app.pid);
   3039                 dumpStackTraces(tracesPath, firstPids, null, null);
   3040             }
   3041 
   3042             File lastTracesFile = null;
   3043             File curTracesFile = null;
   3044             for (int i=9; i>=0; i--) {
   3045                 String name = String.format("slow%02d.txt", i);
   3046                 curTracesFile = new File(tracesDir, name);
   3047                 if (curTracesFile.exists()) {
   3048                     if (lastTracesFile != null) {
   3049                         curTracesFile.renameTo(lastTracesFile);
   3050                     } else {
   3051                         curTracesFile.delete();
   3052                     }
   3053                 }
   3054                 lastTracesFile = curTracesFile;
   3055             }
   3056             tracesFile.renameTo(curTracesFile);
   3057             if (tracesTmp.exists()) {
   3058                 tracesTmp.renameTo(tracesFile);
   3059             }
   3060         } finally {
   3061             StrictMode.setThreadPolicy(oldPolicy);
   3062         }
   3063     }
   3064 
   3065     final void appNotResponding(ProcessRecord app, ActivityRecord activity,
   3066             ActivityRecord parent, final String annotation) {
   3067         ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
   3068         SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
   3069 
   3070         if (mController != null) {
   3071             try {
   3072                 // 0 == continue, -1 = kill process immediately
   3073                 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
   3074                 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
   3075             } catch (RemoteException e) {
   3076                 mController = null;
   3077             }
   3078         }
   3079 
   3080         long anrTime = SystemClock.uptimeMillis();
   3081         if (MONITOR_CPU_USAGE) {
   3082             updateCpuStatsNow();
   3083         }
   3084 
   3085         synchronized (this) {
   3086             // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
   3087             if (mShuttingDown) {
   3088                 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
   3089                 return;
   3090             } else if (app.notResponding) {
   3091                 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
   3092                 return;
   3093             } else if (app.crashing) {
   3094                 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
   3095                 return;
   3096             }
   3097 
   3098             // In case we come through here for the same app before completing
   3099             // this one, mark as anring now so we will bail out.
   3100             app.notResponding = true;
   3101 
   3102             // Log the ANR to the event log.
   3103             EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
   3104                     annotation);
   3105 
   3106             // Dump thread traces as quickly as we can, starting with "interesting" processes.
   3107             firstPids.add(app.pid);
   3108 
   3109             int parentPid = app.pid;
   3110             if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
   3111             if (parentPid != app.pid) firstPids.add(parentPid);
   3112 
   3113             if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
   3114 
   3115             for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
   3116                 ProcessRecord r = mLruProcesses.get(i);
   3117                 if (r != null && r.thread != null) {
   3118                     int pid = r.pid;
   3119                     if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
   3120                         if (r.persistent) {
   3121                             firstPids.add(pid);
   3122                         } else {
   3123                             lastPids.put(pid, Boolean.TRUE);
   3124                         }
   3125                     }
   3126                 }
   3127             }
   3128         }
   3129 
   3130         // Log the ANR to the main log.
   3131         StringBuilder info = mStringBuilder;
   3132         info.setLength(0);
   3133         info.append("ANR in ").append(app.processName);
   3134         if (activity != null && activity.shortComponentName != null) {
   3135             info.append(" (").append(activity.shortComponentName).append(")");
   3136         }
   3137         info.append("\n");
   3138         if (annotation != null) {
   3139             info.append("Reason: ").append(annotation).append("\n");
   3140         }
   3141         if (parent != null && parent != activity) {
   3142             info.append("Parent: ").append(parent.shortComponentName).append("\n");
   3143         }
   3144 
   3145         final ProcessStats processStats = new ProcessStats(true);
   3146 
   3147         File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
   3148 
   3149         String cpuInfo = null;
   3150         if (MONITOR_CPU_USAGE) {
   3151             updateCpuStatsNow();
   3152             synchronized (mProcessStatsThread) {
   3153                 cpuInfo = mProcessStats.printCurrentState(anrTime);
   3154             }
   3155             info.append(processStats.printCurrentLoad());
   3156             info.append(cpuInfo);
   3157         }
   3158 
   3159         info.append(processStats.printCurrentState(anrTime));
   3160 
   3161         Slog.e(TAG, info.toString());
   3162         if (tracesFile == null) {
   3163             // There is no trace file, so dump (only) the alleged culprit's threads to the log
   3164             Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
   3165         }
   3166 
   3167         addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
   3168                 cpuInfo, tracesFile, null);
   3169 
   3170         if (mController != null) {
   3171             try {
   3172                 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
   3173                 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
   3174                 if (res != 0) {
   3175                     if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
   3176                     return;
   3177                 }
   3178             } catch (RemoteException e) {
   3179                 mController = null;
   3180             }
   3181         }
   3182 
   3183         // Unless configured otherwise, swallow ANRs in background processes & kill the process.
   3184         boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
   3185                 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
   3186 
   3187         synchronized (this) {
   3188             if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
   3189                 Slog.w(TAG, "Killing " + app + ": background ANR");
   3190                 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
   3191                         app.processName, app.setAdj, "background ANR");
   3192                 Process.killProcessQuiet(app.pid);
   3193                 return;
   3194             }
   3195 
   3196             // Set the app's notResponding state, and look up the errorReportReceiver
   3197             makeAppNotRespondingLocked(app,
   3198                     activity != null ? activity.shortComponentName : null,
   3199                     annotation != null ? "ANR " + annotation : "ANR",
   3200                     info.toString());
   3201 
   3202             // Bring up the infamous App Not Responding dialog
   3203             Message msg = Message.obtain();
   3204             HashMap map = new HashMap();
   3205             msg.what = SHOW_NOT_RESPONDING_MSG;
   3206             msg.obj = map;
   3207             map.put("app", app);
   3208             if (activity != null) {
   3209                 map.put("activity", activity);
   3210             }
   3211 
   3212             mHandler.sendMessage(msg);
   3213         }
   3214     }
   3215 
   3216     final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
   3217         if (!mLaunchWarningShown) {
   3218             mLaunchWarningShown = true;
   3219             mHandler.post(new Runnable() {
   3220                 @Override
   3221                 public void run() {
   3222                     synchronized (ActivityManagerService.this) {
   3223                         final Dialog d = new LaunchWarningWindow(mContext, cur, next);
   3224                         d.show();
   3225                         mHandler.postDelayed(new Runnable() {
   3226                             @Override
   3227                             public void run() {
   3228                                 synchronized (ActivityManagerService.this) {
   3229                                     d.dismiss();
   3230                                     mLaunchWarningShown = false;
   3231                                 }
   3232                             }
   3233                         }, 4000);
   3234                     }
   3235                 }
   3236             });
   3237         }
   3238     }
   3239 
   3240     public boolean clearApplicationUserData(final String packageName,
   3241             final IPackageDataObserver observer) {
   3242         int uid = Binder.getCallingUid();
   3243         int pid = Binder.getCallingPid();
   3244         long callingId = Binder.clearCallingIdentity();
   3245         try {
   3246             IPackageManager pm = AppGlobals.getPackageManager();
   3247             int pkgUid = -1;
   3248             synchronized(this) {
   3249                 try {
   3250                     pkgUid = pm.getPackageUid(packageName);
   3251                 } catch (RemoteException e) {
   3252                 }
   3253                 if (pkgUid == -1) {
   3254                     Slog.w(TAG, "Invalid packageName:" + packageName);
   3255                     return false;
   3256                 }
   3257                 if (uid == pkgUid || checkComponentPermission(
   3258                         android.Manifest.permission.CLEAR_APP_USER_DATA,
   3259                         pid, uid, -1, true)
   3260                         == PackageManager.PERMISSION_GRANTED) {
   3261                     forceStopPackageLocked(packageName, pkgUid);
   3262                 } else {
   3263                     throw new SecurityException(pid+" does not have permission:"+
   3264                             android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
   3265                                     "for process:"+packageName);
   3266                 }
   3267             }
   3268 
   3269             try {
   3270                 //clear application user data
   3271                 pm.clearApplicationUserData(packageName, observer);
   3272                 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
   3273                         Uri.fromParts("package", packageName, null));
   3274                 intent.putExtra(Intent.EXTRA_UID, pkgUid);
   3275                 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
   3276                         null, null, 0, null, null, null, false, false);
   3277             } catch (RemoteException e) {
   3278             }
   3279         } finally {
   3280