blob: 55c2e2abdd7135f32bfc1aeee2d14329b130521b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080024import com.android.server.AppOpsService;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070025import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import com.android.server.IntentResolver;
27import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import com.android.server.SystemServer;
29import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070030import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborn1676c852012-09-10 14:52:30 -070031import com.android.server.pm.UserManagerService;
Craig Mautner4b71aa12012-12-27 17:20:01 -080032import com.android.server.wm.AppTransition;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080033import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034
Dianne Hackborndd71fc82009-12-16 19:24:32 -080035import dalvik.system.Zygote;
36
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.app.Activity;
38import android.app.ActivityManager;
39import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070040import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.ActivityThread;
42import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070043import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020044import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070046import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.IApplicationThread;
48import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070049import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070050import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070052import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.IThumbnailReceiver;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070054import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070056import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070057import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080059import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020060import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080061import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080062import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070063import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070065import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.ContentResolver;
67import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020068import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070069import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070070import android.content.IIntentReceiver;
71import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070072import android.content.Intent;
73import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070074import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.ActivityInfo;
76import android.content.pm.ApplicationInfo;
77import android.content.pm.ConfigurationInfo;
78import android.content.pm.IPackageDataObserver;
79import android.content.pm.IPackageManager;
80import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080081import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070083import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070084import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070085import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.content.pm.ProviderInfo;
87import android.content.pm.ResolveInfo;
88import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040089import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.content.res.Configuration;
91import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070092import android.net.Proxy;
93import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.net.Uri;
95import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080096import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080097import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070098import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080099import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -0800101import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.FileUtils;
103import android.os.Handler;
104import android.os.IBinder;
105import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700106import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700107import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.Looper;
109import android.os.Message;
110import android.os.Parcel;
111import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700113import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400115import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700117import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.os.SystemClock;
119import android.os.SystemProperties;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700120import android.os.UpdateLock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700121import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700123import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800125import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700126import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700128import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700130import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import android.view.Gravity;
132import android.view.LayoutInflater;
133import android.view.View;
134import android.view.WindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.BufferedInputStream;
137import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700138import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.DataInputStream;
140import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.File;
142import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700143import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700145import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200146import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800147import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700149import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.lang.ref.WeakReference;
151import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700152import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700153import java.util.Collections;
154import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.util.HashMap;
156import java.util.HashSet;
157import java.util.Iterator;
158import java.util.List;
159import java.util.Locale;
160import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700161import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700162import java.util.concurrent.atomic.AtomicBoolean;
163import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700165public final class ActivityManagerService extends ActivityManagerNative
166 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700167 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700169 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400171 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_SWITCH = localLOGV || false;
173 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700174 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_PAUSE = localLOGV || false;
176 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
177 static final boolean DEBUG_TRANSITION = localLOGV || false;
178 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800179 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700180 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700182 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 static final boolean DEBUG_VISBILITY = localLOGV || false;
184 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700185 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700186 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700187 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800188 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700190 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700191 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700192 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700193 static final boolean DEBUG_POWER = localLOGV || false;
194 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700195 static final boolean DEBUG_MU = localLOGV || false;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700196 static final boolean DEBUG_IMMERSIVE = localLOGV || false;
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800197 static final boolean VALIDATE_TOKENS = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 static final boolean SHOW_ACTIVITY_START_TIME = true;
199
200 // Control over CPU and battery monitoring.
201 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
202 static final boolean MONITOR_CPU_USAGE = true;
203 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
204 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
205 static final boolean MONITOR_THREAD_CPU_USAGE = false;
206
Dianne Hackborn1655be42009-05-08 14:29:01 -0700207 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700208 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700209
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800210 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700212 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // Maximum number of recent tasks that we can remember.
215 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700216
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700217 // Amount of time after a call to stopAppSwitches() during which we will
218 // prevent further untrusted switches from happening.
219 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
221 // How long we wait for a launched process to attach to the activity manager
222 // before we decide it's never going to come up for real.
223 static final int PROC_START_TIMEOUT = 10*1000;
224
Jeff Brown3f9dd282011-07-08 20:02:19 -0700225 // How long we wait for a launched process to attach to the activity manager
226 // before we decide it's never going to come up for real, when the process was
227 // started with a wrapper for instrumentation (such as Valgrind) because it
228 // could take much longer than usual.
229 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // How long to wait after going idle before forcing apps to GC.
232 static final int GC_TIMEOUT = 5*1000;
233
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700234 // The minimum amount of time between successive GC requests for a process.
235 static final int GC_MIN_INTERVAL = 60*1000;
236
Dianne Hackborn287952c2010-09-22 22:34:31 -0700237 // The rate at which we check for apps using excessive power -- 15 mins.
238 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
239
240 // The minimum sample duration we will allow before deciding we have
241 // enough data on wake locks to start killing things.
242 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
243
244 // The minimum sample duration we will allow before deciding we have
245 // enough data on CPU usage to start killing things.
246 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800249 static final int BROADCAST_FG_TIMEOUT = 10*1000;
250 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // How long we wait until we timeout on key dispatching.
253 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // How long we wait until we timeout on key dispatching during instrumentation.
256 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
257
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700258 // Amount of time we wait for observers to handle a user switch before
259 // giving up on them and unfreezing the screen.
260 static final int USER_SWITCH_TIMEOUT = 2*1000;
261
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700262 // Maximum number of users we allow to be running at a time.
263 static final int MAX_RUNNING_USERS = 3;
264
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800265 // How long to wait in getTopActivityExtras for the activity to respond with the result.
266 static final int PENDING_ACTIVITY_RESULT_TIMEOUT = 2*2000;
267
Dan Egnor42471dd2010-01-07 17:25:22 -0800268 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269
270 static final String[] EMPTY_STRING_ARRAY = new String[0];
271
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700272 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700273
274 private final boolean mHeadless;
275
Joe Onorato54a4a412011-11-02 20:50:08 -0700276 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
277 // default actuion automatically. Important for devices without direct input
278 // devices.
279 private boolean mShowDialogs = true;
280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700282 * Description of a request to start a new activity, which has been held
283 * due to app switches being disabled.
284 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700285 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700286 ActivityRecord r;
287 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700288 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700289 }
290
291 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
292 = new ArrayList<PendingActivityLaunch>();
293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800295 BroadcastQueue mFgBroadcastQueue;
296 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800297 // Convenient for easy iteration over the queues. Foreground is first
298 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800299 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800300
301 BroadcastQueue broadcastQueueForIntent(Intent intent) {
302 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
303 if (DEBUG_BACKGROUND_BROADCAST) {
304 Slog.i(TAG, "Broadcast intent " + intent + " on "
305 + (isFg ? "foreground" : "background")
306 + " queue");
307 }
308 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
309 }
310
311 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
312 for (BroadcastQueue queue : mBroadcastQueues) {
313 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
314 if (r != null) {
315 return r;
316 }
317 }
318 return null;
319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320
321 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 * Activity we have told the window manager to have key focus.
323 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700324 ActivityRecord mFocusedActivity = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800325
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * List of intents that were used to start the most recent tasks.
328 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700329 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800331 public class PendingActivityExtras extends Binder implements Runnable {
332 public final ActivityRecord activity;
333 public boolean haveResult = false;
334 public Bundle result = null;
335 public PendingActivityExtras(ActivityRecord _activity) {
336 activity = _activity;
337 }
338 @Override
339 public void run() {
340 Slog.w(TAG, "getTopActivityExtras failed: timeout retrieving from " + activity);
341 synchronized (this) {
342 haveResult = true;
343 notifyAll();
344 }
345 }
346 }
347
348 final ArrayList<PendingActivityExtras> mPendingActivityExtras
349 = new ArrayList<PendingActivityExtras>();
350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700352 * Process management.
353 */
354 final ProcessList mProcessList = new ProcessList();
355
356 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 * All of the applications we currently have running organized by name.
358 * The keys are strings of the application package name (as
359 * returned by the package manager), and the keys are ApplicationRecord
360 * objects.
361 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700362 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363
364 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800365 * The currently running isolated processes.
366 */
367 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
368
369 /**
370 * Counter for assigning isolated process uids, to avoid frequently reusing the
371 * same ones.
372 */
373 int mNextIsolatedProcessUid = 0;
374
375 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700376 * The currently running heavy-weight process, if any.
377 */
378 ProcessRecord mHeavyWeightProcess = null;
379
380 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 * The last time that various processes have crashed.
382 */
383 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
384
385 /**
386 * Set of applications that we consider to be bad, and will reject
387 * incoming broadcasts from (which the user has no control over).
388 * Processes are added to this set when they have crashed twice within
389 * a minimum amount of time; they are removed from it when they are
390 * later restarted (hopefully due to some user action). The value is the
391 * time it was added to the list.
392 */
393 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
394
395 /**
396 * All of the processes we currently have running organized by pid.
397 * The keys are the pid running the application.
398 *
399 * <p>NOTE: This object is protected by its own lock, NOT the global
400 * activity manager lock!
401 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700402 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403
404 /**
405 * All of the processes that have been forced to be foreground. The key
406 * is the pid of the caller who requested it (we hold a death
407 * link on it).
408 */
409 abstract class ForegroundToken implements IBinder.DeathRecipient {
410 int pid;
411 IBinder token;
412 }
413 final SparseArray<ForegroundToken> mForegroundProcesses
414 = new SparseArray<ForegroundToken>();
415
416 /**
417 * List of records for processes that someone had tried to start before the
418 * system was ready. We don't start them at that point, but ensure they
419 * are started by the time booting is complete.
420 */
421 final ArrayList<ProcessRecord> mProcessesOnHold
422 = new ArrayList<ProcessRecord>();
423
424 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 * List of persistent applications that are in the process
426 * of being started.
427 */
428 final ArrayList<ProcessRecord> mPersistentStartingProcesses
429 = new ArrayList<ProcessRecord>();
430
431 /**
432 * Processes that are being forcibly torn down.
433 */
434 final ArrayList<ProcessRecord> mRemovedProcesses
435 = new ArrayList<ProcessRecord>();
436
437 /**
438 * List of running applications, sorted by recent usage.
439 * The first entry in the list is the least recently used.
440 * It contains ApplicationRecord objects. This list does NOT include
441 * any persistent application records (since we never want to exit them).
442 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800443 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 = new ArrayList<ProcessRecord>();
445
446 /**
447 * List of processes that should gc as soon as things are idle.
448 */
449 final ArrayList<ProcessRecord> mProcessesToGc
450 = new ArrayList<ProcessRecord>();
451
452 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800453 * This is the process holding what we currently consider to be
454 * the "home" activity.
455 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700456 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800457
458 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700459 * This is the process holding the activity the user last visited that
460 * is in a different process from the one they are currently in.
461 */
462 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800463
464 /**
465 * The time at which the previous process was last visible.
466 */
467 long mPreviousProcessVisibleTime;
468
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700469 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700470 * Which uses have been started, so are allowed to run code.
471 */
472 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
473
474 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700475 * LRU list of history of current users. Most recently current is at the end.
476 */
477 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
478
479 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700480 * Constant array of the users that are currently started.
481 */
482 int[] mStartedUserArray = new int[] { 0 };
483
484 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700485 * Registered observers of the user switching mechanics.
486 */
487 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
488 = new RemoteCallbackList<IUserSwitchObserver>();
489
490 /**
491 * Currently active user switch.
492 */
493 Object mCurUserSwitchCallback;
494
495 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400496 * Packages that the user has asked to have run in screen size
497 * compatibility mode instead of filling the screen.
498 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700499 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400500
501 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 * Set of PendingResultRecord objects that are currently active.
503 */
504 final HashSet mPendingResultRecords = new HashSet();
505
506 /**
507 * Set of IntentSenderRecord objects that are currently active.
508 */
509 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
510 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
511
512 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800513 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700514 * already logged DropBox entries for. Guarded by itself. If
515 * something (rogue user app) forces this over
516 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
517 */
518 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
519 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
520
521 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700522 * Strict Mode background batched logging state.
523 *
524 * The string buffer is guarded by itself, and its lock is also
525 * used to determine if another batched write is already
526 * in-flight.
527 */
528 private final StringBuilder mStrictModeBuffer = new StringBuilder();
529
530 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 * Keeps track of all IIntentReceivers that have been registered for
532 * broadcasts. Hash keys are the receiver IBinder, hash value is
533 * a ReceiverList.
534 */
535 final HashMap mRegisteredReceivers = new HashMap();
536
537 /**
538 * Resolver for broadcast intents to registered receivers.
539 * Holds BroadcastFilter (subclass of IntentFilter).
540 */
541 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
542 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
543 @Override
544 protected boolean allowFilterResult(
545 BroadcastFilter filter, List<BroadcastFilter> dest) {
546 IBinder target = filter.receiverList.receiver.asBinder();
547 for (int i=dest.size()-1; i>=0; i--) {
548 if (dest.get(i).receiverList.receiver.asBinder() == target) {
549 return false;
550 }
551 }
552 return true;
553 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700554
555 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700556 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700557 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
558 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700559 return super.newResult(filter, match, userId);
560 }
561 return null;
562 }
563
564 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700565 protected BroadcastFilter[] newArray(int size) {
566 return new BroadcastFilter[size];
567 }
568
569 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700570 protected String packageForFilter(BroadcastFilter filter) {
571 return filter.packageName;
572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 };
574
575 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700576 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700578 * that action (which should usually be one). The SparseArray is keyed
579 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
580 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700582 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
583 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700585 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700588 * Backup/restore process management
589 */
590 String mBackupAppName = null;
591 BackupRecord mBackupTarget = null;
592
593 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 * List of PendingThumbnailsRecord objects of clients who are still
595 * waiting to receive all of the thumbnails for a task.
596 */
597 final ArrayList mPendingThumbnails = new ArrayList();
598
599 /**
600 * List of HistoryRecord objects that have been finished and must
601 * still report back to a pending thumbnail receiver.
602 */
603 final ArrayList mCancelledThumbnails = new ArrayList();
604
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700605 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 /**
608 * List of content providers who have clients waiting for them. The
609 * application is currently being launched and the provider will be
610 * removed from this list once it is published.
611 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700612 final ArrayList<ContentProviderRecord> mLaunchingProviders
613 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614
615 /**
616 * Global set of specific Uri permissions that have been granted.
617 */
618 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
619 = new SparseArray<HashMap<Uri, UriPermission>>();
620
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800621 CoreSettingsObserver mCoreSettingsObserver;
622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 /**
624 * Thread-local storage used to carry caller permissions over through
625 * indirect content-provider access.
626 * @see #ActivityManagerService.openContentUri()
627 */
628 private class Identity {
629 public int pid;
630 public int uid;
631
632 Identity(int _pid, int _uid) {
633 pid = _pid;
634 uid = _uid;
635 }
636 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
639
640 /**
641 * All information we have collected about the runtime performance of
642 * any user id that can impact battery performance.
643 */
644 final BatteryStatsService mBatteryStatsService;
645
646 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800647 * Information about component usage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 */
649 final UsageStatsService mUsageStatsService;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800650
651 /**
652 * Information about and control over application operations
653 */
654 final AppOpsService mAppOpsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655
656 /**
657 * Current configuration information. HistoryRecord objects are given
658 * a reference to this object to indicate which configuration they are
659 * currently running in, so this object must be kept immutable.
660 */
661 Configuration mConfiguration = new Configuration();
662
663 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800664 * Current sequencing integer of the configuration, for skipping old
665 * configurations.
666 */
667 int mConfigurationSeq = 0;
668
669 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700670 * Hardware-reported OpenGLES version.
671 */
672 final int GL_ES_VERSION;
673
674 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 * List of initialization arguments to pass to all processes when binding applications to them.
676 * For example, references to the commonly used services.
677 */
678 HashMap<String, IBinder> mAppBindArgs;
679
680 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700681 * Temporary to avoid allocations. Protected by main lock.
682 */
683 final StringBuilder mStringBuilder = new StringBuilder(256);
684
685 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 * Used to control how we initialize the service.
687 */
688 boolean mStartRunning = false;
689 ComponentName mTopComponent;
690 String mTopAction;
691 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700692 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 boolean mSystemReady = false;
694 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700695 boolean mWaitingUpdate = false;
696 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700697 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700698 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
700 Context mContext;
701
702 int mFactoryTest;
703
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700704 boolean mCheckedForSetup;
705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700707 * The time at which we will allow normal application switches again,
708 * after a call to {@link #stopAppSwitches()}.
709 */
710 long mAppSwitchesAllowedTime;
711
712 /**
713 * This is set to true after the first switch after mAppSwitchesAllowedTime
714 * is set; any switches after that will clear the time.
715 */
716 boolean mDidAppSwitch;
717
718 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700719 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700720 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700721 long mLastPowerCheckRealtime;
722
723 /**
724 * Last time (in uptime) at which we checked for power usage.
725 */
726 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700727
728 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 * Set while we are wanting to sleep, to prevent any
730 * activities from being started/resumed.
731 */
732 boolean mSleeping = false;
733
734 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700735 * State of external calls telling us if the device is asleep.
736 */
737 boolean mWentToSleep = false;
738
739 /**
740 * State of external call telling us if the lock screen is shown.
741 */
742 boolean mLockScreenShown = false;
743
744 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700745 * Set if we are shutting down the system, similar to sleeping.
746 */
747 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
749 /**
750 * Task identifier that activities are currently being started
751 * in. Incremented each time a new task is created.
752 * todo: Replace this with a TokenSpace class that generates non-repeating
753 * integers that won't wrap.
754 */
755 int mCurTask = 1;
756
757 /**
758 * Current sequence id for oom_adj computation traversal.
759 */
760 int mAdjSeq = 0;
761
762 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700763 * Current sequence id for process LRU updating.
764 */
765 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766
767 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700768 * Keep track of the non-hidden/empty process we last found, to help
769 * determine how to distribute hidden/empty processes next time.
770 */
771 int mNumNonHiddenProcs = 0;
772
773 /**
774 * Keep track of the number of hidden procs, to balance oom adj
775 * distribution between those and empty procs.
776 */
777 int mNumHiddenProcs = 0;
778
779 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700780 * Keep track of the number of service processes we last found, to
781 * determine on the next iteration which should be B services.
782 */
783 int mNumServiceProcs = 0;
784 int mNewNumServiceProcs = 0;
785
786 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 * System monitoring: number of processes that died since the last
788 * N procs were started.
789 */
790 int[] mProcDeaths = new int[20];
791
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700792 /**
793 * This is set if we had to do a delayed dexopt of an app before launching
794 * it, to increasing the ANR timeouts in that case.
795 */
796 boolean mDidDexOpt;
797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 String mDebugApp = null;
799 boolean mWaitForDebugger = false;
800 boolean mDebugTransient = false;
801 String mOrigDebugApp = null;
802 boolean mOrigWaitForDebugger = false;
803 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700804 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700805 String mProfileApp = null;
806 ProcessRecord mProfileProc = null;
807 String mProfileFile;
808 ParcelFileDescriptor mProfileFd;
809 int mProfileType = 0;
810 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800811 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700813 static class ProcessChangeItem {
814 static final int CHANGE_ACTIVITIES = 1<<0;
815 static final int CHANGE_IMPORTANCE= 1<<1;
816 int changes;
817 int uid;
818 int pid;
819 int importance;
820 boolean foregroundActivities;
821 }
822
Jeff Sharkeya4620792011-05-20 15:29:23 -0700823 final RemoteCallbackList<IProcessObserver> mProcessObservers
824 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700825 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
826
827 final ArrayList<ProcessChangeItem> mPendingProcessChanges
828 = new ArrayList<ProcessChangeItem>();
829 final ArrayList<ProcessChangeItem> mAvailProcessChanges
830 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 /**
833 * Callback of last caller to {@link #requestPss}.
834 */
835 Runnable mRequestPssCallback;
836
837 /**
838 * Remaining processes for which we are waiting results from the last
839 * call to {@link #requestPss}.
840 */
841 final ArrayList<ProcessRecord> mRequestPssList
842 = new ArrayList<ProcessRecord>();
843
844 /**
845 * Runtime statistics collection thread. This object's lock is used to
846 * protect all related state.
847 */
848 final Thread mProcessStatsThread;
849
850 /**
851 * Used to collect process stats when showing not responding dialog.
852 * Protected by mProcessStatsThread.
853 */
854 final ProcessStats mProcessStats = new ProcessStats(
855 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700856 final AtomicLong mLastCpuTime = new AtomicLong(0);
857 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 long mLastWriteTime = 0;
860
861 /**
Christopher Tate73c2aee2012-03-15 16:27:14 -0700862 * Used to retain an update lock when the foreground activity is in
863 * immersive mode.
864 */
865 final UpdateLock mUpdateLock = new UpdateLock("immersive");
866
867 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 * Set to true after the system has finished booting.
869 */
870 boolean mBooted = false;
871
Dianne Hackborn7d608422011-08-07 16:24:18 -0700872 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700873 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874
875 WindowManagerService mWindowManager;
876
877 static ActivityManagerService mSelf;
878 static ActivityThread mSystemThread;
879
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700880 private int mCurrentUserId = 0;
881 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700882 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 private final class AppDeathRecipient implements IBinder.DeathRecipient {
885 final ProcessRecord mApp;
886 final int mPid;
887 final IApplicationThread mAppThread;
888
889 AppDeathRecipient(ProcessRecord app, int pid,
890 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800891 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 TAG, "New death recipient " + this
893 + " for thread " + thread.asBinder());
894 mApp = app;
895 mPid = pid;
896 mAppThread = thread;
897 }
898
899 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800900 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 TAG, "Death received in " + this
902 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 synchronized(ActivityManagerService.this) {
904 appDiedLocked(mApp, mPid, mAppThread);
905 }
906 }
907 }
908
909 static final int SHOW_ERROR_MSG = 1;
910 static final int SHOW_NOT_RESPONDING_MSG = 2;
911 static final int SHOW_FACTORY_ERROR_MSG = 3;
912 static final int UPDATE_CONFIGURATION_MSG = 4;
913 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
914 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 static final int SERVICE_TIMEOUT_MSG = 12;
916 static final int UPDATE_TIME_ZONE = 13;
917 static final int SHOW_UID_ERROR_MSG = 14;
918 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700920 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700921 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800922 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700923 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
924 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700925 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700926 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700927 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700928 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700929 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700930 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700931 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700932 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700933 static final int REPORT_USER_SWITCH_MSG = 34;
934 static final int CONTINUE_USER_SWITCH_MSG = 35;
935 static final int USER_SWITCH_TIMEOUT_MSG = 36;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700936 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800938 static final int FIRST_ACTIVITY_STACK_MSG = 100;
939 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
940 static final int FIRST_COMPAT_MODE_MSG = 300;
941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700943 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700944 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945
946 final Handler mHandler = new Handler() {
947 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800948 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 //}
950
951 public void handleMessage(Message msg) {
952 switch (msg.what) {
953 case SHOW_ERROR_MSG: {
954 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700955 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
956 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 synchronized (ActivityManagerService.this) {
958 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700959 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800961 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700962 if (res != null) {
963 res.set(0);
964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 return;
966 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700967 if (!showBackground && UserHandle.getAppId(proc.uid)
968 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
969 && proc.pid != MY_PID) {
970 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
971 if (res != null) {
972 res.set(0);
973 }
974 return;
975 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700976 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700977 Dialog d = new AppErrorDialog(mContext,
978 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 d.show();
980 proc.crashDialog = d;
981 } else {
982 // The device is asleep, so just pretend that the user
983 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700984 if (res != null) {
985 res.set(0);
986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 }
988 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700989
990 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 } break;
992 case SHOW_NOT_RESPONDING_MSG: {
993 synchronized (ActivityManagerService.this) {
994 HashMap data = (HashMap) msg.obj;
995 ProcessRecord proc = (ProcessRecord)data.get("app");
996 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 return;
999 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001000
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001001 Intent intent = new Intent("android.intent.action.ANR");
1002 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001003 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1004 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001005 }
1006 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -08001007 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07001008 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001009
Justin Kohbc52ca22012-03-29 15:11:44 -07001010 if (mShowDialogs) {
1011 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07001012 mContext, proc, (ActivityRecord)data.get("activity"),
1013 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -07001014 d.show();
1015 proc.anrDialog = d;
1016 } else {
1017 // Just kill the app if there is no dialog to be shown.
1018 killAppAtUsersRequest(proc, null);
1019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001021
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001022 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001024 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1025 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1026 synchronized (ActivityManagerService.this) {
1027 ProcessRecord proc = (ProcessRecord) data.get("app");
1028 if (proc == null) {
1029 Slog.e(TAG, "App not found when showing strict mode dialog.");
1030 break;
1031 }
1032 if (proc.crashDialog != null) {
1033 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1034 return;
1035 }
1036 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001037 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001038 Dialog d = new StrictModeViolationDialog(mContext,
1039 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001040 d.show();
1041 proc.crashDialog = d;
1042 } else {
1043 // The device is asleep, so just pretend that the user
1044 // saw a crash dialog and hit "force quit".
1045 res.set(0);
1046 }
1047 }
1048 ensureBootCompleted();
1049 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 case SHOW_FACTORY_ERROR_MSG: {
1051 Dialog d = new FactoryErrorDialog(
1052 mContext, msg.getData().getCharSequence("msg"));
1053 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001054 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 } break;
1056 case UPDATE_CONFIGURATION_MSG: {
1057 final ContentResolver resolver = mContext.getContentResolver();
1058 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1059 } break;
1060 case GC_BACKGROUND_PROCESSES_MSG: {
1061 synchronized (ActivityManagerService.this) {
1062 performAppGcsIfAppropriateLocked();
1063 }
1064 } break;
1065 case WAIT_FOR_DEBUGGER_MSG: {
1066 synchronized (ActivityManagerService.this) {
1067 ProcessRecord app = (ProcessRecord)msg.obj;
1068 if (msg.arg1 != 0) {
1069 if (!app.waitedForDebugger) {
1070 Dialog d = new AppWaitingForDebuggerDialog(
1071 ActivityManagerService.this,
1072 mContext, app);
1073 app.waitDialog = d;
1074 app.waitedForDebugger = true;
1075 d.show();
1076 }
1077 } else {
1078 if (app.waitDialog != null) {
1079 app.waitDialog.dismiss();
1080 app.waitDialog = null;
1081 }
1082 }
1083 }
1084 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001086 if (mDidDexOpt) {
1087 mDidDexOpt = false;
1088 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1089 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001090 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001091 return;
1092 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001093 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 } break;
1095 case UPDATE_TIME_ZONE: {
1096 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001097 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1098 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 if (r.thread != null) {
1100 try {
1101 r.thread.updateTimeZone();
1102 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001103 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
1105 }
1106 }
1107 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001108 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001109 case CLEAR_DNS_CACHE: {
1110 synchronized (ActivityManagerService.this) {
1111 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1112 ProcessRecord r = mLruProcesses.get(i);
1113 if (r.thread != null) {
1114 try {
1115 r.thread.clearDnsCache();
1116 } catch (RemoteException ex) {
1117 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1118 }
1119 }
1120 }
1121 }
1122 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001123 case UPDATE_HTTP_PROXY: {
1124 ProxyProperties proxy = (ProxyProperties)msg.obj;
1125 String host = "";
1126 String port = "";
1127 String exclList = "";
1128 if (proxy != null) {
1129 host = proxy.getHost();
1130 port = Integer.toString(proxy.getPort());
1131 exclList = proxy.getExclusionList();
1132 }
1133 synchronized (ActivityManagerService.this) {
1134 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1135 ProcessRecord r = mLruProcesses.get(i);
1136 if (r.thread != null) {
1137 try {
1138 r.thread.setHttpProxy(host, port, exclList);
1139 } catch (RemoteException ex) {
1140 Slog.w(TAG, "Failed to update http proxy for: " +
1141 r.info.processName);
1142 }
1143 }
1144 }
1145 }
1146 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001148 String title = "System UIDs Inconsistent";
1149 String text = "UIDs on the system are inconsistent, you need to wipe your"
1150 + " data partition or your device will be unstable.";
1151 Log.e(TAG, title + ": " + text);
1152 if (mShowDialogs) {
1153 // XXX This is a temporary dialog, no need to localize.
1154 AlertDialog d = new BaseErrorDialog(mContext);
1155 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1156 d.setCancelable(false);
1157 d.setTitle(title);
1158 d.setMessage(text);
1159 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1160 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1161 mUidAlert = d;
1162 d.show();
1163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 } break;
1165 case IM_FEELING_LUCKY_MSG: {
1166 if (mUidAlert != null) {
1167 mUidAlert.dismiss();
1168 mUidAlert = null;
1169 }
1170 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001172 if (mDidDexOpt) {
1173 mDidDexOpt = false;
1174 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1175 nmsg.obj = msg.obj;
1176 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1177 return;
1178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 ProcessRecord app = (ProcessRecord)msg.obj;
1180 synchronized (ActivityManagerService.this) {
1181 processStartTimedOutLocked(app);
1182 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001183 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001184 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1185 synchronized (ActivityManagerService.this) {
1186 doPendingActivityLaunchesLocked(true);
1187 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001188 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001189 case KILL_APPLICATION_MSG: {
1190 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001191 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001192 boolean restart = (msg.arg2 == 1);
1193 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001194 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1195 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001196 }
1197 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001198 case FINALIZE_PENDING_INTENT_MSG: {
1199 ((PendingIntentRecord)msg.obj).completeFinalize();
1200 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001201 case POST_HEAVY_NOTIFICATION_MSG: {
1202 INotificationManager inm = NotificationManager.getService();
1203 if (inm == null) {
1204 return;
1205 }
1206
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001207 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001208 ProcessRecord process = root.app;
1209 if (process == null) {
1210 return;
1211 }
1212
1213 try {
1214 Context context = mContext.createPackageContext(process.info.packageName, 0);
1215 String text = mContext.getString(R.string.heavy_weight_notification,
1216 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1217 Notification notification = new Notification();
1218 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1219 notification.when = 0;
1220 notification.flags = Notification.FLAG_ONGOING_EVENT;
1221 notification.tickerText = text;
1222 notification.defaults = 0; // please be quiet
1223 notification.sound = null;
1224 notification.vibrate = null;
1225 notification.setLatestEventInfo(context, text,
1226 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001227 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1228 PendingIntent.FLAG_CANCEL_CURRENT, null,
1229 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001230
1231 try {
1232 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001233 inm.enqueueNotificationWithTag("android", null,
1234 R.string.heavy_weight_notification,
1235 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001236 } catch (RuntimeException e) {
1237 Slog.w(ActivityManagerService.TAG,
1238 "Error showing notification for heavy-weight app", e);
1239 } catch (RemoteException e) {
1240 }
1241 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001242 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001243 }
1244 } break;
1245 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1246 INotificationManager inm = NotificationManager.getService();
1247 if (inm == null) {
1248 return;
1249 }
1250 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001251 inm.cancelNotificationWithTag("android", null,
1252 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001253 } catch (RuntimeException e) {
1254 Slog.w(ActivityManagerService.TAG,
1255 "Error canceling notification for service", e);
1256 } catch (RemoteException e) {
1257 }
1258 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001259 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1260 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001261 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001262 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001263 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1264 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001265 }
1266 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001267 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1268 synchronized (ActivityManagerService.this) {
1269 ActivityRecord ar = (ActivityRecord)msg.obj;
1270 if (mCompatModeDialog != null) {
1271 if (mCompatModeDialog.mAppInfo.packageName.equals(
1272 ar.info.applicationInfo.packageName)) {
1273 return;
1274 }
1275 mCompatModeDialog.dismiss();
1276 mCompatModeDialog = null;
1277 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001278 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001279 if (mCompatModePackages.getPackageAskCompatModeLocked(
1280 ar.packageName)) {
1281 int mode = mCompatModePackages.computeCompatModeLocked(
1282 ar.info.applicationInfo);
1283 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1284 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1285 mCompatModeDialog = new CompatModeDialog(
1286 ActivityManagerService.this, mContext,
1287 ar.info.applicationInfo);
1288 mCompatModeDialog.show();
1289 }
1290 }
1291 }
1292 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001293 break;
1294 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001295 case DISPATCH_PROCESSES_CHANGED: {
1296 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001297 break;
1298 }
1299 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001300 final int pid = msg.arg1;
1301 final int uid = msg.arg2;
1302 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001303 break;
1304 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001305 case REPORT_MEM_USAGE: {
1306 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1307 if (!isDebuggable) {
1308 return;
1309 }
1310 synchronized (ActivityManagerService.this) {
1311 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001312 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1313 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001314 // avoid spamming.
1315 return;
1316 }
1317 mLastMemUsageReportTime = now;
1318 }
1319 Thread thread = new Thread() {
1320 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001321 StringBuilder dropBuilder = new StringBuilder(1024);
1322 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001323 StringWriter oomSw = new StringWriter();
1324 PrintWriter oomPw = new PrintWriter(oomSw);
1325 StringWriter catSw = new StringWriter();
1326 PrintWriter catPw = new PrintWriter(catSw);
1327 String[] emptyArgs = new String[] { };
1328 StringBuilder tag = new StringBuilder(128);
1329 StringBuilder stack = new StringBuilder(128);
1330 tag.append("Low on memory -- ");
1331 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1332 tag, stack);
1333 dropBuilder.append(stack);
1334 dropBuilder.append('\n');
1335 dropBuilder.append('\n');
1336 String oomString = oomSw.toString();
1337 dropBuilder.append(oomString);
1338 dropBuilder.append('\n');
1339 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001340 try {
1341 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1342 "procrank", });
1343 final InputStreamReader converter = new InputStreamReader(
1344 proc.getInputStream());
1345 BufferedReader in = new BufferedReader(converter);
1346 String line;
1347 while (true) {
1348 line = in.readLine();
1349 if (line == null) {
1350 break;
1351 }
1352 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001353 logBuilder.append(line);
1354 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001355 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001356 dropBuilder.append(line);
1357 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001358 }
1359 converter.close();
1360 } catch (IOException e) {
1361 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001362 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001363 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001364 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001365 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001366 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1367 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001368 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001369 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001370 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001371 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001372 addErrorToDropBox("lowmem", null, "system_server", null,
1373 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001374 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001375 synchronized (ActivityManagerService.this) {
1376 long now = SystemClock.uptimeMillis();
1377 if (mLastMemUsageReportTime < now) {
1378 mLastMemUsageReportTime = now;
1379 }
1380 }
1381 }
1382 };
1383 thread.start();
1384 break;
1385 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001386 case REPORT_USER_SWITCH_MSG: {
1387 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1388 break;
1389 }
1390 case CONTINUE_USER_SWITCH_MSG: {
1391 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1392 break;
1393 }
1394 case USER_SWITCH_TIMEOUT_MSG: {
1395 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1396 break;
1397 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001398 case IMMERSIVE_MODE_LOCK_MSG: {
1399 final boolean nextState = (msg.arg1 != 0);
1400 if (mUpdateLock.isHeld() != nextState) {
1401 if (DEBUG_IMMERSIVE) {
1402 final ActivityRecord r = (ActivityRecord) msg.obj;
1403 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1404 }
1405 if (nextState) {
1406 mUpdateLock.acquire();
1407 } else {
1408 mUpdateLock.release();
1409 }
1410 }
1411 break;
1412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
1414 }
1415 };
1416
1417 public static void setSystemProcess() {
1418 try {
1419 ActivityManagerService m = mSelf;
1420
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001421 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001423 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001424 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 if (MONITOR_CPU_USAGE) {
1426 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 ServiceManager.addService("permission", new PermissionController(m));
1429
1430 ApplicationInfo info =
1431 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001432 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001433 mSystemThread.installSystemApplicationInfo(info);
1434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 synchronized (mSelf) {
1436 ProcessRecord app = mSelf.newProcessRecordLocked(
1437 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001438 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001440 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001441 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001442 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 synchronized (mSelf.mPidsSelfLocked) {
1444 mSelf.mPidsSelfLocked.put(app.pid, app);
1445 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001446 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448 } catch (PackageManager.NameNotFoundException e) {
1449 throw new RuntimeException(
1450 "Unable to find android system package", e);
1451 }
1452 }
1453
1454 public void setWindowManager(WindowManagerService wm) {
1455 mWindowManager = wm;
1456 }
1457
1458 public static final Context main(int factoryTest) {
1459 AThread thr = new AThread();
1460 thr.start();
1461
1462 synchronized (thr) {
1463 while (thr.mService == null) {
1464 try {
1465 thr.wait();
1466 } catch (InterruptedException e) {
1467 }
1468 }
1469 }
1470
1471 ActivityManagerService m = thr.mService;
1472 mSelf = m;
1473 ActivityThread at = ActivityThread.systemMain();
1474 mSystemThread = at;
1475 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001476 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 m.mContext = context;
1478 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001479 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480
1481 m.mBatteryStatsService.publish(context);
1482 m.mUsageStatsService.publish(context);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001483 m.mAppOpsService.publish(context);
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 synchronized (thr) {
1486 thr.mReady = true;
1487 thr.notifyAll();
1488 }
1489
1490 m.startRunning(null, null, null, null);
1491
1492 return context;
1493 }
1494
1495 public static ActivityManagerService self() {
1496 return mSelf;
1497 }
1498
1499 static class AThread extends Thread {
1500 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001501 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 boolean mReady = false;
1503
1504 public AThread() {
1505 super("ActivityManager");
1506 }
1507
1508 public void run() {
1509 Looper.prepare();
1510
1511 android.os.Process.setThreadPriority(
1512 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001513 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514
1515 ActivityManagerService m = new ActivityManagerService();
1516
1517 synchronized (this) {
1518 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001519 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 notifyAll();
1521 }
1522
1523 synchronized (this) {
1524 while (!mReady) {
1525 try {
1526 wait();
1527 } catch (InterruptedException e) {
1528 }
1529 }
1530 }
1531
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001532 // For debug builds, log event loop stalls to dropbox for analysis.
1533 if (StrictMode.conditionallyEnableDebugLogging()) {
1534 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1535 }
1536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 Looper.loop();
1538 }
1539 }
1540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 static class MemBinder extends Binder {
1542 ActivityManagerService mActivityManagerService;
1543 MemBinder(ActivityManagerService activityManagerService) {
1544 mActivityManagerService = activityManagerService;
1545 }
1546
1547 @Override
1548 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001549 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1550 != PackageManager.PERMISSION_GRANTED) {
1551 pw.println("Permission Denial: can't dump meminfo from from pid="
1552 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1553 + " without permission " + android.Manifest.permission.DUMP);
1554 return;
1555 }
1556
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001557 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001558 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 }
1560 }
1561
Chet Haase9c1e23b2011-03-24 10:51:31 -07001562 static class GraphicsBinder extends Binder {
1563 ActivityManagerService mActivityManagerService;
1564 GraphicsBinder(ActivityManagerService activityManagerService) {
1565 mActivityManagerService = activityManagerService;
1566 }
1567
1568 @Override
1569 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001570 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1571 != PackageManager.PERMISSION_GRANTED) {
1572 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1573 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1574 + " without permission " + android.Manifest.permission.DUMP);
1575 return;
1576 }
1577
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001578 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001579 }
1580 }
1581
Jeff Brown6754ba22011-12-14 20:20:01 -08001582 static class DbBinder extends Binder {
1583 ActivityManagerService mActivityManagerService;
1584 DbBinder(ActivityManagerService activityManagerService) {
1585 mActivityManagerService = activityManagerService;
1586 }
1587
1588 @Override
1589 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1590 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1591 != PackageManager.PERMISSION_GRANTED) {
1592 pw.println("Permission Denial: can't dump dbinfo from from pid="
1593 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1594 + " without permission " + android.Manifest.permission.DUMP);
1595 return;
1596 }
1597
1598 mActivityManagerService.dumpDbInfo(fd, pw, args);
1599 }
1600 }
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 static class CpuBinder extends Binder {
1603 ActivityManagerService mActivityManagerService;
1604 CpuBinder(ActivityManagerService activityManagerService) {
1605 mActivityManagerService = activityManagerService;
1606 }
1607
1608 @Override
1609 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001610 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1611 != PackageManager.PERMISSION_GRANTED) {
1612 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1613 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1614 + " without permission " + android.Manifest.permission.DUMP);
1615 return;
1616 }
1617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001619 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1620 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1621 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 }
1624 }
1625
1626 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001627 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001628
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001629 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1630 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1631 mBroadcastQueues[0] = mFgBroadcastQueue;
1632 mBroadcastQueues[1] = mBgBroadcastQueue;
1633
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001634 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001635 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 File dataDir = Environment.getDataDirectory();
1638 File systemDir = new File(dataDir, "system");
1639 systemDir.mkdirs();
1640 mBatteryStatsService = new BatteryStatsService(new File(
1641 systemDir, "batterystats.bin").toString());
1642 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001643 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001644 mOnBattery = DEBUG_POWER ? true
1645 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001646 mBatteryStatsService.getActiveStatistics().setCallback(this);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001647
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001648 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001649 systemDir, "usagestats").toString());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001650 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"));
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001651 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001653 // User 0 is the first and only user that runs at boot.
1654 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001655 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001656 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001657
Jack Palevichb90d28c2009-07-22 15:35:24 -07001658 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1659 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1660
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001661 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001662 mConfiguration.setLocale(Locale.getDefault());
1663
Dianne Hackborn813075a62011-11-14 17:45:19 -08001664 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 mProcessStats.init();
1666
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001667 mCompatModePackages = new CompatModePackages(this, systemDir);
1668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 // Add ourself to the Watchdog monitors.
1670 Watchdog.getInstance().addMonitor(this);
1671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 mProcessStatsThread = new Thread("ProcessStats") {
1673 public void run() {
1674 while (true) {
1675 try {
1676 try {
1677 synchronized(this) {
1678 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001679 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001681 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 // + ", write delay=" + nextWriteDelay);
1683 if (nextWriteDelay < nextCpuDelay) {
1684 nextCpuDelay = nextWriteDelay;
1685 }
1686 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001687 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 this.wait(nextCpuDelay);
1689 }
1690 }
1691 } catch (InterruptedException e) {
1692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 updateCpuStatsNow();
1694 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001695 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697 }
1698 }
1699 };
1700 mProcessStatsThread.start();
1701 }
1702
1703 @Override
1704 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1705 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001706 if (code == SYSPROPS_TRANSACTION) {
1707 // We need to tell all apps about the system property change.
1708 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1709 synchronized(this) {
1710 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1711 final int NA = apps.size();
1712 for (int ia=0; ia<NA; ia++) {
1713 ProcessRecord app = apps.valueAt(ia);
1714 if (app.thread != null) {
1715 procs.add(app.thread.asBinder());
1716 }
1717 }
1718 }
1719 }
1720
1721 int N = procs.size();
1722 for (int i=0; i<N; i++) {
1723 Parcel data2 = Parcel.obtain();
1724 try {
1725 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1726 } catch (RemoteException e) {
1727 }
1728 data2.recycle();
1729 }
1730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 try {
1732 return super.onTransact(code, data, reply, flags);
1733 } catch (RuntimeException e) {
1734 // The activity manager only throws security exceptions, so let's
1735 // log all others.
1736 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001737 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739 throw e;
1740 }
1741 }
1742
1743 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001744 final long now = SystemClock.uptimeMillis();
1745 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1746 return;
1747 }
1748 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1749 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 mProcessStatsThread.notify();
1751 }
1752 }
1753 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 void updateCpuStatsNow() {
1756 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001757 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 final long now = SystemClock.uptimeMillis();
1759 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001762 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1763 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 haveNewCpuStats = true;
1765 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001766 //Slog.i(TAG, mProcessStats.printCurrentState());
1767 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 // + mProcessStats.getTotalCpuPercent() + "%");
1769
Joe Onorato8a9b2202010-02-26 18:56:32 -08001770 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 if ("true".equals(SystemProperties.get("events.cpu"))) {
1772 int user = mProcessStats.getLastUserTime();
1773 int system = mProcessStats.getLastSystemTime();
1774 int iowait = mProcessStats.getLastIoWaitTime();
1775 int irq = mProcessStats.getLastIrqTime();
1776 int softIrq = mProcessStats.getLastSoftIrqTime();
1777 int idle = mProcessStats.getLastIdleTime();
1778
1779 int total = user + system + iowait + irq + softIrq + idle;
1780 if (total == 0) total = 1;
1781
Doug Zongker2bec3d42009-12-04 12:52:44 -08001782 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 ((user+system+iowait+irq+softIrq) * 100) / total,
1784 (user * 100) / total,
1785 (system * 100) / total,
1786 (iowait * 100) / total,
1787 (irq * 100) / total,
1788 (softIrq * 100) / total);
1789 }
1790 }
1791
Amith Yamasanie43530a2009-08-21 13:11:37 -07001792 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001793 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001794 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 synchronized(mPidsSelfLocked) {
1796 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001797 if (mOnBattery) {
1798 int perc = bstats.startAddingCpuLocked();
1799 int totalUTime = 0;
1800 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001801 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001803 ProcessStats.Stats st = mProcessStats.getStats(i);
1804 if (!st.working) {
1805 continue;
1806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001808 int otherUTime = (st.rel_utime*perc)/100;
1809 int otherSTime = (st.rel_stime*perc)/100;
1810 totalUTime += otherUTime;
1811 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 if (pr != null) {
1813 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001814 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1815 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001816 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001817 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001818 } else {
1819 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001820 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001821 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001822 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1823 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001824 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001828 bstats.finishAddingCpuLocked(perc, totalUTime,
1829 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831 }
1832 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1835 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001836 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 }
1838 }
1839 }
1840 }
1841
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001842 @Override
1843 public void batteryNeedsCpuUpdate() {
1844 updateCpuStatsNow();
1845 }
1846
1847 @Override
1848 public void batteryPowerChanged(boolean onBattery) {
1849 // When plugging in, update the CPU stats first before changing
1850 // the plug state.
1851 updateCpuStatsNow();
1852 synchronized (this) {
1853 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001854 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001855 }
1856 }
1857 }
1858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 /**
1860 * Initialize the application bind args. These are passed to each
1861 * process when the bindApplication() IPC is sent to the process. They're
1862 * lazily setup to make sure the services are running when they're asked for.
1863 */
1864 private HashMap<String, IBinder> getCommonServicesLocked() {
1865 if (mAppBindArgs == null) {
1866 mAppBindArgs = new HashMap<String, IBinder>();
1867
1868 // Setup the application init args
1869 mAppBindArgs.put("package", ServiceManager.getService("package"));
1870 mAppBindArgs.put("window", ServiceManager.getService("window"));
1871 mAppBindArgs.put(Context.ALARM_SERVICE,
1872 ServiceManager.getService(Context.ALARM_SERVICE));
1873 }
1874 return mAppBindArgs;
1875 }
1876
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001877 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 if (mFocusedActivity != r) {
1879 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001880 if (r != null) {
1881 mWindowManager.setFocusedApp(r.appToken, true);
1882 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001883 applyUpdateLockStateLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885 }
1886
Christopher Tate73c2aee2012-03-15 16:27:14 -07001887 final void applyUpdateLockStateLocked(ActivityRecord r) {
1888 // Modifications to the UpdateLock state are done on our handler, outside
1889 // the activity manager's locks. The new state is determined based on the
1890 // state *now* of the relevant activity record. The object is passed to
1891 // the handler solely for logging detail, not to be consulted/modified.
1892 final boolean nextState = r != null && r.immersive;
1893 mHandler.sendMessage(
1894 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
1895 }
1896
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001897 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001899 int lrui = mLruProcesses.indexOf(app);
1900 if (lrui >= 0) mLruProcesses.remove(lrui);
1901
1902 int i = mLruProcesses.size()-1;
1903 int skipTop = 0;
1904
Dianne Hackborn906497c2010-05-10 15:57:38 -07001905 app.lruSeq = mLruSeq;
1906
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001907 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001908 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001909 if (app.activities.size() > 0) {
1910 // If this process has activities, we more strongly want to keep
1911 // it around.
1912 app.lruWeight = app.lastActivityTime;
1913 } else if (app.pubProviders.size() > 0) {
1914 // If this process contains content providers, we want to keep
1915 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001916 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001917 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001918 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001919 } else {
1920 // If this process doesn't have activities, we less strongly
1921 // want to keep it around, and generally want to avoid getting
1922 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001923 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001924 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001925 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001926 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001927
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001928 while (i >= 0) {
1929 ProcessRecord p = mLruProcesses.get(i);
1930 // If this app shouldn't be in front of the first N background
1931 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001932 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001933 skipTop--;
1934 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001935 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001936 mLruProcesses.add(i+1, app);
1937 break;
1938 }
1939 i--;
1940 }
1941 if (i < 0) {
1942 mLruProcesses.add(0, app);
1943 }
1944
Dianne Hackborn906497c2010-05-10 15:57:38 -07001945 // If the app is currently using a content provider or service,
1946 // bump those processes as well.
1947 if (app.connections.size() > 0) {
1948 for (ConnectionRecord cr : app.connections) {
1949 if (cr.binding != null && cr.binding.service != null
1950 && cr.binding.service.app != null
1951 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001952 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001953 }
1954 }
1955 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001956 for (int j=app.conProviders.size()-1; j>=0; j--) {
1957 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1958 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001959 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001960 }
1961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
1963
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001964 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001965 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001966 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001967 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001968
1969 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1970 if (oomAdj) {
1971 updateOomAdjLocked();
1972 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001973 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001974
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001975 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001977 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001978 // The system gets to run in any process. If there are multiple
1979 // processes with the same uid, just pick the first (this
1980 // should never happen).
1981 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1982 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001983 if (procs == null) return null;
1984 final int N = procs.size();
1985 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001986 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 }
1989 ProcessRecord proc = mProcessNames.get(processName, uid);
1990 return proc;
1991 }
1992
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001993 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001994 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001995 try {
1996 if (pm.performDexOpt(packageName)) {
1997 mDidDexOpt = true;
1998 }
1999 } catch (RemoteException e) {
2000 }
2001 }
2002
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002003 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 int transit = mWindowManager.getPendingAppTransition();
Craig Mautner4b71aa12012-12-27 17:20:01 -08002005 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
2006 || transit == AppTransition.TRANSIT_TASK_OPEN
2007 || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002010 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002012 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2013 boolean isolated) {
2014 ProcessRecord app;
2015 if (!isolated) {
2016 app = getProcessRecordLocked(processName, info.uid);
2017 } else {
2018 // If this is an isolated process, it can't re-use an existing process.
2019 app = null;
2020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 // We don't have to do anything more if:
2022 // (1) There is an existing application record; and
2023 // (2) The caller doesn't think it is dead, OR there is no thread
2024 // object attached to it so we know it couldn't have crashed; and
2025 // (3) There is a pid assigned to it, so it is either starting or
2026 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002027 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 + " app=" + app + " knownToBeDead=" + knownToBeDead
2029 + " thread=" + (app != null ? app.thread : null)
2030 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002031 if (app != null && app.pid > 0) {
2032 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002033 // We already have the app running, or are waiting for it to
2034 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002035 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002036 // If this is a new package in the process, add the package to the list
2037 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002038 return app;
2039 } else {
2040 // An application record is attached to a previous process,
2041 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002042 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002043 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 String hostingNameStr = hostingName != null
2048 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002049
2050 if (!isolated) {
2051 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2052 // If we are in the background, then check to see if this process
2053 // is bad. If so, we will just silently fail.
2054 if (mBadProcesses.get(info.processName, info.uid) != null) {
2055 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2056 + "/" + info.processName);
2057 return null;
2058 }
2059 } else {
2060 // When the user is explicitly starting a process, then clear its
2061 // crash count so that we won't make it bad until they see at
2062 // least one crash dialog again, and make the process good again
2063 // if it had been bad.
2064 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002065 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002066 mProcessCrashTimes.remove(info.processName, info.uid);
2067 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002068 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2069 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002070 info.processName);
2071 mBadProcesses.remove(info.processName, info.uid);
2072 if (app != null) {
2073 app.bad = false;
2074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
2076 }
2077 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002080 app = newProcessRecordLocked(null, info, processName, isolated);
2081 if (app == null) {
2082 Slog.w(TAG, "Failed making new process record for "
2083 + processName + "/" + info.uid + " isolated=" + isolated);
2084 return null;
2085 }
2086 mProcessNames.put(processName, app.uid, app);
2087 if (isolated) {
2088 mIsolatedProcesses.put(app.uid, app);
2089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 } else {
2091 // If this is a new package in the process, add the package to the list
2092 app.addPackage(info.packageName);
2093 }
2094
2095 // If the system is not ready yet, then hold off on starting this
2096 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002097 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002098 && !isAllowedWhileBooting(info)
2099 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 if (!mProcessesOnHold.contains(app)) {
2101 mProcessesOnHold.add(app);
2102 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002103 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 return app;
2105 }
2106
2107 startProcessLocked(app, hostingType, hostingNameStr);
2108 return (app.pid != 0) ? app : null;
2109 }
2110
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002111 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2112 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2113 }
2114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 private final void startProcessLocked(ProcessRecord app,
2116 String hostingType, String hostingNameStr) {
2117 if (app.pid > 0 && app.pid != MY_PID) {
2118 synchronized (mPidsSelfLocked) {
2119 mPidsSelfLocked.remove(app.pid);
2120 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2121 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002122 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
2124
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002125 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2126 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 mProcessesOnHold.remove(app);
2128
2129 updateCpuStats();
2130
2131 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2132 mProcDeaths[0] = 0;
2133
2134 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002135 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002138 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002139 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002140 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002141 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002142 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002143 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002144
2145 if (Environment.isExternalStorageEmulated()) {
2146 if (pm.checkPermission(
2147 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2148 app.info.packageName) == PERMISSION_GRANTED) {
2149 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2150 } else {
2151 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2152 }
2153 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002154 } catch (PackageManager.NameNotFoundException e) {
2155 Slog.w(TAG, "Unable to retrieve gids", e);
2156 }
Kenny Roote091f222012-09-11 15:01:26 -07002157
2158 /*
2159 * Add shared application GID so applications can share some
2160 * resources like shared libraries
2161 */
2162 if (permGids == null) {
2163 gids = new int[1];
2164 } else {
2165 gids = new int[permGids.length + 1];
2166 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2167 }
2168 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
2170 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2171 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2172 && mTopComponent != null
2173 && app.processName.equals(mTopComponent.getPackageName())) {
2174 uid = 0;
2175 }
2176 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2177 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2178 uid = 0;
2179 }
2180 }
2181 int debugFlags = 0;
2182 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2183 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002184 // Also turn on CheckJNI for debuggable apps. It's quite
2185 // awkward to turn on otherwise.
2186 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002188 // Run the app in safe mode if its manifest requests so or the
2189 // system is booted in safe mode.
2190 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2191 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002192 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2195 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2196 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002197 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2198 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 if ("1".equals(SystemProperties.get("debug.assert"))) {
2201 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2202 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002203
2204 // Start the process. It will either succeed and return a result containing
2205 // the PID of the new process, or else throw a RuntimeException.
2206 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002207 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002208 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2211 synchronized (bs) {
2212 if (bs.isOnBattery()) {
2213 app.batteryStats.incStartsLocked();
2214 }
2215 }
2216
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002217 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2218 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 app.processName, hostingType,
2220 hostingNameStr != null ? hostingNameStr : "");
2221
2222 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002223 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 }
2225
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002226 StringBuilder buf = mStringBuilder;
2227 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 buf.append("Start proc ");
2229 buf.append(app.processName);
2230 buf.append(" for ");
2231 buf.append(hostingType);
2232 if (hostingNameStr != null) {
2233 buf.append(" ");
2234 buf.append(hostingNameStr);
2235 }
2236 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002237 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 buf.append(" uid=");
2239 buf.append(uid);
2240 buf.append(" gids={");
2241 if (gids != null) {
2242 for (int gi=0; gi<gids.length; gi++) {
2243 if (gi != 0) buf.append(", ");
2244 buf.append(gids[gi]);
2245
2246 }
2247 }
2248 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002249 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002250 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002251 app.usingWrapper = startResult.usingWrapper;
2252 app.removed = false;
2253 synchronized (mPidsSelfLocked) {
2254 this.mPidsSelfLocked.put(startResult.pid, app);
2255 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2256 msg.obj = app;
2257 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2258 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 }
2260 } catch (RuntimeException e) {
2261 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002262 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002263 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 }
2265 }
2266
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002267 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 if (resumed) {
2269 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2270 } else {
2271 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2272 }
2273 }
2274
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002275 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002276 if (mHeadless) {
2277 // Added because none of the other calls to ensureBootCompleted seem to fire
2278 // when running headless.
2279 ensureBootCompleted();
2280 return false;
2281 }
2282
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002283 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2284 && mTopAction == null) {
2285 // We are running in factory test mode, but unable to find
2286 // the factory test app, so just sit around displaying the
2287 // error message and don't try to start anything.
2288 return false;
2289 }
2290 Intent intent = new Intent(
2291 mTopAction,
2292 mTopData != null ? Uri.parse(mTopData) : null);
2293 intent.setComponent(mTopComponent);
2294 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2295 intent.addCategory(Intent.CATEGORY_HOME);
2296 }
2297 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002298 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002299 if (aInfo != null) {
2300 intent.setComponent(new ComponentName(
2301 aInfo.applicationInfo.packageName, aInfo.name));
2302 // Don't do this if the home app is currently being
2303 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002304 aInfo = new ActivityInfo(aInfo);
2305 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002306 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2307 aInfo.applicationInfo.uid);
2308 if (app == null || app.instrumentationClass == null) {
2309 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002310 mMainStack.startActivityLocked(null, intent, null, aInfo,
2311 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002312 }
2313 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002314
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002315 return true;
2316 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002317
Amith Yamasani259d5e52012-08-31 15:11:01 -07002318 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2319 ActivityInfo ai = null;
2320 ComponentName comp = intent.getComponent();
2321 try {
2322 if (comp != null) {
2323 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2324 } else {
2325 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2326 intent,
2327 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2328 flags, userId);
2329
2330 if (info != null) {
2331 ai = info.activityInfo;
2332 }
2333 }
2334 } catch (RemoteException e) {
2335 // ignore
2336 }
2337
2338 return ai;
2339 }
2340
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002341 /**
2342 * Starts the "new version setup screen" if appropriate.
2343 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002344 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002345 // Only do this once per boot.
2346 if (mCheckedForSetup) {
2347 return;
2348 }
2349
2350 // We will show this screen if the current one is a different
2351 // version than the last one shown, and we are not running in
2352 // low-level factory test mode.
2353 final ContentResolver resolver = mContext.getContentResolver();
2354 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002355 Settings.Global.getInt(resolver,
2356 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002357 mCheckedForSetup = true;
2358
2359 // See if we should be showing the platform update setup UI.
2360 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2361 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2362 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2363
2364 // We don't allow third party apps to replace this.
2365 ResolveInfo ri = null;
2366 for (int i=0; ris != null && i<ris.size(); i++) {
2367 if ((ris.get(i).activityInfo.applicationInfo.flags
2368 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2369 ri = ris.get(i);
2370 break;
2371 }
2372 }
2373
2374 if (ri != null) {
2375 String vers = ri.activityInfo.metaData != null
2376 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2377 : null;
2378 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2379 vers = ri.activityInfo.applicationInfo.metaData.getString(
2380 Intent.METADATA_SETUP_VERSION);
2381 }
2382 String lastVers = Settings.Secure.getString(
2383 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2384 if (vers != null && !vers.equals(lastVers)) {
2385 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2386 intent.setComponent(new ComponentName(
2387 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002388 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2389 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002390 }
2391 }
2392 }
2393 }
2394
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002395 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002396 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002397 }
2398
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002399 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002400 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002401 throw new SecurityException("Isolated process not allowed to call " + caller);
2402 }
2403 }
2404
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002405 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002406 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002407 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002408 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2409 }
2410 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002411
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002412 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002413 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2414 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002415 synchronized (this) {
2416 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2417 }
2418 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002419
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002420 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002421 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002422 synchronized (this) {
2423 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2424 }
2425 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002426
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002427 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002428 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2429 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002430 synchronized (this) {
2431 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002432 }
2433 }
2434
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002435 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002436 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002437 synchronized (this) {
2438 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2439 }
2440 }
2441
2442 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002443 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2444 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002445 synchronized (this) {
2446 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2447 }
2448 }
2449
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002450 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002451 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002452 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002455 private void dispatchProcessesChanged() {
2456 int N;
2457 synchronized (this) {
2458 N = mPendingProcessChanges.size();
2459 if (mActiveProcessChanges.length < N) {
2460 mActiveProcessChanges = new ProcessChangeItem[N];
2461 }
2462 mPendingProcessChanges.toArray(mActiveProcessChanges);
2463 mAvailProcessChanges.addAll(mPendingProcessChanges);
2464 mPendingProcessChanges.clear();
2465 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2466 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002467 int i = mProcessObservers.beginBroadcast();
2468 while (i > 0) {
2469 i--;
2470 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2471 if (observer != null) {
2472 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002473 for (int j=0; j<N; j++) {
2474 ProcessChangeItem item = mActiveProcessChanges[j];
2475 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2476 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2477 + item.pid + " uid=" + item.uid + ": "
2478 + item.foregroundActivities);
2479 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2480 item.foregroundActivities);
2481 }
2482 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2483 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2484 + item.pid + " uid=" + item.uid + ": " + item.importance);
2485 observer.onImportanceChanged(item.pid, item.uid,
2486 item.importance);
2487 }
2488 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002489 } catch (RemoteException e) {
2490 }
2491 }
2492 }
2493 mProcessObservers.finishBroadcast();
2494 }
2495
2496 private void dispatchProcessDied(int pid, int uid) {
2497 int i = mProcessObservers.beginBroadcast();
2498 while (i > 0) {
2499 i--;
2500 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2501 if (observer != null) {
2502 try {
2503 observer.onProcessDied(pid, uid);
2504 } catch (RemoteException e) {
2505 }
2506 }
2507 }
2508 mProcessObservers.finishBroadcast();
2509 }
2510
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002511 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002512 final int N = mPendingActivityLaunches.size();
2513 if (N <= 0) {
2514 return;
2515 }
2516 for (int i=0; i<N; i++) {
2517 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002519 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002520 }
2521 mPendingActivityLaunches.clear();
2522 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002523
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002524 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002525 Intent intent, String resolvedType, IBinder resultTo,
2526 String resultWho, int requestCode, int startFlags,
2527 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002528 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002529 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002530 }
2531
2532 public final int startActivityAsUser(IApplicationThread caller,
2533 Intent intent, String resolvedType, IBinder resultTo,
2534 String resultWho, int requestCode, int startFlags,
2535 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002536 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002537 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002538 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002539 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002540 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2541 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002542 }
2543
2544 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002545 Intent intent, String resolvedType, IBinder resultTo,
2546 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002547 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002548 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002549 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002550 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002551 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002552 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002553 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002554 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002555 return res;
2556 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002557
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002558 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002559 Intent intent, String resolvedType, IBinder resultTo,
2560 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002561 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002562 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002563 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002564 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002565 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002566 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002567 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002568 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002569 }
2570
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002571 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002572 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002573 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002574 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002575 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002576 // Refuse possible leaked file descriptors
2577 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2578 throw new IllegalArgumentException("File descriptors passed in Intent");
2579 }
2580
2581 IIntentSender sender = intent.getTarget();
2582 if (!(sender instanceof PendingIntentRecord)) {
2583 throw new IllegalArgumentException("Bad PendingIntent object");
2584 }
2585
2586 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002587
2588 synchronized (this) {
2589 // If this is coming from the currently resumed activity, it is
2590 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002591 if (mMainStack.mResumedActivity != null
2592 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002593 Binder.getCallingUid()) {
2594 mAppSwitchesAllowedTime = 0;
2595 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002596 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002597 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2598 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002599 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002600 }
2601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002603 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 // Refuse possible leaked file descriptors
2605 if (intent != null && intent.hasFileDescriptors() == true) {
2606 throw new IllegalArgumentException("File descriptors passed in Intent");
2607 }
2608
2609 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002610 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2611 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002612 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 return false;
2614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 if (r.app == null || r.app.thread == null) {
2616 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002617 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 return false;
2619 }
2620 intent = new Intent(intent);
2621 // The caller is not allowed to change the data.
2622 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2623 // And we are resetting to find the next component...
2624 intent.setComponent(null);
2625
2626 ActivityInfo aInfo = null;
2627 try {
2628 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002629 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002631 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002632 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633
2634 // Look for the original activity in the list...
2635 final int N = resolves != null ? resolves.size() : 0;
2636 for (int i=0; i<N; i++) {
2637 ResolveInfo rInfo = resolves.get(i);
2638 if (rInfo.activityInfo.packageName.equals(r.packageName)
2639 && rInfo.activityInfo.name.equals(r.info.name)) {
2640 // We found the current one... the next matching is
2641 // after it.
2642 i++;
2643 if (i<N) {
2644 aInfo = resolves.get(i).activityInfo;
2645 }
2646 break;
2647 }
2648 }
2649 } catch (RemoteException e) {
2650 }
2651
2652 if (aInfo == null) {
2653 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002654 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 return false;
2656 }
2657
2658 intent.setComponent(new ComponentName(
2659 aInfo.applicationInfo.packageName, aInfo.name));
2660 intent.setFlags(intent.getFlags()&~(
2661 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2662 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2663 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2664 Intent.FLAG_ACTIVITY_NEW_TASK));
2665
2666 // Okay now we need to start the new activity, replacing the
2667 // currently running activity. This is a little tricky because
2668 // we want to start the new one as if the current one is finished,
2669 // but not finish the current one first so that there is no flicker.
2670 // And thus...
2671 final boolean wasFinishing = r.finishing;
2672 r.finishing = true;
2673
2674 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002675 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 final String resultWho = r.resultWho;
2677 final int requestCode = r.requestCode;
2678 r.resultTo = null;
2679 if (resultTo != null) {
2680 resultTo.removeResultsLocked(r, resultWho, requestCode);
2681 }
2682
2683 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002684 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002685 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2686 resultWho, requestCode, -1, r.launchedFromUid, 0,
2687 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 Binder.restoreCallingIdentity(origId);
2689
2690 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002691 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 return false;
2693 }
2694 return true;
2695 }
2696 }
2697
Dianne Hackborn41203752012-08-31 14:05:51 -07002698 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002700 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2701
Dianne Hackborn139748f2012-09-24 11:36:57 -07002702 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002703 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704
Amith Yamasani742a6712011-05-04 14:49:28 -07002705 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002706 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002707 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002708 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002709 }
2710
2711 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002712 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2713 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002714 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002715 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002716 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002717 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002718 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002719 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002720 }
2721
Dianne Hackborn41203752012-08-31 14:05:51 -07002722 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002723 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002724 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002725
Dianne Hackborn139748f2012-09-24 11:36:57 -07002726 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002727 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002728 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002729 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002730 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
2732
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002733 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002735 // Quick case: check if the top-most recent task is the same.
2736 if (N > 0 && mRecentTasks.get(0) == task) {
2737 return;
2738 }
2739 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 for (int i=0; i<N; i++) {
2741 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002742 if (task.userId == tr.userId
2743 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2744 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 mRecentTasks.remove(i);
2746 i--;
2747 N--;
2748 if (task.intent == null) {
2749 // If the new recent task we are adding is not fully
2750 // specified, then replace it with the existing recent task.
2751 task = tr;
2752 }
2753 }
2754 }
2755 if (N >= MAX_RECENT_TASKS) {
2756 mRecentTasks.remove(N-1);
2757 }
2758 mRecentTasks.add(0, task);
2759 }
2760
2761 public void setRequestedOrientation(IBinder token,
2762 int requestedOrientation) {
2763 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002764 ActivityRecord r = mMainStack.isInStackLocked(token);
2765 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 return;
2767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002769 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002771 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002772 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 if (config != null) {
2774 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002775 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002776 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 }
2778 }
2779 Binder.restoreCallingIdentity(origId);
2780 }
2781 }
2782
2783 public int getRequestedOrientation(IBinder token) {
2784 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002785 ActivityRecord r = mMainStack.isInStackLocked(token);
2786 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2788 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002789 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 }
2791 }
2792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 /**
2794 * This is the internal entry point for handling Activity.finish().
2795 *
2796 * @param token The Binder token referencing the Activity we want to finish.
2797 * @param resultCode Result code, if any, from this Activity.
2798 * @param resultData Result data (Intent), if any, from this Activity.
2799 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002800 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 */
2802 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2803 // Refuse possible leaked file descriptors
2804 if (resultData != null && resultData.hasFileDescriptors() == true) {
2805 throw new IllegalArgumentException("File descriptors passed in Intent");
2806 }
2807
2808 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002809 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 if (next != null) {
2813 // ask watcher if this is allowed
2814 boolean resumeOK = true;
2815 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002816 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002818 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820
2821 if (!resumeOK) {
2822 return false;
2823 }
2824 }
2825 }
2826 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002827 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002828 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 Binder.restoreCallingIdentity(origId);
2830 return res;
2831 }
2832 }
2833
Dianne Hackborn860755f2010-06-03 18:47:52 -07002834 public final void finishHeavyWeightApp() {
2835 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2836 != PackageManager.PERMISSION_GRANTED) {
2837 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2838 + Binder.getCallingPid()
2839 + ", uid=" + Binder.getCallingUid()
2840 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2841 Slog.w(TAG, msg);
2842 throw new SecurityException(msg);
2843 }
2844
2845 synchronized(this) {
2846 if (mHeavyWeightProcess == null) {
2847 return;
2848 }
2849
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002850 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002851 mHeavyWeightProcess.activities);
2852 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002853 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002854 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002855 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002856 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002858 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002859 }
2860 }
2861 }
2862
Dianne Hackborn41203752012-08-31 14:05:51 -07002863 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2864 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002865 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002866 }
2867 }
2868
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002869 public void crashApplication(int uid, int initialPid, String packageName,
2870 String message) {
2871 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2872 != PackageManager.PERMISSION_GRANTED) {
2873 String msg = "Permission Denial: crashApplication() from pid="
2874 + Binder.getCallingPid()
2875 + ", uid=" + Binder.getCallingUid()
2876 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2877 Slog.w(TAG, msg);
2878 throw new SecurityException(msg);
2879 }
2880
2881 synchronized(this) {
2882 ProcessRecord proc = null;
2883
2884 // Figure out which process to kill. We don't trust that initialPid
2885 // still has any relation to current pids, so must scan through the
2886 // list.
2887 synchronized (mPidsSelfLocked) {
2888 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2889 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002890 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002891 continue;
2892 }
2893 if (p.pid == initialPid) {
2894 proc = p;
2895 break;
2896 }
2897 for (String str : p.pkgList) {
2898 if (str.equals(packageName)) {
2899 proc = p;
2900 }
2901 }
2902 }
2903 }
2904
2905 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002906 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002907 + " initialPid=" + initialPid
2908 + " packageName=" + packageName);
2909 return;
2910 }
2911
2912 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002913 if (proc.pid == Process.myPid()) {
2914 Log.w(TAG, "crashApplication: trying to crash self!");
2915 return;
2916 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002917 long ident = Binder.clearCallingIdentity();
2918 try {
2919 proc.thread.scheduleCrash(message);
2920 } catch (RemoteException e) {
2921 }
2922 Binder.restoreCallingIdentity(ident);
2923 }
2924 }
2925 }
2926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 public final void finishSubActivity(IBinder token, String resultWho,
2928 int requestCode) {
2929 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002931 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 Binder.restoreCallingIdentity(origId);
2933 }
2934 }
2935
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002936 public boolean finishActivityAffinity(IBinder token) {
2937 synchronized(this) {
2938 final long origId = Binder.clearCallingIdentity();
2939 boolean res = mMainStack.finishActivityAffinityLocked(token);
2940 Binder.restoreCallingIdentity(origId);
2941 return res;
2942 }
2943 }
2944
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002945 public boolean willActivityBeVisible(IBinder token) {
2946 synchronized(this) {
2947 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002948 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2949 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002950 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002951 return true;
2952 }
2953 if (r.fullscreen && !r.finishing) {
2954 return false;
2955 }
2956 }
2957 return true;
2958 }
2959 }
2960
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002961 public void overridePendingTransition(IBinder token, String packageName,
2962 int enterAnim, int exitAnim) {
2963 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002964 ActivityRecord self = mMainStack.isInStackLocked(token);
2965 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002966 return;
2967 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002968
2969 final long origId = Binder.clearCallingIdentity();
2970
2971 if (self.state == ActivityState.RESUMED
2972 || self.state == ActivityState.PAUSING) {
2973 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002974 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002975 }
2976
2977 Binder.restoreCallingIdentity(origId);
2978 }
2979 }
2980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 * Main function for removing an existing process from the activity manager
2983 * as a result of that process going away. Clears out all connections
2984 * to the process.
2985 */
2986 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002987 boolean restarting, boolean allowRestart) {
2988 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002990 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 }
2992
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002993 if (mProfileProc == app) {
2994 clearProfilerLocked();
2995 }
2996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002998 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002999 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
3000 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003001 mMainStack.mPausingActivity = null;
3002 }
3003 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
3004 mMainStack.mLastPausedActivity = null;
3005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006
3007 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003008 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009
3010 app.activities.clear();
3011
3012 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003013 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 + " running instrumentation " + app.instrumentationClass);
3015 Bundle info = new Bundle();
3016 info.putString("shortMsg", "Process crashed.");
3017 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3018 }
3019
3020 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003021 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 // If there was nothing to resume, and we are not already
3023 // restarting this process, but there is a visible activity that
3024 // is hosted by the process... then make sure all visible
3025 // activities are running, taking care of restarting this
3026 // process.
3027 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003028 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
3030 }
3031 }
3032 }
3033
3034 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3035 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003037 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3038 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3040 return i;
3041 }
3042 }
3043 return -1;
3044 }
3045
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003046 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 IApplicationThread thread) {
3048 if (thread == null) {
3049 return null;
3050 }
3051
3052 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003053 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 }
3055
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003056 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 IApplicationThread thread) {
3058
3059 mProcDeaths[0]++;
3060
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003061 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3062 synchronized (stats) {
3063 stats.noteProcessDiedLocked(app.info.uid, pid);
3064 }
3065
Magnus Edlund7bb25812010-02-24 15:45:06 +01003066 // Clean up already done if the process has been re-started.
3067 if (app.pid == pid && app.thread != null &&
3068 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003069 if (!app.killedBackground) {
3070 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3071 + ") has died.");
3072 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003073 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003074 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 TAG, "Dying app: " + app + ", pid: " + pid
3076 + ", thread: " + thread.asBinder());
3077 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003078 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079
3080 if (doLowMem) {
3081 // If there are no longer any background processes running,
3082 // and the app that died was not running instrumentation,
3083 // then tell everyone we are now low on memory.
3084 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003085 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3086 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003087 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 haveBg = true;
3089 break;
3090 }
3091 }
3092
3093 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003094 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003095 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003096 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3097 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003098 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003099 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3100 // The low memory report is overriding any current
3101 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003102 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003103 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003104 rec.lastRequestedGc = 0;
3105 } else {
3106 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003108 rec.reportLowMemory = true;
3109 rec.lastLowMemory = now;
3110 mProcessesToGc.remove(rec);
3111 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 }
3113 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003114 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003115 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 }
3117 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003118 } else if (app.pid != pid) {
3119 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003120 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003121 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003122 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003123 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003124 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 + thread.asBinder());
3126 }
3127 }
3128
Dan Egnor42471dd2010-01-07 17:25:22 -08003129 /**
3130 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003131 * @param clearTraces causes the dump file to be erased prior to the new
3132 * traces being written, if true; when false, the new traces will be
3133 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003134 * @param firstPids of dalvik VM processes to dump stack traces for first
3135 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003136 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003137 * @return file containing stack traces, or null if no dump file is configured
3138 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003139 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003140 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003141 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3142 if (tracesPath == null || tracesPath.length() == 0) {
3143 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003145
3146 File tracesFile = new File(tracesPath);
3147 try {
3148 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003149 if (!tracesDir.exists()) {
3150 tracesFile.mkdirs();
3151 if (!SELinux.restorecon(tracesDir)) {
3152 return null;
3153 }
3154 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003155 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3156
Christopher Tate6ee412d2010-05-28 12:01:56 -07003157 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003158 tracesFile.createNewFile();
3159 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3160 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003161 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003162 return null;
3163 }
3164
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003165 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003166 return tracesFile;
3167 }
3168
3169 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003170 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003171 // Use a FileObserver to detect when traces finish writing.
3172 // The order of traces is considered important to maintain for legibility.
3173 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3174 public synchronized void onEvent(int event, String path) { notify(); }
3175 };
3176
3177 try {
3178 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003179
3180 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003181 if (firstPids != null) {
3182 try {
3183 int num = firstPids.size();
3184 for (int i = 0; i < num; i++) {
3185 synchronized (observer) {
3186 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3187 observer.wait(200); // Wait for write-close, give up after 200msec
3188 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003189 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003190 } catch (InterruptedException e) {
3191 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003192 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003193 }
3194
3195 // Next measure CPU usage.
3196 if (processStats != null) {
3197 processStats.init();
3198 System.gc();
3199 processStats.update();
3200 try {
3201 synchronized (processStats) {
3202 processStats.wait(500); // measure over 1/2 second.
3203 }
3204 } catch (InterruptedException e) {
3205 }
3206 processStats.update();
3207
3208 // We'll take the stack crawls of just the top apps using CPU.
3209 final int N = processStats.countWorkingStats();
3210 int numProcs = 0;
3211 for (int i=0; i<N && numProcs<5; i++) {
3212 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3213 if (lastPids.indexOfKey(stats.pid) >= 0) {
3214 numProcs++;
3215 try {
3216 synchronized (observer) {
3217 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3218 observer.wait(200); // Wait for write-close, give up after 200msec
3219 }
3220 } catch (InterruptedException e) {
3221 Log.wtf(TAG, e);
3222 }
3223
3224 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003225 }
3226 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003227
Dan Egnor42471dd2010-01-07 17:25:22 -08003228 } finally {
3229 observer.stopWatching();
3230 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003231
3232 if (nativeProcs != null) {
3233 int[] pids = Process.getPidsForCommands(nativeProcs);
3234 if (pids != null) {
3235 for (int pid : pids) {
3236 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3237 }
3238 }
3239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 }
3241
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003242 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003243 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003244 return;
3245 }
3246 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3247 if (tracesPath == null || tracesPath.length() == 0) {
3248 return;
3249 }
3250
3251 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3252 StrictMode.allowThreadDiskWrites();
3253 try {
3254 final File tracesFile = new File(tracesPath);
3255 final File tracesDir = tracesFile.getParentFile();
3256 final File tracesTmp = new File(tracesDir, "__tmp__");
3257 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003258 if (!tracesDir.exists()) {
3259 tracesFile.mkdirs();
3260 if (!SELinux.restorecon(tracesDir.getPath())) {
3261 return;
3262 }
3263 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003264 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3265
3266 if (tracesFile.exists()) {
3267 tracesTmp.delete();
3268 tracesFile.renameTo(tracesTmp);
3269 }
3270 StringBuilder sb = new StringBuilder();
3271 Time tobj = new Time();
3272 tobj.set(System.currentTimeMillis());
3273 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3274 sb.append(": ");
3275 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3276 sb.append(" since ");
3277 sb.append(msg);
3278 FileOutputStream fos = new FileOutputStream(tracesFile);
3279 fos.write(sb.toString().getBytes());
3280 if (app == null) {
3281 fos.write("\n*** No application process!".getBytes());
3282 }
3283 fos.close();
3284 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3285 } catch (IOException e) {
3286 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3287 return;
3288 }
3289
3290 if (app != null) {
3291 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3292 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003293 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003294 }
3295
3296 File lastTracesFile = null;
3297 File curTracesFile = null;
3298 for (int i=9; i>=0; i--) {
3299 String name = String.format("slow%02d.txt", i);
3300 curTracesFile = new File(tracesDir, name);
3301 if (curTracesFile.exists()) {
3302 if (lastTracesFile != null) {
3303 curTracesFile.renameTo(lastTracesFile);
3304 } else {
3305 curTracesFile.delete();
3306 }
3307 }
3308 lastTracesFile = curTracesFile;
3309 }
3310 tracesFile.renameTo(curTracesFile);
3311 if (tracesTmp.exists()) {
3312 tracesTmp.renameTo(tracesFile);
3313 }
3314 } finally {
3315 StrictMode.setThreadPolicy(oldPolicy);
3316 }
3317 }
3318
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003319 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003320 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003321 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3322 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3323
Dianne Hackborn287952c2010-09-22 22:34:31 -07003324 if (mController != null) {
3325 try {
3326 // 0 == continue, -1 = kill process immediately
3327 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3328 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3329 } catch (RemoteException e) {
3330 mController = null;
3331 }
3332 }
3333
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003334 long anrTime = SystemClock.uptimeMillis();
3335 if (MONITOR_CPU_USAGE) {
3336 updateCpuStatsNow();
3337 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003338
3339 synchronized (this) {
3340 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3341 if (mShuttingDown) {
3342 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3343 return;
3344 } else if (app.notResponding) {
3345 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3346 return;
3347 } else if (app.crashing) {
3348 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3349 return;
3350 }
3351
3352 // In case we come through here for the same app before completing
3353 // this one, mark as anring now so we will bail out.
3354 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003355
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003356 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003357 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3358 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003359
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003360 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003361 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003362
3363 int parentPid = app.pid;
3364 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003365 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003366
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003367 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003368
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003369 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3370 ProcessRecord r = mLruProcesses.get(i);
3371 if (r != null && r.thread != null) {
3372 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003373 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3374 if (r.persistent) {
3375 firstPids.add(pid);
3376 } else {
3377 lastPids.put(pid, Boolean.TRUE);
3378 }
3379 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 }
3382 }
3383
Dan Egnor42471dd2010-01-07 17:25:22 -08003384 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003385 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003386 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003387 info.append("ANR in ").append(app.processName);
3388 if (activity != null && activity.shortComponentName != null) {
3389 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003390 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003391 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003393 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003395 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003396 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398
Dianne Hackborn287952c2010-09-22 22:34:31 -07003399 final ProcessStats processStats = new ProcessStats(true);
3400
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003401 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003402
Dan Egnor42471dd2010-01-07 17:25:22 -08003403 String cpuInfo = null;
3404 if (MONITOR_CPU_USAGE) {
3405 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003406 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003407 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003408 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003409 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003410 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 }
3412
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003413 info.append(processStats.printCurrentState(anrTime));
3414
Joe Onorato8a9b2202010-02-26 18:56:32 -08003415 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003416 if (tracesFile == null) {
3417 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3418 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3419 }
3420
Jeff Sharkeya353d262011-10-28 11:12:06 -07003421 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3422 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003423
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003424 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003426 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3427 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003429 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3430 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 }
3432 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003433 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 }
3435 }
3436
Dan Egnor42471dd2010-01-07 17:25:22 -08003437 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3438 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3439 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003440
3441 synchronized (this) {
3442 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003443 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003444 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003445 app.processName, app.setAdj, "background ANR");
3446 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003447 return;
3448 }
3449
3450 // Set the app's notResponding state, and look up the errorReportReceiver
3451 makeAppNotRespondingLocked(app,
3452 activity != null ? activity.shortComponentName : null,
3453 annotation != null ? "ANR " + annotation : "ANR",
3454 info.toString());
3455
3456 // Bring up the infamous App Not Responding dialog
3457 Message msg = Message.obtain();
3458 HashMap map = new HashMap();
3459 msg.what = SHOW_NOT_RESPONDING_MSG;
3460 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003461 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003462 map.put("app", app);
3463 if (activity != null) {
3464 map.put("activity", activity);
3465 }
3466
3467 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 }
3470
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003471 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3472 if (!mLaunchWarningShown) {
3473 mLaunchWarningShown = true;
3474 mHandler.post(new Runnable() {
3475 @Override
3476 public void run() {
3477 synchronized (ActivityManagerService.this) {
3478 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3479 d.show();
3480 mHandler.postDelayed(new Runnable() {
3481 @Override
3482 public void run() {
3483 synchronized (ActivityManagerService.this) {
3484 d.dismiss();
3485 mLaunchWarningShown = false;
3486 }
3487 }
3488 }, 4000);
3489 }
3490 }
3491 });
3492 }
3493 }
3494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003496 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003497 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 int uid = Binder.getCallingUid();
3499 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003500 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003501 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 long callingId = Binder.clearCallingIdentity();
3503 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003504 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 int pkgUid = -1;
3506 synchronized(this) {
3507 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003508 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 } catch (RemoteException e) {
3510 }
3511 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003512 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 return false;
3514 }
3515 if (uid == pkgUid || checkComponentPermission(
3516 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003517 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003519 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 } else {
3521 throw new SecurityException(pid+" does not have permission:"+
3522 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3523 "for process:"+packageName);
3524 }
3525 }
3526
3527 try {
3528 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003529 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3531 Uri.fromParts("package", packageName, null));
3532 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003533 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003534 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 } catch (RemoteException e) {
3536 }
3537 } finally {
3538 Binder.restoreCallingIdentity(callingId);
3539 }
3540 return true;
3541 }
3542
Dianne Hackborn1676c852012-09-10 14:52:30 -07003543 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003544 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3545 != PackageManager.PERMISSION_GRANTED &&
3546 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3547 != PackageManager.PERMISSION_GRANTED) {
3548 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 + Binder.getCallingPid()
3550 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003551 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003552 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 throw new SecurityException(msg);
3554 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003555
Dianne Hackborn139748f2012-09-24 11:36:57 -07003556 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003557 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 long callingId = Binder.clearCallingIdentity();
3559 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003560 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003562 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003564 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 } catch (RemoteException e) {
3566 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003567 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003568 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 return;
3570 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003571 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003572 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3573 }
3574 } finally {
3575 Binder.restoreCallingIdentity(callingId);
3576 }
3577 }
3578
3579 public void killAllBackgroundProcesses() {
3580 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3581 != PackageManager.PERMISSION_GRANTED) {
3582 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3583 + Binder.getCallingPid()
3584 + ", uid=" + Binder.getCallingUid()
3585 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3586 Slog.w(TAG, msg);
3587 throw new SecurityException(msg);
3588 }
3589
3590 long callingId = Binder.clearCallingIdentity();
3591 try {
3592 synchronized(this) {
3593 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3594 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3595 final int NA = apps.size();
3596 for (int ia=0; ia<NA; ia++) {
3597 ProcessRecord app = apps.valueAt(ia);
3598 if (app.persistent) {
3599 // we don't kill persistent processes
3600 continue;
3601 }
3602 if (app.removed) {
3603 procs.add(app);
3604 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3605 app.removed = true;
3606 procs.add(app);
3607 }
3608 }
3609 }
3610
3611 int N = procs.size();
3612 for (int i=0; i<N; i++) {
3613 removeProcessLocked(procs.get(i), false, true, "kill all background");
3614 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003615 }
3616 } finally {
3617 Binder.restoreCallingIdentity(callingId);
3618 }
3619 }
3620
Dianne Hackborn1676c852012-09-10 14:52:30 -07003621 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003622 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3623 != PackageManager.PERMISSION_GRANTED) {
3624 String msg = "Permission Denial: forceStopPackage() from pid="
3625 + Binder.getCallingPid()
3626 + ", uid=" + Binder.getCallingUid()
3627 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003628 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003629 throw new SecurityException(msg);
3630 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003631 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003632 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003633 long callingId = Binder.clearCallingIdentity();
3634 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003635 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003636 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003637 int[] users = userId == UserHandle.USER_ALL
3638 ? getUsersLocked() : new int[] { userId };
3639 for (int user : users) {
3640 int pkgUid = -1;
3641 try {
3642 pkgUid = pm.getPackageUid(packageName, user);
3643 } catch (RemoteException e) {
3644 }
3645 if (pkgUid == -1) {
3646 Slog.w(TAG, "Invalid packageName: " + packageName);
3647 continue;
3648 }
3649 try {
3650 pm.setPackageStoppedState(packageName, true, user);
3651 } catch (RemoteException e) {
3652 } catch (IllegalArgumentException e) {
3653 Slog.w(TAG, "Failed trying to unstop package "
3654 + packageName + ": " + e);
3655 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003656 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003657 forceStopPackageLocked(packageName, pkgUid);
3658 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 }
3661 } finally {
3662 Binder.restoreCallingIdentity(callingId);
3663 }
3664 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003665
3666 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003667 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003668 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003669 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003670 if (pkg == null) {
3671 return;
3672 }
3673 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003674 if (appid < 0) {
3675 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003676 return;
3677 }
3678 int callerUid = Binder.getCallingUid();
3679 // Only the system server can kill an application
3680 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003681 // Post an aysnc message to kill the application
3682 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003683 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003684 msg.arg2 = 0;
3685 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003686 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003687 } else {
3688 throw new SecurityException(callerUid + " cannot kill pkg: " +
3689 pkg);
3690 }
3691 }
3692
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003693 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003694 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003695
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003696 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003697 final int uid = Binder.getCallingUid();
3698 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003699 try {
3700 synchronized (this) {
3701 // Only allow this from foreground processes, so that background
3702 // applications can't abuse it to prevent system UI from being shown.
3703 if (uid >= Process.FIRST_APPLICATION_UID) {
3704 ProcessRecord proc;
3705 synchronized (mPidsSelfLocked) {
3706 proc = mPidsSelfLocked.get(pid);
3707 }
3708 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3709 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3710 + " from background process " + proc);
3711 return;
3712 }
3713 }
3714 closeSystemDialogsLocked(reason);
3715 }
3716 } finally {
3717 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003718 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003719 }
3720
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003721 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003722 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003723 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3724 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003725 if (reason != null) {
3726 intent.putExtra("reason", reason);
3727 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003728 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003729
Dianne Hackborne302a162012-05-15 14:58:32 -07003730 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3731 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003732 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003733 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003734 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003735 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003736 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003737
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003738 broadcastIntentLocked(null, null, intent, null,
3739 null, 0, null, null, null, false, false, -1,
3740 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003741 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003742
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003743 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003744 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003745 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003746 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3747 for (int i=pids.length-1; i>=0; i--) {
3748 infos[i] = new Debug.MemoryInfo();
3749 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003750 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003751 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003752 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003753
Dianne Hackbornb437e092011-08-05 17:50:29 -07003754 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003755 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003756 long[] pss = new long[pids.length];
3757 for (int i=pids.length-1; i>=0; i--) {
3758 pss[i] = Debug.getPss(pids[i]);
3759 }
3760 return pss;
3761 }
3762
Christopher Tate5e1ab332009-09-01 20:32:49 -07003763 public void killApplicationProcess(String processName, int uid) {
3764 if (processName == null) {
3765 return;
3766 }
3767
3768 int callerUid = Binder.getCallingUid();
3769 // Only the system server can kill an application
3770 if (callerUid == Process.SYSTEM_UID) {
3771 synchronized (this) {
3772 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003773 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003774 try {
3775 app.thread.scheduleSuicide();
3776 } catch (RemoteException e) {
3777 // If the other end already died, then our work here is done.
3778 }
3779 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003780 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003781 + processName + " / " + uid);
3782 }
3783 }
3784 } else {
3785 throw new SecurityException(callerUid + " cannot kill app process: " +
3786 processName);
3787 }
3788 }
3789
Dianne Hackborn03abb812010-01-04 18:43:19 -08003790 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003791 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3792 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3794 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003795 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003796 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3797 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003800 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 broadcastIntentLocked(null, null, intent,
3802 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003803 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003804 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003806
3807 private void forceStopUserLocked(int userId) {
3808 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3809 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003810 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3811 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003812 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3813 broadcastIntentLocked(null, null, intent,
3814 null, null, 0, null, null, null,
3815 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003816 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003817 }
3818
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003819 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003820 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3821 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003822 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823
Dianne Hackborn03abb812010-01-04 18:43:19 -08003824 // Remove all processes this package may have touched: all with the
3825 // same UID (except for the system or root user), and all whose name
3826 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003827 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003828 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3829 final int NA = apps.size();
3830 for (int ia=0; ia<NA; ia++) {
3831 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003832 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003833 // we don't kill persistent processes
3834 continue;
3835 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003836 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003837 if (doit) {
3838 procs.add(app);
3839 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003840 continue;
3841 }
3842
3843 // Skip process if it doesn't meet our oom adj requirement.
3844 if (app.setAdj < minOomAdj) {
3845 continue;
3846 }
3847
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003848 // If no package is specified, we call all processes under the
3849 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003850 if (packageName == null) {
3851 if (app.userId != userId) {
3852 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003853 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003854 // Package has been specified, we want to hit all processes
3855 // that match it. We need to qualify this by the processes
3856 // that are running under the specified app and user ID.
3857 } else {
3858 if (UserHandle.getAppId(app.uid) != appId) {
3859 continue;
3860 }
3861 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3862 continue;
3863 }
3864 if (!app.pkgList.contains(packageName)) {
3865 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003866 }
3867 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003868
3869 // Process has passed all conditions, kill it!
3870 if (!doit) {
3871 return true;
3872 }
3873 app.removed = true;
3874 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003875 }
3876 }
3877
3878 int N = procs.size();
3879 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003880 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003881 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003882 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003883 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003884
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003885 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003886 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003887 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003888 int i;
3889 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003891 if (userId == UserHandle.USER_ALL && name == null) {
3892 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3893 }
3894
3895 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003897 appId = UserHandle.getAppId(
3898 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 } catch (RemoteException e) {
3900 }
3901 }
3902
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003903 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003904 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003905 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3906 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003907 } else {
3908 Slog.i(TAG, "Force stopping user " + userId);
3909 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003910
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003911 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3912 while (badApps.hasNext()) {
3913 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003914 for (i=ba.size()-1; i>=0; i--) {
3915 boolean remove = false;
3916 final int entUid = ba.keyAt(i);
3917 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003918 if (userId == UserHandle.USER_ALL) {
3919 if (UserHandle.getAppId(entUid) == appId) {
3920 remove = true;
3921 }
3922 } else {
3923 if (entUid == UserHandle.getUid(userId, appId)) {
3924 remove = true;
3925 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003926 }
3927 } else if (UserHandle.getUserId(entUid) == userId) {
3928 remove = true;
3929 }
3930 if (remove) {
3931 ba.removeAt(i);
3932 }
3933 }
3934 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003935 badApps.remove();
3936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 }
3938 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003939
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003940 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003941 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003942 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003944 TaskRecord lastTask = null;
3945 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003946 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003947 final boolean samePackage = r.packageName.equals(name)
3948 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003949 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003950 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003951 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003952 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003953 if (r.finishing) {
3954 // If this activity is just finishing, then it is not
3955 // interesting as far as something to stop.
3956 continue;
3957 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003958 return true;
3959 }
3960 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003961 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003962 if (samePackage) {
3963 if (r.app != null) {
3964 r.app.removed = true;
3965 }
3966 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003968 lastTask = r.task;
3969 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003970 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003971 i--;
3972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 }
3974 }
3975
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003976 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3977 if (!doit) {
3978 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003980 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003982
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003983 if (name == null) {
3984 // Remove all sticky broadcasts from this user.
3985 mStickyBroadcasts.remove(userId);
3986 }
3987
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003988 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003989 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3990 userId, providers)) {
3991 if (!doit) {
3992 return true;
3993 }
3994 didSomething = true;
3995 }
3996 N = providers.size();
3997 for (i=0; i<N; i++) {
3998 removeDyingProviderLocked(null, providers.get(i), true);
3999 }
4000
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004001 if (name == null) {
4002 // Remove pending intents. For now we only do this when force
4003 // stopping users, because we have some problems when doing this
4004 // for packages -- app widgets are not currently cleaned up for
4005 // such packages, so they can be left with bad pending intents.
4006 if (mIntentSenderRecords.size() > 0) {
4007 Iterator<WeakReference<PendingIntentRecord>> it
4008 = mIntentSenderRecords.values().iterator();
4009 while (it.hasNext()) {
4010 WeakReference<PendingIntentRecord> wpir = it.next();
4011 if (wpir == null) {
4012 it.remove();
4013 continue;
4014 }
4015 PendingIntentRecord pir = wpir.get();
4016 if (pir == null) {
4017 it.remove();
4018 continue;
4019 }
4020 if (name == null) {
4021 // Stopping user, remove all objects for the user.
4022 if (pir.key.userId != userId) {
4023 // Not the same user, skip it.
4024 continue;
4025 }
4026 } else {
4027 if (UserHandle.getAppId(pir.uid) != appId) {
4028 // Different app id, skip it.
4029 continue;
4030 }
4031 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
4032 // Different user, skip it.
4033 continue;
4034 }
4035 if (!pir.key.packageName.equals(name)) {
4036 // Different package, skip it.
4037 continue;
4038 }
4039 }
4040 if (!doit) {
4041 return true;
4042 }
4043 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004044 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004045 pir.canceled = true;
4046 if (pir.key.activity != null) {
4047 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004048 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004049 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004050 }
4051 }
4052
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004053 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004054 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004055 AttributeCache ac = AttributeCache.instance();
4056 if (ac != null) {
4057 ac.removePackage(name);
4058 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004059 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004060 if (mBooted) {
4061 mMainStack.resumeTopActivityLocked(null);
4062 mMainStack.scheduleIdleLocked();
4063 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004064 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004065
4066 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 }
4068
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004069 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004070 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004072 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004073 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004074 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 + "/" + uid + ")");
4076
4077 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004078 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004079 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004080 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4081 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004082 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 boolean needRestart = false;
4085 if (app.pid > 0 && app.pid != MY_PID) {
4086 int pid = app.pid;
4087 synchronized (mPidsSelfLocked) {
4088 mPidsSelfLocked.remove(pid);
4089 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4090 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004091 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004092 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004093 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004094 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004096 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004098 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 } else {
4100 needRestart = true;
4101 }
4102 }
4103 } else {
4104 mRemovedProcesses.add(app);
4105 }
4106
4107 return needRestart;
4108 }
4109
4110 private final void processStartTimedOutLocked(ProcessRecord app) {
4111 final int pid = app.pid;
4112 boolean gone = false;
4113 synchronized (mPidsSelfLocked) {
4114 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4115 if (knownApp != null && knownApp.thread == null) {
4116 mPidsSelfLocked.remove(pid);
4117 gone = true;
4118 }
4119 }
4120
4121 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004122 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004123 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4124 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004125 mProcessNames.remove(app.processName, app.uid);
4126 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004127 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004128 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4129 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004130 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004131 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004132 // Take care of any launching providers waiting for this process.
4133 checkAppInLaunchingProvidersLocked(app, true);
4134 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004135 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004136 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004137 app.processName, app.setAdj, "start timeout");
4138 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004139 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004140 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004141 try {
4142 IBackupManager bm = IBackupManager.Stub.asInterface(
4143 ServiceManager.getService(Context.BACKUP_SERVICE));
4144 bm.agentDisconnected(app.info.packageName);
4145 } catch (RemoteException e) {
4146 // Can't happen; the backup manager is local
4147 }
4148 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004149 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004150 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004151 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004154 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156 }
4157
4158 private final boolean attachApplicationLocked(IApplicationThread thread,
4159 int pid) {
4160
4161 // Find the application record that is being attached... either via
4162 // the pid if we are running in multiple processes, or just pull the
4163 // next app record if we are emulating process with anonymous threads.
4164 ProcessRecord app;
4165 if (pid != MY_PID && pid >= 0) {
4166 synchronized (mPidsSelfLocked) {
4167 app = mPidsSelfLocked.get(pid);
4168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 } else {
4170 app = null;
4171 }
4172
4173 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004174 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004176 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004178 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 } else {
4180 try {
4181 thread.scheduleExit();
4182 } catch (Exception e) {
4183 // Ignore exceptions.
4184 }
4185 }
4186 return false;
4187 }
4188
4189 // If this application record is still attached to a previous
4190 // process, clean it up now.
4191 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004192 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 }
4194
4195 // Tell the process all about itself.
4196
Joe Onorato8a9b2202010-02-26 18:56:32 -08004197 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 TAG, "Binding process pid " + pid + " to record " + app);
4199
4200 String processName = app.processName;
4201 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004202 AppDeathRecipient adr = new AppDeathRecipient(
4203 app, pid, thread);
4204 thread.asBinder().linkToDeath(adr, 0);
4205 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 } catch (RemoteException e) {
4207 app.resetPackageList();
4208 startProcessLocked(app, "link fail", processName);
4209 return false;
4210 }
4211
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004212 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213
4214 app.thread = thread;
4215 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004216 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4217 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 app.forcingToForeground = null;
4219 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004220 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 app.debugging = false;
4222
4223 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4224
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004225 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004226 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004228 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004229 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004230 }
4231
Joe Onorato8a9b2202010-02-26 18:56:32 -08004232 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 TAG, "New app record " + app
4234 + " thread=" + thread.asBinder() + " pid=" + pid);
4235 try {
4236 int testMode = IApplicationThread.DEBUG_OFF;
4237 if (mDebugApp != null && mDebugApp.equals(processName)) {
4238 testMode = mWaitForDebugger
4239 ? IApplicationThread.DEBUG_WAIT
4240 : IApplicationThread.DEBUG_ON;
4241 app.debugging = true;
4242 if (mDebugTransient) {
4243 mDebugApp = mOrigDebugApp;
4244 mWaitForDebugger = mOrigWaitForDebugger;
4245 }
4246 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004247 String profileFile = app.instrumentationProfileFile;
4248 ParcelFileDescriptor profileFd = null;
4249 boolean profileAutoStop = false;
4250 if (mProfileApp != null && mProfileApp.equals(processName)) {
4251 mProfileProc = app;
4252 profileFile = mProfileFile;
4253 profileFd = mProfileFd;
4254 profileAutoStop = mAutoStopProfiler;
4255 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004256 boolean enableOpenGlTrace = false;
4257 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4258 enableOpenGlTrace = true;
4259 mOpenGlTraceApp = null;
4260 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004261
Christopher Tate181fafa2009-05-14 11:12:14 -07004262 // If the app is being launched for restore or full backup, set it up specially
4263 boolean isRestrictedBackupMode = false;
4264 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4265 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004266 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004267 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4268 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004269
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004270 ensurePackageDexOpt(app.instrumentationInfo != null
4271 ? app.instrumentationInfo.packageName
4272 : app.info.packageName);
4273 if (app.instrumentationClass != null) {
4274 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004275 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004276 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004277 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004278 ApplicationInfo appInfo = app.instrumentationInfo != null
4279 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004280 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004281 if (profileFd != null) {
4282 profileFd = profileFd.dup();
4283 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004284 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004285 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004286 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4287 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004288 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004289 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004290 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004291 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 } catch (Exception e) {
4293 // todo: Yikes! What should we do? For now we will try to
4294 // start another process, but that could easily get us in
4295 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004296 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297
4298 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004299 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 startProcessLocked(app, "bind fail", processName);
4301 return false;
4302 }
4303
4304 // Remove this record from the list of starting applications.
4305 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004306 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4307 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 mProcessesOnHold.remove(app);
4309
4310 boolean badApp = false;
4311 boolean didSomething = false;
4312
4313 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004314 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004315 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004316 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 && processName.equals(hr.processName)) {
4318 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004319 if (mHeadless) {
4320 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4321 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 didSomething = true;
4323 }
4324 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004325 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 + hr.intent.getComponent().flattenToShortString(), e);
4327 badApp = true;
4328 }
4329 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004330 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 }
4332 }
4333
4334 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004335 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004337 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 badApp = true;
4340 }
4341 }
4342
Christopher Tatef46723b2012-01-26 14:19:24 -08004343 // Check if a next-broadcast receiver is in this process...
4344 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004346 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004348 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 }
4351 }
4352
Christopher Tate181fafa2009-05-14 11:12:14 -07004353 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004354 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004355 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004356 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004357 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004358 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4359 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4360 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004361 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004362 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004363 e.printStackTrace();
4364 }
4365 }
4366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 if (badApp) {
4368 // todo: Also need to kill application to deal with all
4369 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004370 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 return false;
4372 }
4373
4374 if (!didSomething) {
4375 updateOomAdjLocked();
4376 }
4377
4378 return true;
4379 }
4380
4381 public final void attachApplication(IApplicationThread thread) {
4382 synchronized (this) {
4383 int callingPid = Binder.getCallingPid();
4384 final long origId = Binder.clearCallingIdentity();
4385 attachApplicationLocked(thread, callingPid);
4386 Binder.restoreCallingIdentity(origId);
4387 }
4388 }
4389
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004390 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004392 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4393 if (stopProfiling) {
4394 synchronized (this) {
4395 if (mProfileProc == r.app) {
4396 if (mProfileFd != null) {
4397 try {
4398 mProfileFd.close();
4399 } catch (IOException e) {
4400 }
4401 clearProfilerLocked();
4402 }
4403 }
4404 }
4405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 Binder.restoreCallingIdentity(origId);
4407 }
4408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004410 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004411 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004413
4414 synchronized (this) {
4415 updateEventDispatchingLocked();
4416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417 }
4418
Dianne Hackborn661cd522011-08-22 00:26:20 -07004419 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004420 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004421 mWindowManager.showBootMessage(msg, always);
4422 }
4423
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004424 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004425 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004426 final long token = Binder.clearCallingIdentity();
4427 try {
4428 synchronized (this) {
4429 if (mLockScreenShown) {
4430 mLockScreenShown = false;
4431 comeOutOfSleepIfNeededLocked();
4432 }
4433 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004434 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004435 } finally {
4436 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004437 }
4438 }
4439
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004440 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004441 IntentFilter pkgFilter = new IntentFilter();
4442 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4443 pkgFilter.addDataScheme("package");
4444 mContext.registerReceiver(new BroadcastReceiver() {
4445 @Override
4446 public void onReceive(Context context, Intent intent) {
4447 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4448 if (pkgs != null) {
4449 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004450 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004451 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4452 setResultCode(Activity.RESULT_OK);
4453 return;
4454 }
4455 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004456 }
4457 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004458 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004459 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004460
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004461 synchronized (this) {
4462 // Ensure that any processes we had put on hold are now started
4463 // up.
4464 final int NP = mProcessesOnHold.size();
4465 if (NP > 0) {
4466 ArrayList<ProcessRecord> procs =
4467 new ArrayList<ProcessRecord>(mProcessesOnHold);
4468 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004469 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4470 + procs.get(ip));
4471 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004472 }
4473 }
4474
4475 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004476 // Start looking for apps that are abusing wake locks.
4477 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004478 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004479 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004480 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004481 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004482 for (int i=0; i<mStartedUsers.size(); i++) {
4483 UserStartedState uss = mStartedUsers.valueAt(i);
4484 if (uss.mState == UserStartedState.STATE_BOOTING) {
4485 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004486 final int userId = mStartedUsers.keyAt(i);
4487 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4488 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4489 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004490 null, null, 0, null, null,
4491 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004492 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004493 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004494 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004495 }
4496 }
4497 }
4498
4499 final void ensureBootCompleted() {
4500 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004501 boolean enableScreen;
4502 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004503 booting = mBooting;
4504 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004505 enableScreen = !mBooted;
4506 mBooted = true;
4507 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004508
4509 if (booting) {
4510 finishBooting();
4511 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004512
4513 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004514 enableScreenAfterBoot();
4515 }
4516 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004517
4518 public final void activityResumed(IBinder token) {
4519 final long origId = Binder.clearCallingIdentity();
4520 mMainStack.activityResumed(token);
4521 Binder.restoreCallingIdentity(origId);
4522 }
4523
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004524 public final void activityPaused(IBinder token) {
4525 final long origId = Binder.clearCallingIdentity();
4526 mMainStack.activityPaused(token, false);
4527 Binder.restoreCallingIdentity(origId);
4528 }
4529
4530 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4531 CharSequence description) {
4532 if (localLOGV) Slog.v(
4533 TAG, "Activity stopped: token=" + token);
4534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 // Refuse possible leaked file descriptors
4536 if (icicle != null && icicle.hasFileDescriptors()) {
4537 throw new IllegalArgumentException("File descriptors passed in Bundle");
4538 }
4539
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004540 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541
4542 final long origId = Binder.clearCallingIdentity();
4543
4544 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004545 r = mMainStack.isInStackLocked(token);
4546 if (r != null) {
4547 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 }
4549 }
4550
4551 if (r != null) {
4552 sendPendingThumbnail(r, null, null, null, false);
4553 }
4554
4555 trimApplications();
4556
4557 Binder.restoreCallingIdentity(origId);
4558 }
4559
4560 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004561 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004562 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 }
4564
4565 public String getCallingPackage(IBinder token) {
4566 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004567 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004568 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 }
4570 }
4571
4572 public ComponentName getCallingActivity(IBinder token) {
4573 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004574 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 return r != null ? r.intent.getComponent() : null;
4576 }
4577 }
4578
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004579 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004580 ActivityRecord r = mMainStack.isInStackLocked(token);
4581 if (r == null) {
4582 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004584 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 }
4586
4587 public ComponentName getActivityClassForToken(IBinder token) {
4588 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004589 ActivityRecord r = mMainStack.isInStackLocked(token);
4590 if (r == null) {
4591 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004593 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 }
4595 }
4596
4597 public String getPackageForToken(IBinder token) {
4598 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004599 ActivityRecord r = mMainStack.isInStackLocked(token);
4600 if (r == null) {
4601 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004603 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 }
4605 }
4606
4607 public IIntentSender getIntentSender(int type,
4608 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004609 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004610 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004611 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004613 if (intents != null) {
4614 if (intents.length < 1) {
4615 throw new IllegalArgumentException("Intents array length must be >= 1");
4616 }
4617 for (int i=0; i<intents.length; i++) {
4618 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004619 if (intent != null) {
4620 if (intent.hasFileDescriptors()) {
4621 throw new IllegalArgumentException("File descriptors passed in Intent");
4622 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004623 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004624 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4625 throw new IllegalArgumentException(
4626 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4627 }
4628 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004629 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004630 }
4631 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004632 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004633 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004634 }
4635 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004636 if (options != null) {
4637 if (options.hasFileDescriptors()) {
4638 throw new IllegalArgumentException("File descriptors passed in options");
4639 }
4640 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004642 synchronized(this) {
4643 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004644 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004645 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004646 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004647 "getIntentSender", null);
4648 if (origUserId == UserHandle.USER_CURRENT) {
4649 // We don't want to evaluate this until the pending intent is
4650 // actually executed. However, we do want to always do the
4651 // security checking for it above.
4652 userId = UserHandle.USER_CURRENT;
4653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004655 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004656 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004657 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4658 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004659 String msg = "Permission Denial: getIntentSender() from pid="
4660 + Binder.getCallingPid()
4661 + ", uid=" + Binder.getCallingUid()
4662 + ", (need uid=" + uid + ")"
4663 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004664 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 throw new SecurityException(msg);
4666 }
4667 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004668
4669 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004670 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004672 } catch (RemoteException e) {
4673 throw new SecurityException(e);
4674 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004675 }
4676 }
4677
Dianne Hackborn41203752012-08-31 14:05:51 -07004678 IIntentSender getIntentSenderLocked(int type, String packageName,
4679 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004680 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4681 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004682 if (DEBUG_MU)
4683 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004684 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004685 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004686 activity = mMainStack.isInStackLocked(token);
4687 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004688 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004690 if (activity.finishing) {
4691 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004693 }
4694
4695 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4696 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4697 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4698 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4699 |PendingIntent.FLAG_UPDATE_CURRENT);
4700
4701 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4702 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004703 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004704 WeakReference<PendingIntentRecord> ref;
4705 ref = mIntentSenderRecords.get(key);
4706 PendingIntentRecord rec = ref != null ? ref.get() : null;
4707 if (rec != null) {
4708 if (!cancelCurrent) {
4709 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004710 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004711 rec.key.requestIntent.replaceExtras(intents != null ?
4712 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004713 }
4714 if (intents != null) {
4715 intents[intents.length-1] = rec.key.requestIntent;
4716 rec.key.allIntents = intents;
4717 rec.key.allResolvedTypes = resolvedTypes;
4718 } else {
4719 rec.key.allIntents = null;
4720 rec.key.allResolvedTypes = null;
4721 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 return rec;
4724 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004725 rec.canceled = true;
4726 mIntentSenderRecords.remove(key);
4727 }
4728 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 return rec;
4730 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004731 rec = new PendingIntentRecord(this, key, callingUid);
4732 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004733 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004734 if (activity.pendingResults == null) {
4735 activity.pendingResults
4736 = new HashSet<WeakReference<PendingIntentRecord>>();
4737 }
4738 activity.pendingResults.add(rec.ref);
4739 }
4740 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 }
4742
4743 public void cancelIntentSender(IIntentSender sender) {
4744 if (!(sender instanceof PendingIntentRecord)) {
4745 return;
4746 }
4747 synchronized(this) {
4748 PendingIntentRecord rec = (PendingIntentRecord)sender;
4749 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004750 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004751 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4752 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 String msg = "Permission Denial: cancelIntentSender() from pid="
4754 + Binder.getCallingPid()
4755 + ", uid=" + Binder.getCallingUid()
4756 + " is not allowed to cancel packges "
4757 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004758 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004759 throw new SecurityException(msg);
4760 }
4761 } catch (RemoteException e) {
4762 throw new SecurityException(e);
4763 }
4764 cancelIntentSenderLocked(rec, true);
4765 }
4766 }
4767
4768 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4769 rec.canceled = true;
4770 mIntentSenderRecords.remove(rec.key);
4771 if (cleanActivity && rec.key.activity != null) {
4772 rec.key.activity.pendingResults.remove(rec.ref);
4773 }
4774 }
4775
4776 public String getPackageForIntentSender(IIntentSender pendingResult) {
4777 if (!(pendingResult instanceof PendingIntentRecord)) {
4778 return null;
4779 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004780 try {
4781 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4782 return res.key.packageName;
4783 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 }
4785 return null;
4786 }
4787
Christopher Tatec4a07d12012-04-06 14:19:13 -07004788 public int getUidForIntentSender(IIntentSender sender) {
4789 if (sender instanceof PendingIntentRecord) {
4790 try {
4791 PendingIntentRecord res = (PendingIntentRecord)sender;
4792 return res.uid;
4793 } catch (ClassCastException e) {
4794 }
4795 }
4796 return -1;
4797 }
4798
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004799 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4800 if (!(pendingResult instanceof PendingIntentRecord)) {
4801 return false;
4802 }
4803 try {
4804 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4805 if (res.key.allIntents == null) {
4806 return false;
4807 }
4808 for (int i=0; i<res.key.allIntents.length; i++) {
4809 Intent intent = res.key.allIntents[i];
4810 if (intent.getPackage() != null && intent.getComponent() != null) {
4811 return false;
4812 }
4813 }
4814 return true;
4815 } catch (ClassCastException e) {
4816 }
4817 return false;
4818 }
4819
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004820 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4821 if (!(pendingResult instanceof PendingIntentRecord)) {
4822 return false;
4823 }
4824 try {
4825 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4826 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4827 return true;
4828 }
4829 return false;
4830 } catch (ClassCastException e) {
4831 }
4832 return false;
4833 }
4834
Dianne Hackborn81038902012-11-26 17:04:09 -08004835 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4836 if (!(pendingResult instanceof PendingIntentRecord)) {
4837 return null;
4838 }
4839 try {
4840 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4841 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4842 } catch (ClassCastException e) {
4843 }
4844 return null;
4845 }
4846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 public void setProcessLimit(int max) {
4848 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4849 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004850 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004851 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004852 mProcessLimitOverride = max;
4853 }
4854 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004855 }
4856
4857 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004858 synchronized (this) {
4859 return mProcessLimitOverride;
4860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 }
4862
4863 void foregroundTokenDied(ForegroundToken token) {
4864 synchronized (ActivityManagerService.this) {
4865 synchronized (mPidsSelfLocked) {
4866 ForegroundToken cur
4867 = mForegroundProcesses.get(token.pid);
4868 if (cur != token) {
4869 return;
4870 }
4871 mForegroundProcesses.remove(token.pid);
4872 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4873 if (pr == null) {
4874 return;
4875 }
4876 pr.forcingToForeground = null;
4877 pr.foregroundServices = false;
4878 }
4879 updateOomAdjLocked();
4880 }
4881 }
4882
4883 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4884 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4885 "setProcessForeground()");
4886 synchronized(this) {
4887 boolean changed = false;
4888
4889 synchronized (mPidsSelfLocked) {
4890 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004891 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004892 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 return;
4894 }
4895 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4896 if (oldToken != null) {
4897 oldToken.token.unlinkToDeath(oldToken, 0);
4898 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004899 if (pr != null) {
4900 pr.forcingToForeground = null;
4901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 changed = true;
4903 }
4904 if (isForeground && token != null) {
4905 ForegroundToken newToken = new ForegroundToken() {
4906 public void binderDied() {
4907 foregroundTokenDied(this);
4908 }
4909 };
4910 newToken.pid = pid;
4911 newToken.token = token;
4912 try {
4913 token.linkToDeath(newToken, 0);
4914 mForegroundProcesses.put(pid, newToken);
4915 pr.forcingToForeground = token;
4916 changed = true;
4917 } catch (RemoteException e) {
4918 // If the process died while doing this, we will later
4919 // do the cleanup with the process death link.
4920 }
4921 }
4922 }
4923
4924 if (changed) {
4925 updateOomAdjLocked();
4926 }
4927 }
4928 }
4929
4930 // =========================================================
4931 // PERMISSIONS
4932 // =========================================================
4933
4934 static class PermissionController extends IPermissionController.Stub {
4935 ActivityManagerService mActivityManagerService;
4936 PermissionController(ActivityManagerService activityManagerService) {
4937 mActivityManagerService = activityManagerService;
4938 }
4939
4940 public boolean checkPermission(String permission, int pid, int uid) {
4941 return mActivityManagerService.checkPermission(permission, pid,
4942 uid) == PackageManager.PERMISSION_GRANTED;
4943 }
4944 }
4945
4946 /**
4947 * This can be called with or without the global lock held.
4948 */
4949 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004950 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 // We might be performing an operation on behalf of an indirect binder
4952 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4953 // client identity accordingly before proceeding.
4954 Identity tlsIdentity = sCallerIdentity.get();
4955 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004956 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4958 uid = tlsIdentity.uid;
4959 pid = tlsIdentity.pid;
4960 }
4961
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004962 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 return PackageManager.PERMISSION_GRANTED;
4964 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004965
4966 return ActivityManager.checkComponentPermission(permission, uid,
4967 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004968 }
4969
4970 /**
4971 * As the only public entry point for permissions checking, this method
4972 * can enforce the semantic that requesting a check on a null global
4973 * permission is automatically denied. (Internally a null permission
4974 * string is used when calling {@link #checkComponentPermission} in cases
4975 * when only uid-based security is needed.)
4976 *
4977 * This can be called with or without the global lock held.
4978 */
4979 public int checkPermission(String permission, int pid, int uid) {
4980 if (permission == null) {
4981 return PackageManager.PERMISSION_DENIED;
4982 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004983 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 }
4985
4986 /**
4987 * Binder IPC calls go through the public entry point.
4988 * This can be called with or without the global lock held.
4989 */
4990 int checkCallingPermission(String permission) {
4991 return checkPermission(permission,
4992 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004993 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004994 }
4995
4996 /**
4997 * This can be called with or without the global lock held.
4998 */
4999 void enforceCallingPermission(String permission, String func) {
5000 if (checkCallingPermission(permission)
5001 == PackageManager.PERMISSION_GRANTED) {
5002 return;
5003 }
5004
5005 String msg = "Permission Denial: " + func + " from pid="
5006 + Binder.getCallingPid()
5007 + ", uid=" + Binder.getCallingUid()
5008 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005009 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005010 throw new SecurityException(msg);
5011 }
5012
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005013 /**
5014 * Determine if UID is holding permissions required to access {@link Uri} in
5015 * the given {@link ProviderInfo}. Final permission checking is always done
5016 * in {@link ContentProvider}.
5017 */
5018 private final boolean checkHoldingPermissionsLocked(
5019 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005020 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5021 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005022
5023 if (pi.applicationInfo.uid == uid) {
5024 return true;
5025 } else if (!pi.exported) {
5026 return false;
5027 }
5028
5029 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5030 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005032 // check if target holds top-level <provider> permissions
5033 if (!readMet && pi.readPermission != null
5034 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
5035 readMet = true;
5036 }
5037 if (!writeMet && pi.writePermission != null
5038 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
5039 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005040 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005041
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005042 // track if unprotected read/write is allowed; any denied
5043 // <path-permission> below removes this ability
5044 boolean allowDefaultRead = pi.readPermission == null;
5045 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07005046
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005047 // check if target holds any <path-permission> that match uri
5048 final PathPermission[] pps = pi.pathPermissions;
5049 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005050 final String path = uri.getPath();
5051 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005052 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005053 i--;
5054 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005055 if (pp.match(path)) {
5056 if (!readMet) {
5057 final String pprperm = pp.getReadPermission();
5058 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5059 + pprperm + " for " + pp.getPath()
5060 + ": match=" + pp.match(path)
5061 + " check=" + pm.checkUidPermission(pprperm, uid));
5062 if (pprperm != null) {
5063 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5064 readMet = true;
5065 } else {
5066 allowDefaultRead = false;
5067 }
5068 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005069 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005070 if (!writeMet) {
5071 final String ppwperm = pp.getWritePermission();
5072 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5073 + ppwperm + " for " + pp.getPath()
5074 + ": match=" + pp.match(path)
5075 + " check=" + pm.checkUidPermission(ppwperm, uid));
5076 if (ppwperm != null) {
5077 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5078 writeMet = true;
5079 } else {
5080 allowDefaultWrite = false;
5081 }
5082 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005083 }
5084 }
5085 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005086 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005087
5088 // grant unprotected <provider> read/write, if not blocked by
5089 // <path-permission> above
5090 if (allowDefaultRead) readMet = true;
5091 if (allowDefaultWrite) writeMet = true;
5092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 } catch (RemoteException e) {
5094 return false;
5095 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005096
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005097 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 }
5099
5100 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5101 int modeFlags) {
5102 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005103 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 return true;
5105 }
5106 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5107 if (perms == null) return false;
5108 UriPermission perm = perms.get(uri);
5109 if (perm == null) return false;
5110 return (modeFlags&perm.modeFlags) == modeFlags;
5111 }
5112
5113 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005114 enforceNotIsolatedCaller("checkUriPermission");
5115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 // Another redirected-binder-call permissions check as in
5117 // {@link checkComponentPermission}.
5118 Identity tlsIdentity = sCallerIdentity.get();
5119 if (tlsIdentity != null) {
5120 uid = tlsIdentity.uid;
5121 pid = tlsIdentity.pid;
5122 }
5123
5124 // Our own process gets to do everything.
5125 if (pid == MY_PID) {
5126 return PackageManager.PERMISSION_GRANTED;
5127 }
5128 synchronized(this) {
5129 return checkUriPermissionLocked(uri, uid, modeFlags)
5130 ? PackageManager.PERMISSION_GRANTED
5131 : PackageManager.PERMISSION_DENIED;
5132 }
5133 }
5134
Dianne Hackborn39792d22010-08-19 18:01:52 -07005135 /**
5136 * Check if the targetPkg can be granted permission to access uri by
5137 * the callingUid using the given modeFlags. Throws a security exception
5138 * if callingUid is not allowed to do this. Returns the uid of the target
5139 * if the URI permission grant should be performed; returns -1 if it is not
5140 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005141 * If you already know the uid of the target, you can supply it in
5142 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005143 */
5144 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005145 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5147 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5148 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005149 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 }
5151
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005152 if (targetPkg != null) {
5153 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5154 "Checking grant " + targetPkg + " permission to " + uri);
5155 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005156
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005157 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158
5159 // If this is not a content: uri, we can't do anything with it.
5160 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005161 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005162 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005163 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005164 }
5165
5166 String name = uri.getAuthority();
5167 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005168 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005169 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170 if (cpr != null) {
5171 pi = cpr.info;
5172 } else {
5173 try {
5174 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005175 PackageManager.GET_URI_PERMISSION_PATTERNS,
5176 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 } catch (RemoteException ex) {
5178 }
5179 }
5180 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005181 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005182 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 }
5184
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005185 int targetUid = lastTargetUid;
5186 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005187 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005188 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005189 if (targetUid < 0) {
5190 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5191 "Can't grant URI permission no uid for: " + targetPkg);
5192 return -1;
5193 }
5194 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005195 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 }
5198
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005199 if (targetUid >= 0) {
5200 // First... does the target actually need this permission?
5201 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5202 // No need to grant the target this permission.
5203 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5204 "Target " + targetPkg + " already has full permission to " + uri);
5205 return -1;
5206 }
5207 } else {
5208 // First... there is no target package, so can anyone access it?
5209 boolean allowed = pi.exported;
5210 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5211 if (pi.readPermission != null) {
5212 allowed = false;
5213 }
5214 }
5215 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5216 if (pi.writePermission != null) {
5217 allowed = false;
5218 }
5219 }
5220 if (allowed) {
5221 return -1;
5222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 }
5224
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005225 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005226 if (!pi.grantUriPermissions) {
5227 throw new SecurityException("Provider " + pi.packageName
5228 + "/" + pi.name
5229 + " does not allow granting of Uri permissions (uri "
5230 + uri + ")");
5231 }
5232 if (pi.uriPermissionPatterns != null) {
5233 final int N = pi.uriPermissionPatterns.length;
5234 boolean allowed = false;
5235 for (int i=0; i<N; i++) {
5236 if (pi.uriPermissionPatterns[i] != null
5237 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5238 allowed = true;
5239 break;
5240 }
5241 }
5242 if (!allowed) {
5243 throw new SecurityException("Provider " + pi.packageName
5244 + "/" + pi.name
5245 + " does not allow granting of permission to path of Uri "
5246 + uri);
5247 }
5248 }
5249
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005250 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005252 if (callingUid != Process.myUid()) {
5253 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5254 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5255 throw new SecurityException("Uid " + callingUid
5256 + " does not have permission to uri " + uri);
5257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 }
5259 }
5260
Dianne Hackborn39792d22010-08-19 18:01:52 -07005261 return targetUid;
5262 }
5263
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005264 public int checkGrantUriPermission(int callingUid, String targetPkg,
5265 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005266 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005267 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005268 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005269 }
5270 }
5271
Dianne Hackborn39792d22010-08-19 18:01:52 -07005272 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5273 Uri uri, int modeFlags, UriPermissionOwner owner) {
5274 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5275 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5276 if (modeFlags == 0) {
5277 return;
5278 }
5279
5280 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 // to the uri, and the target doesn't. Let's now give this to
5282 // the target.
5283
Joe Onorato8a9b2202010-02-26 18:56:32 -08005284 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005285 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 HashMap<Uri, UriPermission> targetUris
5288 = mGrantedUriPermissions.get(targetUid);
5289 if (targetUris == null) {
5290 targetUris = new HashMap<Uri, UriPermission>();
5291 mGrantedUriPermissions.put(targetUid, targetUris);
5292 }
5293
5294 UriPermission perm = targetUris.get(uri);
5295 if (perm == null) {
5296 perm = new UriPermission(targetUid, uri);
5297 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005298 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005300 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005301 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005302 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005303 } else {
5304 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5305 perm.readOwners.add(owner);
5306 owner.addReadPermission(perm);
5307 }
5308 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5309 perm.writeOwners.add(owner);
5310 owner.addWritePermission(perm);
5311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
5313 }
5314
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005315 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5316 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005317 if (targetPkg == null) {
5318 throw new NullPointerException("targetPkg");
5319 }
5320
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005321 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005322 if (targetUid < 0) {
5323 return;
5324 }
5325
5326 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5327 }
5328
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005329 static class NeededUriGrants extends ArrayList<Uri> {
5330 final String targetPkg;
5331 final int targetUid;
5332 final int flags;
5333
5334 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5335 targetPkg = _targetPkg;
5336 targetUid = _targetUid;
5337 flags = _flags;
5338 }
5339 }
5340
Dianne Hackborn39792d22010-08-19 18:01:52 -07005341 /**
5342 * Like checkGrantUriPermissionLocked, but takes an Intent.
5343 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005344 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5345 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005346 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005347 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5348 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005349 + " from " + intent + "; flags=0x"
5350 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5351
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005352 if (targetPkg == null) {
5353 throw new NullPointerException("targetPkg");
5354 }
5355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005357 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 }
5359 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005360 ClipData clip = intent.getClipData();
5361 if (data == null && clip == null) {
5362 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005363 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005364 if (data != null) {
5365 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5366 mode, needed != null ? needed.targetUid : -1);
5367 if (target > 0) {
5368 if (needed == null) {
5369 needed = new NeededUriGrants(targetPkg, target, mode);
5370 }
5371 needed.add(data);
5372 }
5373 }
5374 if (clip != null) {
5375 for (int i=0; i<clip.getItemCount(); i++) {
5376 Uri uri = clip.getItemAt(i).getUri();
5377 if (uri != null) {
5378 int target = -1;
5379 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5380 mode, needed != null ? needed.targetUid : -1);
5381 if (target > 0) {
5382 if (needed == null) {
5383 needed = new NeededUriGrants(targetPkg, target, mode);
5384 }
5385 needed.add(uri);
5386 }
5387 } else {
5388 Intent clipIntent = clip.getItemAt(i).getIntent();
5389 if (clipIntent != null) {
5390 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5391 callingUid, targetPkg, clipIntent, mode, needed);
5392 if (newNeeded != null) {
5393 needed = newNeeded;
5394 }
5395 }
5396 }
5397 }
5398 }
5399
5400 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005401 }
5402
5403 /**
5404 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5405 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005406 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5407 UriPermissionOwner owner) {
5408 if (needed != null) {
5409 for (int i=0; i<needed.size(); i++) {
5410 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5411 needed.get(i), needed.flags, owner);
5412 }
5413 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005414 }
5415
5416 void grantUriPermissionFromIntentLocked(int callingUid,
5417 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005418 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005419 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005420 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 return;
5422 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005423
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005424 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 }
5426
5427 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5428 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005429 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 synchronized(this) {
5431 final ProcessRecord r = getRecordForAppLocked(caller);
5432 if (r == null) {
5433 throw new SecurityException("Unable to find app for caller "
5434 + caller
5435 + " when granting permission to uri " + uri);
5436 }
5437 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005438 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 }
5440 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005441 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 }
5443
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005444 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 null);
5446 }
5447 }
5448
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005449 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5451 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5452 HashMap<Uri, UriPermission> perms
5453 = mGrantedUriPermissions.get(perm.uid);
5454 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005455 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005456 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 perms.remove(perm.uri);
5458 if (perms.size() == 0) {
5459 mGrantedUriPermissions.remove(perm.uid);
5460 }
5461 }
5462 }
5463 }
5464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5466 int modeFlags) {
5467 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5468 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5469 if (modeFlags == 0) {
5470 return;
5471 }
5472
Joe Onorato8a9b2202010-02-26 18:56:32 -08005473 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005474 "Revoking all granted permissions to " + uri);
5475
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005476 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477
5478 final String authority = uri.getAuthority();
5479 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005480 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005481 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 if (cpr != null) {
5483 pi = cpr.info;
5484 } else {
5485 try {
5486 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005487 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 } catch (RemoteException ex) {
5489 }
5490 }
5491 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005492 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 return;
5494 }
5495
5496 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005497 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 // Right now, if you are not the original owner of the permission,
5499 // you are not allowed to revoke it.
5500 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5501 throw new SecurityException("Uid " + callingUid
5502 + " does not have permission to uri " + uri);
5503 //}
5504 }
5505
5506 // Go through all of the permissions and remove any that match.
5507 final List<String> SEGMENTS = uri.getPathSegments();
5508 if (SEGMENTS != null) {
5509 final int NS = SEGMENTS.size();
5510 int N = mGrantedUriPermissions.size();
5511 for (int i=0; i<N; i++) {
5512 HashMap<Uri, UriPermission> perms
5513 = mGrantedUriPermissions.valueAt(i);
5514 Iterator<UriPermission> it = perms.values().iterator();
5515 toploop:
5516 while (it.hasNext()) {
5517 UriPermission perm = it.next();
5518 Uri targetUri = perm.uri;
5519 if (!authority.equals(targetUri.getAuthority())) {
5520 continue;
5521 }
5522 List<String> targetSegments = targetUri.getPathSegments();
5523 if (targetSegments == null) {
5524 continue;
5525 }
5526 if (targetSegments.size() < NS) {
5527 continue;
5528 }
5529 for (int j=0; j<NS; j++) {
5530 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5531 continue toploop;
5532 }
5533 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005534 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005535 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 perm.clearModes(modeFlags);
5537 if (perm.modeFlags == 0) {
5538 it.remove();
5539 }
5540 }
5541 if (perms.size() == 0) {
5542 mGrantedUriPermissions.remove(
5543 mGrantedUriPermissions.keyAt(i));
5544 N--;
5545 i--;
5546 }
5547 }
5548 }
5549 }
5550
5551 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5552 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005553 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 synchronized(this) {
5555 final ProcessRecord r = getRecordForAppLocked(caller);
5556 if (r == null) {
5557 throw new SecurityException("Unable to find app for caller "
5558 + caller
5559 + " when revoking permission to uri " + uri);
5560 }
5561 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005562 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 return;
5564 }
5565
5566 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5567 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5568 if (modeFlags == 0) {
5569 return;
5570 }
5571
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005572 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573
5574 final String authority = uri.getAuthority();
5575 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005576 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 if (cpr != null) {
5578 pi = cpr.info;
5579 } else {
5580 try {
5581 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005582 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 } catch (RemoteException ex) {
5584 }
5585 }
5586 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005587 Slog.w(TAG, "No content provider found for permission revoke: "
5588 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 return;
5590 }
5591
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005592 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 }
5594 }
5595
Dianne Hackborn7e269642010-08-25 19:50:20 -07005596 @Override
5597 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005598 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005599 synchronized(this) {
5600 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5601 return owner.getExternalTokenLocked();
5602 }
5603 }
5604
5605 @Override
5606 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5607 Uri uri, int modeFlags) {
5608 synchronized(this) {
5609 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5610 if (owner == null) {
5611 throw new IllegalArgumentException("Unknown owner: " + token);
5612 }
5613 if (fromUid != Binder.getCallingUid()) {
5614 if (Binder.getCallingUid() != Process.myUid()) {
5615 // Only system code can grant URI permissions on behalf
5616 // of other users.
5617 throw new SecurityException("nice try");
5618 }
5619 }
5620 if (targetPkg == null) {
5621 throw new IllegalArgumentException("null target");
5622 }
5623 if (uri == null) {
5624 throw new IllegalArgumentException("null uri");
5625 }
5626
5627 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5628 }
5629 }
5630
5631 @Override
5632 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5633 synchronized(this) {
5634 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5635 if (owner == null) {
5636 throw new IllegalArgumentException("Unknown owner: " + token);
5637 }
5638
5639 if (uri == null) {
5640 owner.removeUriPermissionsLocked(mode);
5641 } else {
5642 owner.removeUriPermissionLocked(uri, mode);
5643 }
5644 }
5645 }
5646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5648 synchronized (this) {
5649 ProcessRecord app =
5650 who != null ? getRecordForAppLocked(who) : null;
5651 if (app == null) return;
5652
5653 Message msg = Message.obtain();
5654 msg.what = WAIT_FOR_DEBUGGER_MSG;
5655 msg.obj = app;
5656 msg.arg1 = waiting ? 1 : 0;
5657 mHandler.sendMessage(msg);
5658 }
5659 }
5660
5661 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005662 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5663 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005665 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005666 outInfo.threshold = homeAppMem;
5667 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5668 outInfo.hiddenAppThreshold = hiddenAppMem;
5669 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005670 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005671 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5672 ProcessList.VISIBLE_APP_ADJ);
5673 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5674 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 }
5676
5677 // =========================================================
5678 // TASK MANAGEMENT
5679 // =========================================================
5680
5681 public List getTasks(int maxNum, int flags,
5682 IThumbnailReceiver receiver) {
5683 ArrayList list = new ArrayList();
5684
5685 PendingThumbnailsRecord pending = null;
5686 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005687 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688
5689 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005690 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5692 + ", receiver=" + receiver);
5693
5694 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5695 != PackageManager.PERMISSION_GRANTED) {
5696 if (receiver != null) {
5697 // If the caller wants to wait for pending thumbnails,
5698 // it ain't gonna get them.
5699 try {
5700 receiver.finished();
5701 } catch (RemoteException ex) {
5702 }
5703 }
5704 String msg = "Permission Denial: getTasks() from pid="
5705 + Binder.getCallingPid()
5706 + ", uid=" + Binder.getCallingUid()
5707 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005708 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 throw new SecurityException(msg);
5710 }
5711
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005712 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005713 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005714 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005715 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 TaskRecord curTask = null;
5717 int numActivities = 0;
5718 int numRunning = 0;
5719 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005720 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005722 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723
5724 // Initialize state for next task if needed.
5725 if (top == null ||
5726 (top.state == ActivityState.INITIALIZING
5727 && top.task == r.task)) {
5728 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 curTask = r.task;
5730 numActivities = numRunning = 0;
5731 }
5732
5733 // Add 'r' into the current task.
5734 numActivities++;
5735 if (r.app != null && r.app.thread != null) {
5736 numRunning++;
5737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738
Joe Onorato8a9b2202010-02-26 18:56:32 -08005739 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 TAG, r.intent.getComponent().flattenToShortString()
5741 + ": task=" + r.task);
5742
5743 // If the next one is a different task, generate a new
5744 // TaskInfo entry for what we have.
5745 if (next == null || next.task != curTask) {
5746 ActivityManager.RunningTaskInfo ci
5747 = new ActivityManager.RunningTaskInfo();
5748 ci.id = curTask.taskId;
5749 ci.baseActivity = r.intent.getComponent();
5750 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005751 if (top.thumbHolder != null) {
5752 ci.description = top.thumbHolder.lastDescription;
5753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 ci.numActivities = numActivities;
5755 ci.numRunning = numRunning;
5756 //System.out.println(
5757 // "#" + maxNum + ": " + " descr=" + ci.description);
5758 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005759 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 TAG, "State=" + top.state + "Idle=" + top.idle
5761 + " app=" + top.app
5762 + " thr=" + (top.app != null ? top.app.thread : null));
5763 if (top.state == ActivityState.RESUMED
5764 || top.state == ActivityState.PAUSING) {
5765 if (top.idle && top.app != null
5766 && top.app.thread != null) {
5767 topRecord = top;
5768 topThumbnail = top.app.thread;
5769 } else {
5770 top.thumbnailNeeded = true;
5771 }
5772 }
5773 if (pending == null) {
5774 pending = new PendingThumbnailsRecord(receiver);
5775 }
5776 pending.pendingRecords.add(top);
5777 }
5778 list.add(ci);
5779 maxNum--;
5780 top = null;
5781 }
5782 }
5783
5784 if (pending != null) {
5785 mPendingThumbnails.add(pending);
5786 }
5787 }
5788
Joe Onorato8a9b2202010-02-26 18:56:32 -08005789 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790
5791 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005792 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005794 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005796 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005797 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 }
5799 }
5800
5801 if (pending == null && receiver != null) {
5802 // In this case all thumbnails were available and the client
5803 // is being asked to be told when the remaining ones come in...
5804 // which is unusually, since the top-most currently running
5805 // activity should never have a canned thumbnail! Oh well.
5806 try {
5807 receiver.finished();
5808 } catch (RemoteException ex) {
5809 }
5810 }
5811
5812 return list;
5813 }
5814
5815 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005816 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005817 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5818 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 synchronized (this) {
5821 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5822 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005823 final boolean detailed = checkCallingPermission(
5824 android.Manifest.permission.GET_DETAILED_TASKS)
5825 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005827 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 final int N = mRecentTasks.size();
5830 ArrayList<ActivityManager.RecentTaskInfo> res
5831 = new ArrayList<ActivityManager.RecentTaskInfo>(
5832 maxNum < N ? maxNum : N);
5833 for (int i=0; i<N && maxNum > 0; i++) {
5834 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005835 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005836 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005837 // Return the entry if desired by the caller. We always return
5838 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005839 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005840 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5841 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005842
Dianne Hackborn905577f2011-09-07 18:31:28 -07005843 if (i == 0
5844 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 || (tr.intent == null)
5846 || ((tr.intent.getFlags()
5847 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5848 ActivityManager.RecentTaskInfo rti
5849 = new ActivityManager.RecentTaskInfo();
5850 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005851 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 rti.baseIntent = new Intent(
5853 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005854 if (!detailed) {
5855 rti.baseIntent.replaceExtras((Bundle)null);
5856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005858 rti.description = tr.lastDescription;
5859
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005860 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5861 // Check whether this activity is currently available.
5862 try {
5863 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005864 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005865 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005866 continue;
5867 }
5868 } else if (rti.baseIntent != null) {
5869 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005870 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005871 continue;
5872 }
5873 }
5874 } catch (RemoteException e) {
5875 // Will never happen.
5876 }
5877 }
5878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 res.add(rti);
5880 maxNum--;
5881 }
5882 }
5883 return res;
5884 }
5885 }
5886
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005887 private TaskRecord taskForIdLocked(int id) {
5888 final int N = mRecentTasks.size();
5889 for (int i=0; i<N; i++) {
5890 TaskRecord tr = mRecentTasks.get(i);
5891 if (tr.taskId == id) {
5892 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005893 }
5894 }
5895 return null;
5896 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005897
5898 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5899 synchronized (this) {
5900 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5901 "getTaskThumbnails()");
5902 TaskRecord tr = taskForIdLocked(id);
5903 if (tr != null) {
5904 return mMainStack.getTaskThumbnailsLocked(tr);
5905 }
5906 }
5907 return null;
5908 }
5909
Dianne Hackborn15491c62012-09-19 10:59:14 -07005910 public Bitmap getTaskTopThumbnail(int id) {
5911 synchronized (this) {
5912 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5913 "getTaskTopThumbnail()");
5914 TaskRecord tr = taskForIdLocked(id);
5915 if (tr != null) {
5916 return mMainStack.getTaskTopThumbnailLocked(tr);
5917 }
5918 }
5919 return null;
5920 }
5921
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005922 public boolean removeSubTask(int taskId, int subTaskIndex) {
5923 synchronized (this) {
5924 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5925 "removeSubTask()");
5926 long ident = Binder.clearCallingIdentity();
5927 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005928 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5929 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005930 } finally {
5931 Binder.restoreCallingIdentity(ident);
5932 }
5933 }
5934 }
5935
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005936 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5937 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005938 Intent baseIntent = new Intent(
5939 tr.intent != null ? tr.intent : tr.affinityIntent);
5940 ComponentName component = baseIntent.getComponent();
5941 if (component == null) {
5942 Slog.w(TAG, "Now component for base intent of task: " + tr);
5943 return;
5944 }
5945
5946 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005947 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005948
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005949 if (killProcesses) {
5950 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005951 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005952 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005953 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5954 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5955 for (int i=0; i<uids.size(); i++) {
5956 ProcessRecord proc = uids.valueAt(i);
5957 if (proc.userId != tr.userId) {
5958 continue;
5959 }
5960 if (!proc.pkgList.contains(pkg)) {
5961 continue;
5962 }
5963 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005964 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005965 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005966
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005967 // Kill the running processes.
5968 for (int i=0; i<procs.size(); i++) {
5969 ProcessRecord pr = procs.get(i);
5970 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5971 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005972 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005973 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005974 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005975 Process.killProcessQuiet(pr.pid);
5976 } else {
5977 pr.waitingToKill = "remove task";
5978 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005979 }
5980 }
5981 }
5982
5983 public boolean removeTask(int taskId, int flags) {
5984 synchronized (this) {
5985 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5986 "removeTask()");
5987 long ident = Binder.clearCallingIdentity();
5988 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005989 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5990 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005991 if (r != null) {
5992 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005993 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005994 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005995 } else {
5996 TaskRecord tr = null;
5997 int i=0;
5998 while (i < mRecentTasks.size()) {
5999 TaskRecord t = mRecentTasks.get(i);
6000 if (t.taskId == taskId) {
6001 tr = t;
6002 break;
6003 }
6004 i++;
6005 }
6006 if (tr != null) {
6007 if (tr.numActivities <= 0) {
6008 // Caller is just removing a recent task that is
6009 // not actively running. That is easy!
6010 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07006011 cleanUpRemovedTaskLocked(tr, flags);
6012 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006013 } else {
6014 Slog.w(TAG, "removeTask: task " + taskId
6015 + " does not have activities to remove, "
6016 + " but numActivities=" + tr.numActivities
6017 + ": " + tr);
6018 }
6019 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006020 }
6021 } finally {
6022 Binder.restoreCallingIdentity(ident);
6023 }
6024 }
6025 return false;
6026 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6029 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006030 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 TaskRecord jt = startTask;
6032
6033 // First look backwards
6034 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006035 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 if (r.task != jt) {
6037 jt = r.task;
6038 if (affinity.equals(jt.affinity)) {
6039 return j;
6040 }
6041 }
6042 }
6043
6044 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006045 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 jt = startTask;
6047 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006048 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 if (r.task != jt) {
6050 if (affinity.equals(jt.affinity)) {
6051 return j;
6052 }
6053 jt = r.task;
6054 }
6055 }
6056
6057 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006058 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 return N-1;
6060 }
6061
6062 return -1;
6063 }
6064
6065 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006066 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006068 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6070 "moveTaskToFront()");
6071
6072 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006073 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6074 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006075 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006076 return;
6077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 final long origId = Binder.clearCallingIdentity();
6079 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006080 TaskRecord tr = taskForIdLocked(task);
6081 if (tr != null) {
6082 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6083 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006085 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6086 // Caller wants the home activity moved with it. To accomplish this,
6087 // we'll just move the home task to the top first.
6088 mMainStack.moveHomeToFrontLocked();
6089 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006090 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006091 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006092 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006093 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6094 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006096 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6097 mMainStack.mUserLeaving = true;
6098 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006099 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6100 // Caller wants the home activity moved with it. To accomplish this,
6101 // we'll just move the home task to the top first.
6102 mMainStack.moveHomeToFrontLocked();
6103 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006104 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 return;
6106 }
6107 }
6108 } finally {
6109 Binder.restoreCallingIdentity(origId);
6110 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006111 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 }
6113 }
6114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 public void moveTaskToBack(int task) {
6116 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6117 "moveTaskToBack()");
6118
6119 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006120 if (mMainStack.mResumedActivity != null
6121 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006122 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6123 Binder.getCallingUid(), "Task to back")) {
6124 return;
6125 }
6126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006128 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 Binder.restoreCallingIdentity(origId);
6130 }
6131 }
6132
6133 /**
6134 * Moves an activity, and all of the other activities within the same task, to the bottom
6135 * of the history stack. The activity's order within the task is unchanged.
6136 *
6137 * @param token A reference to the activity we wish to move
6138 * @param nonRoot If false then this only works if the activity is the root
6139 * of a task; if true it will work for any activity in a task.
6140 * @return Returns true if the move completed, false if not.
6141 */
6142 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006143 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 synchronized(this) {
6145 final long origId = Binder.clearCallingIdentity();
6146 int taskId = getTaskForActivityLocked(token, !nonRoot);
6147 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006148 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
6150 Binder.restoreCallingIdentity(origId);
6151 }
6152 return false;
6153 }
6154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 public void moveTaskBackwards(int task) {
6156 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6157 "moveTaskBackwards()");
6158
6159 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006160 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6161 Binder.getCallingUid(), "Task backwards")) {
6162 return;
6163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 final long origId = Binder.clearCallingIdentity();
6165 moveTaskBackwardsLocked(task);
6166 Binder.restoreCallingIdentity(origId);
6167 }
6168 }
6169
6170 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006171 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 }
6173
6174 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6175 synchronized(this) {
6176 return getTaskForActivityLocked(token, onlyRoot);
6177 }
6178 }
6179
6180 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006181 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 TaskRecord lastTask = null;
6183 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006184 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006185 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 if (!onlyRoot || lastTask != r.task) {
6187 return r.task.taskId;
6188 }
6189 return -1;
6190 }
6191 lastTask = r.task;
6192 }
6193
6194 return -1;
6195 }
6196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 // =========================================================
6198 // THUMBNAILS
6199 // =========================================================
6200
6201 public void reportThumbnail(IBinder token,
6202 Bitmap thumbnail, CharSequence description) {
6203 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6204 final long origId = Binder.clearCallingIdentity();
6205 sendPendingThumbnail(null, token, thumbnail, description, true);
6206 Binder.restoreCallingIdentity(origId);
6207 }
6208
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006209 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 Bitmap thumbnail, CharSequence description, boolean always) {
6211 TaskRecord task = null;
6212 ArrayList receivers = null;
6213
6214 //System.out.println("Send pending thumbnail: " + r);
6215
6216 synchronized(this) {
6217 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006218 r = mMainStack.isInStackLocked(token);
6219 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 return;
6221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006223 if (thumbnail == null && r.thumbHolder != null) {
6224 thumbnail = r.thumbHolder.lastThumbnail;
6225 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 }
6227 if (thumbnail == null && !always) {
6228 // If there is no thumbnail, and this entry is not actually
6229 // going away, then abort for now and pick up the next
6230 // thumbnail we get.
6231 return;
6232 }
6233 task = r.task;
6234
6235 int N = mPendingThumbnails.size();
6236 int i=0;
6237 while (i<N) {
6238 PendingThumbnailsRecord pr =
6239 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6240 //System.out.println("Looking in " + pr.pendingRecords);
6241 if (pr.pendingRecords.remove(r)) {
6242 if (receivers == null) {
6243 receivers = new ArrayList();
6244 }
6245 receivers.add(pr);
6246 if (pr.pendingRecords.size() == 0) {
6247 pr.finished = true;
6248 mPendingThumbnails.remove(i);
6249 N--;
6250 continue;
6251 }
6252 }
6253 i++;
6254 }
6255 }
6256
6257 if (receivers != null) {
6258 final int N = receivers.size();
6259 for (int i=0; i<N; i++) {
6260 try {
6261 PendingThumbnailsRecord pr =
6262 (PendingThumbnailsRecord)receivers.get(i);
6263 pr.receiver.newThumbnail(
6264 task != null ? task.taskId : -1, thumbnail, description);
6265 if (pr.finished) {
6266 pr.receiver.finished();
6267 }
6268 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006269 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 }
6271 }
6272 }
6273 }
6274
6275 // =========================================================
6276 // CONTENT PROVIDERS
6277 // =========================================================
6278
Jeff Brown10e89712011-07-08 18:52:57 -07006279 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6280 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006282 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006283 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006284 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 } catch (RemoteException ex) {
6286 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006287 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006288 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6289 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006291 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 for (int i=0; i<N; i++) {
6293 ProviderInfo cpi =
6294 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006295 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6296 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006297 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006298 // This is a singleton provider, but a user besides the
6299 // default user is asking to initialize a process it runs
6300 // in... well, no, it doesn't actually run in this process,
6301 // it runs in the process of the default user. Get rid of it.
6302 providers.remove(i);
6303 N--;
6304 continue;
6305 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006306
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006307 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006308 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006310 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006311 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006313 if (DEBUG_MU)
6314 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 app.pubProviders.put(cpi.name, cpr);
6316 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006317 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 }
6319 }
6320 return providers;
6321 }
6322
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006323 /**
6324 * Check if {@link ProcessRecord} has a possible chance at accessing the
6325 * given {@link ProviderInfo}. Final permission checking is always done
6326 * in {@link ContentProvider}.
6327 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006329 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006331 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006333 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006334 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 return null;
6336 }
6337 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006338 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 == PackageManager.PERMISSION_GRANTED) {
6340 return null;
6341 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006342
6343 PathPermission[] pps = cpi.pathPermissions;
6344 if (pps != null) {
6345 int i = pps.length;
6346 while (i > 0) {
6347 i--;
6348 PathPermission pp = pps[i];
6349 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006350 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006351 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006352 return null;
6353 }
6354 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006355 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006356 == PackageManager.PERMISSION_GRANTED) {
6357 return null;
6358 }
6359 }
6360 }
6361
Dianne Hackbornb424b632010-08-18 15:59:05 -07006362 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6363 if (perms != null) {
6364 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6365 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6366 return null;
6367 }
6368 }
6369 }
6370
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006371 String msg;
6372 if (!cpi.exported) {
6373 msg = "Permission Denial: opening provider " + cpi.name
6374 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6375 + ", uid=" + callingUid + ") that is not exported from uid "
6376 + cpi.applicationInfo.uid;
6377 } else {
6378 msg = "Permission Denial: opening provider " + cpi.name
6379 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6380 + ", uid=" + callingUid + ") requires "
6381 + cpi.readPermission + " or " + cpi.writePermission;
6382 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006383 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 return msg;
6385 }
6386
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006387 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6388 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006389 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006390 for (int i=0; i<r.conProviders.size(); i++) {
6391 ContentProviderConnection conn = r.conProviders.get(i);
6392 if (conn.provider == cpr) {
6393 if (DEBUG_PROVIDER) Slog.v(TAG,
6394 "Adding provider requested by "
6395 + r.processName + " from process "
6396 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6397 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6398 if (stable) {
6399 conn.stableCount++;
6400 conn.numStableIncs++;
6401 } else {
6402 conn.unstableCount++;
6403 conn.numUnstableIncs++;
6404 }
6405 return conn;
6406 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006407 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006408 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6409 if (stable) {
6410 conn.stableCount = 1;
6411 conn.numStableIncs = 1;
6412 } else {
6413 conn.unstableCount = 1;
6414 conn.numUnstableIncs = 1;
6415 }
6416 cpr.connections.add(conn);
6417 r.conProviders.add(conn);
6418 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006419 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006420 cpr.addExternalProcessHandleLocked(externalProcessToken);
6421 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006422 }
6423
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006424 boolean decProviderCountLocked(ContentProviderConnection conn,
6425 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6426 if (conn != null) {
6427 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006428 if (DEBUG_PROVIDER) Slog.v(TAG,
6429 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006430 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006431 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006432 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6433 if (stable) {
6434 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006435 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006436 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006437 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006438 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6439 cpr.connections.remove(conn);
6440 conn.client.conProviders.remove(conn);
6441 return true;
6442 }
6443 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006444 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006445 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006446 return false;
6447 }
6448
Amith Yamasani742a6712011-05-04 14:49:28 -07006449 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006450 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006452 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 ProviderInfo cpi = null;
6454
6455 synchronized(this) {
6456 ProcessRecord r = null;
6457 if (caller != null) {
6458 r = getRecordForAppLocked(caller);
6459 if (r == null) {
6460 throw new SecurityException(
6461 "Unable to find app for caller " + caller
6462 + " (pid=" + Binder.getCallingPid()
6463 + ") when getting content provider " + name);
6464 }
6465 }
6466
6467 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006468 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006469 boolean providerRunning = cpr != null;
6470 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006472 String msg;
6473 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6474 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 }
6476
6477 if (r != null && cpr.canRunHere(r)) {
6478 // This provider has been published or is in the process
6479 // of being published... but it is also allowed to run
6480 // in the caller's process, so don't make a connection
6481 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006482 ContentProviderHolder holder = cpr.newHolder(null);
6483 // don't give caller the provider object, it needs
6484 // to make its own.
6485 holder.provider = null;
6486 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
6489 final long origId = Binder.clearCallingIdentity();
6490
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006491 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006493 conn = incProviderCountLocked(r, cpr, token, stable);
6494 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006495 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006496 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006497 // make sure to count it as being accessed and thus
6498 // back up on the LRU list. This is good because
6499 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006500 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006501 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006502 }
6503
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006504 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006505 if (false) {
6506 if (cpr.name.flattenToShortString().equals(
6507 "com.android.providers.calendar/.CalendarProvider2")) {
6508 Slog.v(TAG, "****************** KILLING "
6509 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006510 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006511 }
6512 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006513 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006514 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6515 // NOTE: there is still a race here where a signal could be
6516 // pending on the process even though we managed to update its
6517 // adj level. Not sure what to do about this, but at least
6518 // the race is now smaller.
6519 if (!success) {
6520 // Uh oh... it looks like the provider's process
6521 // has been killed on us. We need to wait for a new
6522 // process to be started, and make sure its death
6523 // doesn't kill our process.
6524 Slog.i(TAG,
6525 "Existing provider " + cpr.name.flattenToShortString()
6526 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006527 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006528 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006529 if (!lastRef) {
6530 // This wasn't the last ref our process had on
6531 // the provider... we have now been killed, bail.
6532 return null;
6533 }
6534 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006535 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 }
6538
6539 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006542 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006543 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006545 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006546 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006547 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 } catch (RemoteException ex) {
6549 }
6550 if (cpi == null) {
6551 return null;
6552 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006553 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6554 cpi.name, cpi.flags);
6555 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006556 userId = 0;
6557 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006558 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006559
Dianne Hackbornb424b632010-08-18 15:59:05 -07006560 String msg;
6561 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6562 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 }
6564
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006565 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006566 && !cpi.processName.equals("system")) {
6567 // If this content provider does not run in the system
6568 // process, and the system is not yet ready to run other
6569 // processes, then fail fast instead of hanging.
6570 throw new IllegalArgumentException(
6571 "Attempt to launch content provider before system ready");
6572 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006573
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006574 // Make sure that the user who owns this provider is started. If not,
6575 // we don't want to allow it to run.
6576 if (mStartedUsers.get(userId) == null) {
6577 Slog.w(TAG, "Unable to launch app "
6578 + cpi.applicationInfo.packageName + "/"
6579 + cpi.applicationInfo.uid + " for provider "
6580 + name + ": user " + userId + " is stopped");
6581 return null;
6582 }
6583
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006584 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006585 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 final boolean firstClass = cpr == null;
6587 if (firstClass) {
6588 try {
6589 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006590 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 getApplicationInfo(
6592 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006593 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006595 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 + cpi.name);
6597 return null;
6598 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006599 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006600 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 } catch (RemoteException ex) {
6602 // pm is in same process, this will never happen.
6603 }
6604 }
6605
6606 if (r != null && cpr.canRunHere(r)) {
6607 // If this is a multiprocess provider, then just return its
6608 // info and allow the caller to instantiate it. Only do
6609 // this if the provider is the same user as the caller's
6610 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006611 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 }
6613
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006614 if (DEBUG_PROVIDER) {
6615 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006616 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006617 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619
6620 // This is single process, and our app is now connecting to it.
6621 // See if we are already in the process of launching this
6622 // provider.
6623 final int N = mLaunchingProviders.size();
6624 int i;
6625 for (i=0; i<N; i++) {
6626 if (mLaunchingProviders.get(i) == cpr) {
6627 break;
6628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 }
6630
6631 // If the provider is not already being launched, then get it
6632 // started.
6633 if (i >= N) {
6634 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006635
6636 try {
6637 // Content provider is now in use, its package can't be stopped.
6638 try {
6639 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006640 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006641 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006642 } catch (IllegalArgumentException e) {
6643 Slog.w(TAG, "Failed trying to unstop package "
6644 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006645 }
6646
6647 ProcessRecord proc = startProcessLocked(cpi.processName,
6648 cpr.appInfo, false, 0, "content provider",
6649 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006650 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006651 if (proc == null) {
6652 Slog.w(TAG, "Unable to launch app "
6653 + cpi.applicationInfo.packageName + "/"
6654 + cpi.applicationInfo.uid + " for provider "
6655 + name + ": process is bad");
6656 return null;
6657 }
6658 cpr.launchingApp = proc;
6659 mLaunchingProviders.add(cpr);
6660 } finally {
6661 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 }
6664
6665 // Make sure the provider is published (the same provider class
6666 // may be published under multiple names).
6667 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006668 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006670
Amith Yamasani742a6712011-05-04 14:49:28 -07006671 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006672 conn = incProviderCountLocked(r, cpr, token, stable);
6673 if (conn != null) {
6674 conn.waiting = true;
6675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 }
6677 }
6678
6679 // Wait for the provider to be published...
6680 synchronized (cpr) {
6681 while (cpr.provider == null) {
6682 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006683 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 + cpi.applicationInfo.packageName + "/"
6685 + cpi.applicationInfo.uid + " for provider "
6686 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006687 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006688 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 cpi.applicationInfo.packageName,
6690 cpi.applicationInfo.uid, name);
6691 return null;
6692 }
6693 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006694 if (DEBUG_MU) {
6695 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6696 + cpr.launchingApp);
6697 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006698 if (conn != null) {
6699 conn.waiting = true;
6700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 cpr.wait();
6702 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006703 } finally {
6704 if (conn != null) {
6705 conn.waiting = false;
6706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 }
6708 }
6709 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006710 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 }
6712
6713 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006714 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006715 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 if (caller == null) {
6717 String msg = "null IApplicationThread when getting content provider "
6718 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006719 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 throw new SecurityException(msg);
6721 }
6722
Dianne Hackborn139748f2012-09-24 11:36:57 -07006723 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006724 false, true, "getContentProvider", null);
6725 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 }
6727
Jeff Sharkey6d515712012-09-20 16:06:08 -07006728 public ContentProviderHolder getContentProviderExternal(
6729 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006730 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6731 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006732 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006733 false, true, "getContentProvider", null);
6734 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006735 }
6736
Dianne Hackborn41203752012-08-31 14:05:51 -07006737 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6738 IBinder token, int userId) {
6739 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 }
6741
6742 /**
6743 * Drop a content provider from a ProcessRecord's bookkeeping
6744 * @param cpr
6745 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006746 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006747 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006749 ContentProviderConnection conn;
6750 try {
6751 conn = (ContentProviderConnection)connection;
6752 } catch (ClassCastException e) {
6753 String msg ="removeContentProvider: " + connection
6754 + " not a ContentProviderConnection";
6755 Slog.w(TAG, msg);
6756 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006758 if (conn == null) {
6759 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006761 if (decProviderCountLocked(conn, null, null, stable)) {
6762 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 }
6765 }
6766
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006767 public void removeContentProviderExternal(String name, IBinder token) {
6768 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6769 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006770 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006771 }
6772
Dianne Hackborn41203752012-08-31 14:05:51 -07006773 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006775 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 if(cpr == null) {
6777 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006778 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 return;
6780 }
6781
6782 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006783 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006784 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006785 if (localCpr.hasExternalProcessHandles()) {
6786 if (localCpr.removeExternalProcessHandleLocked(token)) {
6787 updateOomAdjLocked();
6788 } else {
6789 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6790 + " with no external reference for token: "
6791 + token + ".");
6792 }
6793 } else {
6794 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6795 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 }
6798 }
6799
6800 public final void publishContentProviders(IApplicationThread caller,
6801 List<ContentProviderHolder> providers) {
6802 if (providers == null) {
6803 return;
6804 }
6805
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006806 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006807 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006808 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006809 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006810 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 if (r == null) {
6812 throw new SecurityException(
6813 "Unable to find app for caller " + caller
6814 + " (pid=" + Binder.getCallingPid()
6815 + ") when publishing content providers");
6816 }
6817
6818 final long origId = Binder.clearCallingIdentity();
6819
6820 final int N = providers.size();
6821 for (int i=0; i<N; i++) {
6822 ContentProviderHolder src = providers.get(i);
6823 if (src == null || src.info == null || src.provider == null) {
6824 continue;
6825 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006826 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006827 if (DEBUG_MU)
6828 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006830 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006831 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 String names[] = dst.info.authority.split(";");
6833 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006834 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 }
6836
6837 int NL = mLaunchingProviders.size();
6838 int j;
6839 for (j=0; j<NL; j++) {
6840 if (mLaunchingProviders.get(j) == dst) {
6841 mLaunchingProviders.remove(j);
6842 j--;
6843 NL--;
6844 }
6845 }
6846 synchronized (dst) {
6847 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006848 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 dst.notifyAll();
6850 }
6851 updateOomAdjLocked(r);
6852 }
6853 }
6854
6855 Binder.restoreCallingIdentity(origId);
6856 }
6857 }
6858
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006859 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6860 ContentProviderConnection conn;
6861 try {
6862 conn = (ContentProviderConnection)connection;
6863 } catch (ClassCastException e) {
6864 String msg ="refContentProvider: " + connection
6865 + " not a ContentProviderConnection";
6866 Slog.w(TAG, msg);
6867 throw new IllegalArgumentException(msg);
6868 }
6869 if (conn == null) {
6870 throw new NullPointerException("connection is null");
6871 }
6872
6873 synchronized (this) {
6874 if (stable > 0) {
6875 conn.numStableIncs += stable;
6876 }
6877 stable = conn.stableCount + stable;
6878 if (stable < 0) {
6879 throw new IllegalStateException("stableCount < 0: " + stable);
6880 }
6881
6882 if (unstable > 0) {
6883 conn.numUnstableIncs += unstable;
6884 }
6885 unstable = conn.unstableCount + unstable;
6886 if (unstable < 0) {
6887 throw new IllegalStateException("unstableCount < 0: " + unstable);
6888 }
6889
6890 if ((stable+unstable) <= 0) {
6891 throw new IllegalStateException("ref counts can't go to zero here: stable="
6892 + stable + " unstable=" + unstable);
6893 }
6894 conn.stableCount = stable;
6895 conn.unstableCount = unstable;
6896 return !conn.dead;
6897 }
6898 }
6899
6900 public void unstableProviderDied(IBinder connection) {
6901 ContentProviderConnection conn;
6902 try {
6903 conn = (ContentProviderConnection)connection;
6904 } catch (ClassCastException e) {
6905 String msg ="refContentProvider: " + connection
6906 + " not a ContentProviderConnection";
6907 Slog.w(TAG, msg);
6908 throw new IllegalArgumentException(msg);
6909 }
6910 if (conn == null) {
6911 throw new NullPointerException("connection is null");
6912 }
6913
6914 // Safely retrieve the content provider associated with the connection.
6915 IContentProvider provider;
6916 synchronized (this) {
6917 provider = conn.provider.provider;
6918 }
6919
6920 if (provider == null) {
6921 // Um, yeah, we're way ahead of you.
6922 return;
6923 }
6924
6925 // Make sure the caller is being honest with us.
6926 if (provider.asBinder().pingBinder()) {
6927 // Er, no, still looks good to us.
6928 synchronized (this) {
6929 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6930 + " says " + conn + " died, but we don't agree");
6931 return;
6932 }
6933 }
6934
6935 // Well look at that! It's dead!
6936 synchronized (this) {
6937 if (conn.provider.provider != provider) {
6938 // But something changed... good enough.
6939 return;
6940 }
6941
6942 ProcessRecord proc = conn.provider.proc;
6943 if (proc == null || proc.thread == null) {
6944 // Seems like the process is already cleaned up.
6945 return;
6946 }
6947
6948 // As far as we're concerned, this is just like receiving a
6949 // death notification... just a bit prematurely.
6950 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6951 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006952 final long ident = Binder.clearCallingIdentity();
6953 try {
6954 appDiedLocked(proc, proc.pid, proc.thread);
6955 } finally {
6956 Binder.restoreCallingIdentity(ident);
6957 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006958 }
6959 }
6960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006961 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006962 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006963 synchronized (mSelf) {
6964 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6965 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006966 if (providers != null) {
6967 for (int i=providers.size()-1; i>=0; i--) {
6968 ProviderInfo pi = (ProviderInfo)providers.get(i);
6969 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6970 Slog.w(TAG, "Not installing system proc provider " + pi.name
6971 + ": not system .apk");
6972 providers.remove(i);
6973 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006974 }
6975 }
6976 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006977 if (providers != null) {
6978 mSystemThread.installSystemProviders(providers);
6979 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006980
6981 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006982
6983 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006984 }
6985
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006986 /**
6987 * Allows app to retrieve the MIME type of a URI without having permission
6988 * to access its content provider.
6989 *
6990 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6991 *
6992 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6993 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6994 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006995 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006996 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006997 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006998 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006999 final String name = uri.getAuthority();
7000 final long ident = Binder.clearCallingIdentity();
7001 ContentProviderHolder holder = null;
7002
7003 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07007004 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007005 if (holder != null) {
7006 return holder.provider.getType(uri);
7007 }
7008 } catch (RemoteException e) {
7009 Log.w(TAG, "Content provider dead retrieving " + uri, e);
7010 return null;
7011 } finally {
7012 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07007013 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007014 }
7015 Binder.restoreCallingIdentity(ident);
7016 }
7017
7018 return null;
7019 }
7020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 // =========================================================
7022 // GLOBAL MANAGEMENT
7023 // =========================================================
7024
7025 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007026 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 String proc = customProcess != null ? customProcess : info.processName;
7028 BatteryStatsImpl.Uid.Proc ps = null;
7029 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007030 int uid = info.uid;
7031 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007032 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007033 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7034 uid = 0;
7035 while (true) {
7036 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7037 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7038 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7039 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007040 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007041 mNextIsolatedProcessUid++;
7042 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7043 // No process for this uid, use it.
7044 break;
7045 }
7046 stepsLeft--;
7047 if (stepsLeft <= 0) {
7048 return null;
7049 }
7050 }
7051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 synchronized (stats) {
7053 ps = stats.getProcessStatsLocked(info.uid, proc);
7054 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007055 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 }
7057
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007058 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7059 ProcessRecord app;
7060 if (!isolated) {
7061 app = getProcessRecordLocked(info.processName, info.uid);
7062 } else {
7063 app = null;
7064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065
7066 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007067 app = newProcessRecordLocked(null, info, null, isolated);
7068 mProcessNames.put(info.processName, app.uid, app);
7069 if (isolated) {
7070 mIsolatedProcesses.put(app.uid, app);
7071 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007072 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 }
7074
Dianne Hackborne7f97212011-02-24 14:40:20 -08007075 // This package really, really can not be stopped.
7076 try {
7077 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007078 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007079 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007080 } catch (IllegalArgumentException e) {
7081 Slog.w(TAG, "Failed trying to unstop package "
7082 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007083 }
7084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7086 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7087 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007088 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 }
7090 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7091 mPersistentStartingProcesses.add(app);
7092 startProcessLocked(app, "added application", app.processName);
7093 }
7094
7095 return app;
7096 }
7097
7098 public void unhandledBack() {
7099 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7100 "unhandledBack()");
7101
7102 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007103 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007104 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 TAG, "Performing unhandledBack(): stack size = " + count);
7106 if (count > 1) {
7107 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007108 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007109 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 Binder.restoreCallingIdentity(origId);
7111 }
7112 }
7113 }
7114
7115 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007116 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007117 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007119 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 ParcelFileDescriptor pfd = null;
7121 if (cph != null) {
7122 // We record the binder invoker's uid in thread-local storage before
7123 // going to the content provider to open the file. Later, in the code
7124 // that handles all permissions checks, we look for this uid and use
7125 // that rather than the Activity Manager's own uid. The effect is that
7126 // we do the check against the caller's permissions even though it looks
7127 // to the content provider like the Activity Manager itself is making
7128 // the request.
7129 sCallerIdentity.set(new Identity(
7130 Binder.getCallingPid(), Binder.getCallingUid()));
7131 try {
Dianne Hackborn35654b62013-01-14 17:38:02 -08007132 pfd = cph.provider.openFile(null, uri, "r");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 } catch (FileNotFoundException e) {
7134 // do nothing; pfd will be returned null
7135 } finally {
7136 // Ensure that whatever happens, we clean up the identity state
7137 sCallerIdentity.remove();
7138 }
7139
7140 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007141 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007143 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007144 }
7145 return pfd;
7146 }
7147
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007148 // Actually is sleeping or shutting down or whatever else in the future
7149 // is an inactive state.
7150 public boolean isSleeping() {
7151 return mSleeping || mShuttingDown;
7152 }
7153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007155 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7156 != PackageManager.PERMISSION_GRANTED) {
7157 throw new SecurityException("Requires permission "
7158 + android.Manifest.permission.DEVICE_POWER);
7159 }
7160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007162 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007163 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007165 if (!mSleeping) {
7166 mSleeping = true;
7167 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007168
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007169 // Initialize the wake times of all processes.
7170 checkExcessivePowerUsageLocked(false);
7171 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7172 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7173 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 }
7176 }
7177
Dianne Hackborn55280a92009-05-07 15:53:46 -07007178 public boolean shutdown(int timeout) {
7179 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7180 != PackageManager.PERMISSION_GRANTED) {
7181 throw new SecurityException("Requires permission "
7182 + android.Manifest.permission.SHUTDOWN);
7183 }
7184
7185 boolean timedout = false;
7186
7187 synchronized(this) {
7188 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007189 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007190
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007191 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007192 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007193 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007194 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007195 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007196 long delay = endTime - System.currentTimeMillis();
7197 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007198 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007199 timedout = true;
7200 break;
7201 }
7202 try {
7203 this.wait();
7204 } catch (InterruptedException e) {
7205 }
7206 }
7207 }
7208 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007209
7210 mAppOpsService.shutdown();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007211 mUsageStatsService.shutdown();
7212 mBatteryStatsService.shutdown();
7213
7214 return timedout;
7215 }
7216
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007217 public final void activitySlept(IBinder token) {
7218 if (localLOGV) Slog.v(
7219 TAG, "Activity slept: token=" + token);
7220
7221 ActivityRecord r = null;
7222
7223 final long origId = Binder.clearCallingIdentity();
7224
7225 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007226 r = mMainStack.isInStackLocked(token);
7227 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007228 mMainStack.activitySleptLocked(r);
7229 }
7230 }
7231
7232 Binder.restoreCallingIdentity(origId);
7233 }
7234
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007235 private void comeOutOfSleepIfNeededLocked() {
7236 if (!mWentToSleep && !mLockScreenShown) {
7237 if (mSleeping) {
7238 mSleeping = false;
7239 mMainStack.awakeFromSleepingLocked();
7240 mMainStack.resumeTopActivityLocked(null);
7241 }
7242 }
7243 }
7244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007246 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7247 != PackageManager.PERMISSION_GRANTED) {
7248 throw new SecurityException("Requires permission "
7249 + android.Manifest.permission.DEVICE_POWER);
7250 }
7251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007253 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007254 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007255 comeOutOfSleepIfNeededLocked();
7256 }
7257 }
7258
Jeff Brownc042ee22012-05-08 13:03:42 -07007259 private void updateEventDispatchingLocked() {
7260 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7261 }
7262
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007263 public void setLockScreenShown(boolean shown) {
7264 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7265 != PackageManager.PERMISSION_GRANTED) {
7266 throw new SecurityException("Requires permission "
7267 + android.Manifest.permission.DEVICE_POWER);
7268 }
7269
7270 synchronized(this) {
7271 mLockScreenShown = shown;
7272 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 }
7274 }
7275
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007276 public void stopAppSwitches() {
7277 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7278 != PackageManager.PERMISSION_GRANTED) {
7279 throw new SecurityException("Requires permission "
7280 + android.Manifest.permission.STOP_APP_SWITCHES);
7281 }
7282
7283 synchronized(this) {
7284 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7285 + APP_SWITCH_DELAY_TIME;
7286 mDidAppSwitch = false;
7287 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7288 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7289 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7290 }
7291 }
7292
7293 public void resumeAppSwitches() {
7294 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7295 != PackageManager.PERMISSION_GRANTED) {
7296 throw new SecurityException("Requires permission "
7297 + android.Manifest.permission.STOP_APP_SWITCHES);
7298 }
7299
7300 synchronized(this) {
7301 // Note that we don't execute any pending app switches... we will
7302 // let those wait until either the timeout, or the next start
7303 // activity request.
7304 mAppSwitchesAllowedTime = 0;
7305 }
7306 }
7307
7308 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7309 String name) {
7310 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7311 return true;
7312 }
7313
7314 final int perm = checkComponentPermission(
7315 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007316 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007317 if (perm == PackageManager.PERMISSION_GRANTED) {
7318 return true;
7319 }
7320
Joe Onorato8a9b2202010-02-26 18:56:32 -08007321 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007322 return false;
7323 }
7324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 public void setDebugApp(String packageName, boolean waitForDebugger,
7326 boolean persistent) {
7327 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7328 "setDebugApp()");
7329
7330 // Note that this is not really thread safe if there are multiple
7331 // callers into it at the same time, but that's not a situation we
7332 // care about.
7333 if (persistent) {
7334 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007335 Settings.Global.putString(
7336 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007338 Settings.Global.putInt(
7339 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 waitForDebugger ? 1 : 0);
7341 }
7342
7343 synchronized (this) {
7344 if (!persistent) {
7345 mOrigDebugApp = mDebugApp;
7346 mOrigWaitForDebugger = mWaitForDebugger;
7347 }
7348 mDebugApp = packageName;
7349 mWaitForDebugger = waitForDebugger;
7350 mDebugTransient = !persistent;
7351 if (packageName != null) {
7352 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007353 forceStopPackageLocked(packageName, -1, false, false, true, true,
7354 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 Binder.restoreCallingIdentity(origId);
7356 }
7357 }
7358 }
7359
Siva Velusamy92a8b222012-03-09 16:24:04 -08007360 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7361 synchronized (this) {
7362 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7363 if (!isDebuggable) {
7364 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7365 throw new SecurityException("Process not debuggable: " + app.packageName);
7366 }
7367 }
7368
7369 mOpenGlTraceApp = processName;
7370 }
7371 }
7372
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007373 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7374 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7375 synchronized (this) {
7376 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7377 if (!isDebuggable) {
7378 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7379 throw new SecurityException("Process not debuggable: " + app.packageName);
7380 }
7381 }
7382 mProfileApp = processName;
7383 mProfileFile = profileFile;
7384 if (mProfileFd != null) {
7385 try {
7386 mProfileFd.close();
7387 } catch (IOException e) {
7388 }
7389 mProfileFd = null;
7390 }
7391 mProfileFd = profileFd;
7392 mProfileType = 0;
7393 mAutoStopProfiler = autoStopProfiler;
7394 }
7395 }
7396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 public void setAlwaysFinish(boolean enabled) {
7398 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7399 "setAlwaysFinish()");
7400
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007401 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007403 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404
7405 synchronized (this) {
7406 mAlwaysFinishActivities = enabled;
7407 }
7408 }
7409
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007410 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007412 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007414 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 }
7416 }
7417
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007418 public boolean isUserAMonkey() {
7419 // For now the fact that there is a controller implies
7420 // we have a monkey.
7421 synchronized (this) {
7422 return mController != null;
7423 }
7424 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007425
7426 public void requestBugReport() {
7427 // No permission check because this can't do anything harmful --
7428 // it will just eventually cause the user to be presented with
7429 // a UI to select where the bug report goes.
7430 SystemProperties.set("ctl.start", "bugreport");
7431 }
7432
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007433 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7434 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7435 != PackageManager.PERMISSION_GRANTED) {
7436 throw new SecurityException("Requires permission "
7437 + android.Manifest.permission.FILTER_EVENTS);
7438 }
7439
7440 ProcessRecord proc;
7441
7442 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7443 synchronized (this) {
7444 synchronized (mPidsSelfLocked) {
7445 proc = mPidsSelfLocked.get(pid);
7446 }
7447 if (proc != null) {
7448 if (proc.debugging) {
7449 return -1;
7450 }
7451
7452 if (mDidDexOpt) {
7453 // Give more time since we were dexopting.
7454 mDidDexOpt = false;
7455 return -1;
7456 }
7457
7458 if (proc.instrumentationClass != null) {
7459 Bundle info = new Bundle();
7460 info.putString("shortMsg", "keyDispatchingTimedOut");
7461 info.putString("longMsg", "Timed out while dispatching key event");
7462 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7463 proc = null;
7464 }
7465 }
7466 }
7467
7468 if (proc != null) {
7469 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7470 if (proc.instrumentationClass != null || proc.usingWrapper) {
7471 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7472 }
7473 }
7474
7475 return KEY_DISPATCHING_TIMEOUT;
7476 }
7477
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08007478 public Bundle getTopActivityExtras(int requestType) {
7479 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
7480 "getTopActivityExtras()");
7481 PendingActivityExtras pae;
7482 Bundle extras = new Bundle();
7483 synchronized (this) {
7484 ActivityRecord activity = mMainStack.mResumedActivity;
7485 if (activity == null) {
7486 Slog.w(TAG, "getTopActivityExtras failed: no resumed activity");
7487 return null;
7488 }
7489 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
7490 if (activity.app == null || activity.app.thread == null) {
7491 Slog.w(TAG, "getTopActivityExtras failed: no process for " + activity);
7492 return extras;
7493 }
7494 if (activity.app.pid == Binder.getCallingPid()) {
7495 Slog.w(TAG, "getTopActivityExtras failed: request process same as " + activity);
7496 return extras;
7497 }
7498 pae = new PendingActivityExtras(activity);
7499 try {
7500 activity.app.thread.requestActivityExtras(activity.appToken, pae, requestType);
7501 mPendingActivityExtras.add(pae);
7502 mHandler.postDelayed(pae, PENDING_ACTIVITY_RESULT_TIMEOUT);
7503 } catch (RemoteException e) {
7504 Slog.w(TAG, "getTopActivityExtras failed: crash calling " + activity);
7505 return extras;
7506 }
7507 }
7508 synchronized (pae) {
7509 while (!pae.haveResult) {
7510 try {
7511 pae.wait();
7512 } catch (InterruptedException e) {
7513 }
7514 }
7515 if (pae.result != null) {
7516 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
7517 }
7518 }
7519 synchronized (this) {
7520 mPendingActivityExtras.remove(pae);
7521 mHandler.removeCallbacks(pae);
7522 }
7523 return extras;
7524 }
7525
7526 public void reportTopActivityExtras(IBinder token, Bundle extras) {
7527 PendingActivityExtras pae = (PendingActivityExtras)token;
7528 synchronized (pae) {
7529 pae.result = extras;
7530 pae.haveResult = true;
7531 pae.notifyAll();
7532 }
7533 }
7534
Jeff Sharkeya4620792011-05-20 15:29:23 -07007535 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007536 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7537 "registerProcessObserver()");
7538 synchronized (this) {
7539 mProcessObservers.register(observer);
7540 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007541 }
7542
7543 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007544 synchronized (this) {
7545 mProcessObservers.unregister(observer);
7546 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007547 }
7548
Daniel Sandler69a48172010-06-23 16:29:36 -04007549 public void setImmersive(IBinder token, boolean immersive) {
7550 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007551 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007552 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007553 throw new IllegalArgumentException();
7554 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007555 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007556
7557 // update associated state if we're frontmost
7558 if (r == mFocusedActivity) {
7559 if (DEBUG_IMMERSIVE) {
7560 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7561 }
7562 applyUpdateLockStateLocked(r);
7563 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007564 }
7565 }
7566
7567 public boolean isImmersive(IBinder token) {
7568 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007569 ActivityRecord r = mMainStack.isInStackLocked(token);
7570 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007571 throw new IllegalArgumentException();
7572 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007573 return r.immersive;
7574 }
7575 }
7576
7577 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007578 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007579 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007580 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007581 return (r != null) ? r.immersive : false;
7582 }
7583 }
7584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 public final void enterSafeMode() {
7586 synchronized(this) {
7587 // It only makes sense to do this before the system is ready
7588 // and started launching other packages.
7589 if (!mSystemReady) {
7590 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007591 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 } catch (RemoteException e) {
7593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 }
7595 }
7596 }
7597
Jeff Brownb09abc12011-01-13 21:08:27 -08007598 public final void showSafeModeOverlay() {
7599 View v = LayoutInflater.from(mContext).inflate(
7600 com.android.internal.R.layout.safe_mode, null);
7601 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7602 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7603 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7604 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007605 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007606 lp.format = v.getBackground().getOpacity();
7607 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7608 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007609 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007610 ((WindowManager)mContext.getSystemService(
7611 Context.WINDOW_SERVICE)).addView(v, lp);
7612 }
7613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 public void noteWakeupAlarm(IIntentSender sender) {
7615 if (!(sender instanceof PendingIntentRecord)) {
7616 return;
7617 }
7618 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7619 synchronized (stats) {
7620 if (mBatteryStatsService.isOnBattery()) {
7621 mBatteryStatsService.enforceCallingPermission();
7622 PendingIntentRecord rec = (PendingIntentRecord)sender;
7623 int MY_UID = Binder.getCallingUid();
7624 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7625 BatteryStatsImpl.Uid.Pkg pkg =
7626 stats.getPackageStatsLocked(uid, rec.key.packageName);
7627 pkg.incWakeupsLocked();
7628 }
7629 }
7630 }
7631
Dianne Hackborn64825172011-03-02 21:32:58 -08007632 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007634 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007636 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 // XXX Note: don't acquire main activity lock here, because the window
7638 // manager calls in with its locks held.
7639
7640 boolean killed = false;
7641 synchronized (mPidsSelfLocked) {
7642 int[] types = new int[pids.length];
7643 int worstType = 0;
7644 for (int i=0; i<pids.length; i++) {
7645 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7646 if (proc != null) {
7647 int type = proc.setAdj;
7648 types[i] = type;
7649 if (type > worstType) {
7650 worstType = type;
7651 }
7652 }
7653 }
7654
Dianne Hackborn64825172011-03-02 21:32:58 -08007655 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007657 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7658 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007659 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007661
7662 // If this is not a secure call, don't let it kill processes that
7663 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007664 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7665 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007666 }
7667
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007668 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 for (int i=0; i<pids.length; i++) {
7670 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7671 if (proc == null) {
7672 continue;
7673 }
7674 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007675 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007676 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007677 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007678 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007680 proc.killedBackground = true;
7681 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 }
7683 }
7684 }
7685 return killed;
7686 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007687
7688 @Override
7689 public boolean killProcessesBelowForeground(String reason) {
7690 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7691 throw new SecurityException("killProcessesBelowForeground() only available to system");
7692 }
7693
7694 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7695 }
7696
7697 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7698 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7699 throw new SecurityException("killProcessesBelowAdj() only available to system");
7700 }
7701
7702 boolean killed = false;
7703 synchronized (mPidsSelfLocked) {
7704 final int size = mPidsSelfLocked.size();
7705 for (int i = 0; i < size; i++) {
7706 final int pid = mPidsSelfLocked.keyAt(i);
7707 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7708 if (proc == null) continue;
7709
7710 final int adj = proc.setAdj;
7711 if (adj > belowAdj && !proc.killedBackground) {
7712 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007713 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7714 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007715 killed = true;
7716 proc.killedBackground = true;
7717 Process.killProcessQuiet(pid);
7718 }
7719 }
7720 }
7721 return killed;
7722 }
7723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 public final void startRunning(String pkg, String cls, String action,
7725 String data) {
7726 synchronized(this) {
7727 if (mStartRunning) {
7728 return;
7729 }
7730 mStartRunning = true;
7731 mTopComponent = pkg != null && cls != null
7732 ? new ComponentName(pkg, cls) : null;
7733 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7734 mTopData = data;
7735 if (!mSystemReady) {
7736 return;
7737 }
7738 }
7739
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007740 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 }
7742
7743 private void retrieveSettings() {
7744 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007745 String debugApp = Settings.Global.getString(
7746 resolver, Settings.Global.DEBUG_APP);
7747 boolean waitForDebugger = Settings.Global.getInt(
7748 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7749 boolean alwaysFinishActivities = Settings.Global.getInt(
7750 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751
7752 Configuration configuration = new Configuration();
7753 Settings.System.getConfiguration(resolver, configuration);
7754
7755 synchronized (this) {
7756 mDebugApp = mOrigDebugApp = debugApp;
7757 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7758 mAlwaysFinishActivities = alwaysFinishActivities;
7759 // This happens before any activities are started, so we can
7760 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007761 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007762 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 }
7764 }
7765
7766 public boolean testIsSystemReady() {
7767 // no need to synchronize(this) just to read & return the value
7768 return mSystemReady;
7769 }
7770
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007771 private static File getCalledPreBootReceiversFile() {
7772 File dataDir = Environment.getDataDirectory();
7773 File systemDir = new File(dataDir, "system");
7774 File fname = new File(systemDir, "called_pre_boots.dat");
7775 return fname;
7776 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007777
7778 static final int LAST_DONE_VERSION = 10000;
7779
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007780 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7781 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7782 File file = getCalledPreBootReceiversFile();
7783 FileInputStream fis = null;
7784 try {
7785 fis = new FileInputStream(file);
7786 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007787 int fvers = dis.readInt();
7788 if (fvers == LAST_DONE_VERSION) {
7789 String vers = dis.readUTF();
7790 String codename = dis.readUTF();
7791 String build = dis.readUTF();
7792 if (android.os.Build.VERSION.RELEASE.equals(vers)
7793 && android.os.Build.VERSION.CODENAME.equals(codename)
7794 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7795 int num = dis.readInt();
7796 while (num > 0) {
7797 num--;
7798 String pkg = dis.readUTF();
7799 String cls = dis.readUTF();
7800 lastDoneReceivers.add(new ComponentName(pkg, cls));
7801 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007802 }
7803 }
7804 } catch (FileNotFoundException e) {
7805 } catch (IOException e) {
7806 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7807 } finally {
7808 if (fis != null) {
7809 try {
7810 fis.close();
7811 } catch (IOException e) {
7812 }
7813 }
7814 }
7815 return lastDoneReceivers;
7816 }
7817
7818 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7819 File file = getCalledPreBootReceiversFile();
7820 FileOutputStream fos = null;
7821 DataOutputStream dos = null;
7822 try {
7823 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7824 fos = new FileOutputStream(file);
7825 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007826 dos.writeInt(LAST_DONE_VERSION);
7827 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007828 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007829 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007830 dos.writeInt(list.size());
7831 for (int i=0; i<list.size(); i++) {
7832 dos.writeUTF(list.get(i).getPackageName());
7833 dos.writeUTF(list.get(i).getClassName());
7834 }
7835 } catch (IOException e) {
7836 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7837 file.delete();
7838 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007839 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007840 if (dos != null) {
7841 try {
7842 dos.close();
7843 } catch (IOException e) {
7844 // TODO Auto-generated catch block
7845 e.printStackTrace();
7846 }
7847 }
7848 }
7849 }
7850
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007851 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 synchronized(this) {
7853 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007854 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007855 return;
7856 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007857
7858 // Check to see if there are any update receivers to run.
7859 if (!mDidUpdate) {
7860 if (mWaitingUpdate) {
7861 return;
7862 }
7863 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7864 List<ResolveInfo> ris = null;
7865 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007866 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007867 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007868 } catch (RemoteException e) {
7869 }
7870 if (ris != null) {
7871 for (int i=ris.size()-1; i>=0; i--) {
7872 if ((ris.get(i).activityInfo.applicationInfo.flags
7873 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7874 ris.remove(i);
7875 }
7876 }
7877 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007878
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007879 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007880
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007881 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007882 for (int i=0; i<ris.size(); i++) {
7883 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007884 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7885 if (lastDoneReceivers.contains(comp)) {
7886 ris.remove(i);
7887 i--;
7888 }
7889 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007890
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007891 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007892 for (int i=0; i<ris.size(); i++) {
7893 ActivityInfo ai = ris.get(i).activityInfo;
7894 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7895 doneReceivers.add(comp);
7896 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007897 for (int j=0; j<users.length; j++) {
7898 IIntentReceiver finisher = null;
7899 if (i == ris.size()-1 && j == users.length-1) {
7900 finisher = new IIntentReceiver.Stub() {
7901 public void performReceive(Intent intent, int resultCode,
7902 String data, Bundle extras, boolean ordered,
7903 boolean sticky, int sendingUser) {
7904 // The raw IIntentReceiver interface is called
7905 // with the AM lock held, so redispatch to
7906 // execute our code without the lock.
7907 mHandler.post(new Runnable() {
7908 public void run() {
7909 synchronized (ActivityManagerService.this) {
7910 mDidUpdate = true;
7911 }
7912 writeLastDonePreBootReceivers(doneReceivers);
7913 showBootMessage(mContext.getText(
7914 R.string.android_upgrading_complete),
7915 false);
7916 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007917 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007918 });
7919 }
7920 };
7921 }
7922 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7923 + " for user " + users[j]);
7924 broadcastIntentLocked(null, null, intent, null, finisher,
7925 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7926 users[j]);
7927 if (finisher != null) {
7928 mWaitingUpdate = true;
7929 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007930 }
7931 }
7932 }
7933 if (mWaitingUpdate) {
7934 return;
7935 }
7936 mDidUpdate = true;
7937 }
7938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 mSystemReady = true;
7940 if (!mStartRunning) {
7941 return;
7942 }
7943 }
7944
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007945 ArrayList<ProcessRecord> procsToKill = null;
7946 synchronized(mPidsSelfLocked) {
7947 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7948 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7949 if (!isAllowedWhileBooting(proc.info)){
7950 if (procsToKill == null) {
7951 procsToKill = new ArrayList<ProcessRecord>();
7952 }
7953 procsToKill.add(proc);
7954 }
7955 }
7956 }
7957
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007958 synchronized(this) {
7959 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007960 for (int i=procsToKill.size()-1; i>=0; i--) {
7961 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007962 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007963 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007964 }
7965 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007966
7967 // Now that we have cleaned up any update processes, we
7968 // are ready to start launching real processes and know that
7969 // we won't trample on them any more.
7970 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007971 }
7972
Joe Onorato8a9b2202010-02-26 18:56:32 -08007973 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007974 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 SystemClock.uptimeMillis());
7976
7977 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007978 // Make sure we have no pre-ready processes sitting around.
7979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7981 ResolveInfo ri = mContext.getPackageManager()
7982 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007983 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 CharSequence errorMsg = null;
7985 if (ri != null) {
7986 ActivityInfo ai = ri.activityInfo;
7987 ApplicationInfo app = ai.applicationInfo;
7988 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7989 mTopAction = Intent.ACTION_FACTORY_TEST;
7990 mTopData = null;
7991 mTopComponent = new ComponentName(app.packageName,
7992 ai.name);
7993 } else {
7994 errorMsg = mContext.getResources().getText(
7995 com.android.internal.R.string.factorytest_not_system);
7996 }
7997 } else {
7998 errorMsg = mContext.getResources().getText(
7999 com.android.internal.R.string.factorytest_no_action);
8000 }
8001 if (errorMsg != null) {
8002 mTopAction = null;
8003 mTopData = null;
8004 mTopComponent = null;
8005 Message msg = Message.obtain();
8006 msg.what = SHOW_FACTORY_ERROR_MSG;
8007 msg.getData().putCharSequence("msg", errorMsg);
8008 mHandler.sendMessage(msg);
8009 }
8010 }
8011 }
8012
8013 retrieveSettings();
8014
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008015 if (goingCallback != null) goingCallback.run();
8016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 synchronized (this) {
8018 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
8019 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008020 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07008021 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 if (apps != null) {
8023 int N = apps.size();
8024 int i;
8025 for (i=0; i<N; i++) {
8026 ApplicationInfo info
8027 = (ApplicationInfo)apps.get(i);
8028 if (info != null &&
8029 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008030 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 }
8032 }
8033 }
8034 } catch (RemoteException ex) {
8035 // pm is in same process, this will never happen.
8036 }
8037 }
8038
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008039 // Start up initial activity.
8040 mBooting = true;
8041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008043 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 Message msg = Message.obtain();
8045 msg.what = SHOW_UID_ERROR_MSG;
8046 mHandler.sendMessage(msg);
8047 }
8048 } catch (RemoteException e) {
8049 }
8050
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008051 long ident = Binder.clearCallingIdentity();
8052 try {
8053 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008054 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
8055 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008056 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8057 broadcastIntentLocked(null, null, intent,
8058 null, null, 0, null, null, null,
8059 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008060 intent = new Intent(Intent.ACTION_USER_STARTING);
8061 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8062 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8063 broadcastIntentLocked(null, null, intent,
8064 null, new IIntentReceiver.Stub() {
8065 @Override
8066 public void performReceive(Intent intent, int resultCode, String data,
8067 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
8068 throws RemoteException {
8069 }
8070 }, 0, null, null,
8071 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08008072 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008073 } finally {
8074 Binder.restoreCallingIdentity(ident);
8075 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008076 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008077 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 }
8079 }
8080
Dan Egnorb7f03672009-12-09 16:22:32 -08008081 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008082 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008084 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008085 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 startAppProblemLocked(app);
8087 app.stopFreezingAllLocked();
8088 return handleAppCrashLocked(app);
8089 }
8090
Dan Egnorb7f03672009-12-09 16:22:32 -08008091 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008092 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008094 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008095 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8096 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 startAppProblemLocked(app);
8098 app.stopFreezingAllLocked();
8099 }
8100
8101 /**
8102 * Generate a process error record, suitable for attachment to a ProcessRecord.
8103 *
8104 * @param app The ProcessRecord in which the error occurred.
8105 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8106 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008107 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 * @param shortMsg Short message describing the crash.
8109 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008110 * @param stackTrace Full crash stack trace, may be null.
8111 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 * @return Returns a fully-formed AppErrorStateInfo record.
8113 */
8114 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008115 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 report.condition = condition;
8119 report.processName = app.processName;
8120 report.pid = app.pid;
8121 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008122 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 report.shortMsg = shortMsg;
8124 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008125 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126
8127 return report;
8128 }
8129
Dan Egnor42471dd2010-01-07 17:25:22 -08008130 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 synchronized (this) {
8132 app.crashing = false;
8133 app.crashingReport = null;
8134 app.notResponding = false;
8135 app.notRespondingReport = null;
8136 if (app.anrDialog == fromDialog) {
8137 app.anrDialog = null;
8138 }
8139 if (app.waitDialog == fromDialog) {
8140 app.waitDialog = null;
8141 }
8142 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008143 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008144 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008145 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008146 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008147 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 }
8150 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008151
Dan Egnorb7f03672009-12-09 16:22:32 -08008152 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008153 if (mHeadless) {
8154 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8155 return false;
8156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 long now = SystemClock.uptimeMillis();
8158
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008159 Long crashTime;
8160 if (!app.isolated) {
8161 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8162 } else {
8163 crashTime = null;
8164 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008165 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008167 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008168 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008169 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008170 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008171 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8172 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008174 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008176 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8177 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008178 }
8179 }
8180 if (!app.persistent) {
8181 // We don't want to start this process again until the user
8182 // explicitly does so... but for persistent process, we really
8183 // need to keep it running. If a persistent process is actually
8184 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008185 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008187 if (!app.isolated) {
8188 // XXX We don't have a way to mark isolated processes
8189 // as bad, since they don't have a peristent identity.
8190 mBadProcesses.put(app.info.processName, app.uid, now);
8191 mProcessCrashTimes.remove(app.info.processName, app.uid);
8192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008195 // Don't let services in this process be restarted and potentially
8196 // annoy the user repeatedly. Unless it is persistent, since those
8197 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008198 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008199 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 return false;
8201 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008202 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008203 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008204 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008205 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008206 // If the top running activity is from this crashing
8207 // process, then terminate it to avoid getting in a loop.
8208 Slog.w(TAG, " Force finishing activity "
8209 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008210 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008211 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008212 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008213 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008214 // stopped, to avoid a situation where one will get
8215 // re-start our crashing activity once it gets resumed again.
8216 index--;
8217 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008218 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008219 if (r.state == ActivityState.RESUMED
8220 || r.state == ActivityState.PAUSING
8221 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008222 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008223 Slog.w(TAG, " Force finishing activity "
8224 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008225 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008226 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008227 }
8228 }
8229 }
8230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008231 }
8232
8233 // Bump up the crash count of any services currently running in the proc.
8234 if (app.services.size() != 0) {
8235 // Any services running in the application need to be placed
8236 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008237 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008239 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 sr.crashCount++;
8241 }
8242 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008243
8244 // If the crashing process is what we consider to be the "home process" and it has been
8245 // replaced by a third-party app, clear the package preferred activities from packages
8246 // with a home activity running in the process to prevent a repeatedly crashing app
8247 // from blocking the user to manually clear the list.
8248 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8249 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8250 Iterator it = mHomeProcess.activities.iterator();
8251 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008252 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008253 if (r.isHomeActivity) {
8254 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8255 try {
8256 ActivityThread.getPackageManager()
8257 .clearPackagePreferredActivities(r.packageName);
8258 } catch (RemoteException c) {
8259 // pm is in same process, this will never happen.
8260 }
8261 }
8262 }
8263 }
8264
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008265 if (!app.isolated) {
8266 // XXX Can't keep track of crash times for isolated processes,
8267 // because they don't have a perisistent identity.
8268 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8269 }
8270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 return true;
8272 }
8273
8274 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008275 if (app.userId == mCurrentUserId) {
8276 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8277 mContext, app.info.packageName, app.info.flags);
8278 } else {
8279 // If this app is not running under the current user, then we
8280 // can't give it a report button because that would require
8281 // launching the report UI under a different user.
8282 app.errorReportReceiver = null;
8283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 skipCurrentReceiverLocked(app);
8285 }
8286
8287 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008288 for (BroadcastQueue queue : mBroadcastQueues) {
8289 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 }
8291 }
8292
Dan Egnor60d87622009-12-16 16:32:58 -08008293 /**
8294 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8295 * The application process will exit immediately after this call returns.
8296 * @param app object of the crashing app, null for the system server
8297 * @param crashInfo describing the exception
8298 */
8299 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008300 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008301 final String processName = app == null ? "system_server"
8302 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008303
8304 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008305 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008306 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008307 crashInfo.exceptionClassName,
8308 crashInfo.exceptionMessage,
8309 crashInfo.throwFileName,
8310 crashInfo.throwLineNumber);
8311
Jeff Sharkeya353d262011-10-28 11:12:06 -07008312 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008313
8314 crashApplication(r, crashInfo);
8315 }
8316
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008317 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008318 IBinder app,
8319 int violationMask,
8320 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008321 ProcessRecord r = findAppProcess(app, "StrictMode");
8322 if (r == null) {
8323 return;
8324 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008325
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008326 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008327 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008328 boolean logIt = true;
8329 synchronized (mAlreadyLoggedViolatedStacks) {
8330 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8331 logIt = false;
8332 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008333 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008334 // the relative pain numbers, without logging all
8335 // the stack traces repeatedly. We'd want to do
8336 // likewise in the client code, which also does
8337 // dup suppression, before the Binder call.
8338 } else {
8339 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8340 mAlreadyLoggedViolatedStacks.clear();
8341 }
8342 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8343 }
8344 }
8345 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008346 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008347 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008348 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008349
8350 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8351 AppErrorResult result = new AppErrorResult();
8352 synchronized (this) {
8353 final long origId = Binder.clearCallingIdentity();
8354
8355 Message msg = Message.obtain();
8356 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8357 HashMap<String, Object> data = new HashMap<String, Object>();
8358 data.put("result", result);
8359 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008360 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008361 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008362 msg.obj = data;
8363 mHandler.sendMessage(msg);
8364
8365 Binder.restoreCallingIdentity(origId);
8366 }
8367 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008368 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008369 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008370 }
8371
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008372 // Depending on the policy in effect, there could be a bunch of
8373 // these in quick succession so we try to batch these together to
8374 // minimize disk writes, number of dropbox entries, and maximize
8375 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008376 private void logStrictModeViolationToDropBox(
8377 ProcessRecord process,
8378 StrictMode.ViolationInfo info) {
8379 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008380 return;
8381 }
8382 final boolean isSystemApp = process == null ||
8383 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8384 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008385 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008386 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8387 final DropBoxManager dbox = (DropBoxManager)
8388 mContext.getSystemService(Context.DROPBOX_SERVICE);
8389
8390 // Exit early if the dropbox isn't configured to accept this report type.
8391 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8392
8393 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008394 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008395 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8396 synchronized (sb) {
8397 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008398 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008399 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8400 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008401 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8402 if (info.violationNumThisLoop != 0) {
8403 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8404 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008405 if (info.numAnimationsRunning != 0) {
8406 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8407 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008408 if (info.broadcastIntentAction != null) {
8409 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8410 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008411 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008412 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008413 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008414 if (info.numInstances != -1) {
8415 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8416 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008417 if (info.tags != null) {
8418 for (String tag : info.tags) {
8419 sb.append("Span-Tag: ").append(tag).append("\n");
8420 }
8421 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008422 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008423 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8424 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008425 }
8426 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008427
8428 // Only buffer up to ~64k. Various logging bits truncate
8429 // things at 128k.
8430 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008431 }
8432
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008433 // Flush immediately if the buffer's grown too large, or this
8434 // is a non-system app. Non-system apps are isolated with a
8435 // different tag & policy and not batched.
8436 //
8437 // Batching is useful during internal testing with
8438 // StrictMode settings turned up high. Without batching,
8439 // thousands of separate files could be created on boot.
8440 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008441 new Thread("Error dump: " + dropboxTag) {
8442 @Override
8443 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008444 String report;
8445 synchronized (sb) {
8446 report = sb.toString();
8447 sb.delete(0, sb.length());
8448 sb.trimToSize();
8449 }
8450 if (report.length() != 0) {
8451 dbox.addText(dropboxTag, report);
8452 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008453 }
8454 }.start();
8455 return;
8456 }
8457
8458 // System app batching:
8459 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008460 // An existing dropbox-writing thread is outstanding, so
8461 // we don't need to start it up. The existing thread will
8462 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008463 return;
8464 }
8465
8466 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8467 // (After this point, we shouldn't access AMS internal data structures.)
8468 new Thread("Error dump: " + dropboxTag) {
8469 @Override
8470 public void run() {
8471 // 5 second sleep to let stacks arrive and be batched together
8472 try {
8473 Thread.sleep(5000); // 5 seconds
8474 } catch (InterruptedException e) {}
8475
8476 String errorReport;
8477 synchronized (mStrictModeBuffer) {
8478 errorReport = mStrictModeBuffer.toString();
8479 if (errorReport.length() == 0) {
8480 return;
8481 }
8482 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8483 mStrictModeBuffer.trimToSize();
8484 }
8485 dbox.addText(dropboxTag, errorReport);
8486 }
8487 }.start();
8488 }
8489
Dan Egnor60d87622009-12-16 16:32:58 -08008490 /**
8491 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8492 * @param app object of the crashing app, null for the system server
8493 * @param tag reported by the caller
8494 * @param crashInfo describing the context of the error
8495 * @return true if the process should exit immediately (WTF is fatal)
8496 */
8497 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008498 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008499 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008500 final String processName = app == null ? "system_server"
8501 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008502
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008503 EventLog.writeEvent(EventLogTags.AM_WTF,
8504 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008505 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008506 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008507 tag, crashInfo.exceptionMessage);
8508
Jeff Sharkeya353d262011-10-28 11:12:06 -07008509 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008510
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008511 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008512 Settings.Global.getInt(mContext.getContentResolver(),
8513 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008514 crashApplication(r, crashInfo);
8515 return true;
8516 } else {
8517 return false;
8518 }
8519 }
8520
8521 /**
8522 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8523 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8524 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008525 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008526 if (app == null) {
8527 return null;
8528 }
8529
8530 synchronized (this) {
8531 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8532 final int NA = apps.size();
8533 for (int ia=0; ia<NA; ia++) {
8534 ProcessRecord p = apps.valueAt(ia);
8535 if (p.thread != null && p.thread.asBinder() == app) {
8536 return p;
8537 }
8538 }
8539 }
8540
Dianne Hackborncb44d962011-03-10 17:02:27 -08008541 Slog.w(TAG, "Can't find mystery application for " + reason
8542 + " from pid=" + Binder.getCallingPid()
8543 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008544 return null;
8545 }
8546 }
8547
8548 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008549 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8550 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008551 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008552 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8553 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008554 // Watchdog thread ends up invoking this function (with
8555 // a null ProcessRecord) to add the stack file to dropbox.
8556 // Do not acquire a lock on this (am) in such cases, as it
8557 // could cause a potential deadlock, if and when watchdog
8558 // is invoked due to unavailability of lock on am and it
8559 // would prevent watchdog from killing system_server.
8560 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008561 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008562 return;
8563 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008564 // Note: ProcessRecord 'process' is guarded by the service
8565 // instance. (notably process.pkgList, which could otherwise change
8566 // concurrently during execution of this method)
8567 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008568 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008569 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008570 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008571 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8572 for (String pkg : process.pkgList) {
8573 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008574 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008575 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008576 if (pi != null) {
8577 sb.append(" v").append(pi.versionCode);
8578 if (pi.versionName != null) {
8579 sb.append(" (").append(pi.versionName).append(")");
8580 }
8581 }
8582 } catch (RemoteException e) {
8583 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008584 }
Dan Egnora455d192010-03-12 08:52:28 -08008585 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008586 }
Dan Egnora455d192010-03-12 08:52:28 -08008587 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008588 }
8589
8590 private static String processClass(ProcessRecord process) {
8591 if (process == null || process.pid == MY_PID) {
8592 return "system_server";
8593 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8594 return "system_app";
8595 } else {
8596 return "data_app";
8597 }
8598 }
8599
8600 /**
8601 * Write a description of an error (crash, WTF, ANR) to the drop box.
8602 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8603 * @param process which caused the error, null means the system server
8604 * @param activity which triggered the error, null if unknown
8605 * @param parent activity related to the error, null if unknown
8606 * @param subject line related to the error, null if absent
8607 * @param report in long form describing the error, null if absent
8608 * @param logFile to include in the report, null if none
8609 * @param crashInfo giving an application stack trace, null if absent
8610 */
8611 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008612 ProcessRecord process, String processName, ActivityRecord activity,
8613 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008614 final String report, final File logFile,
8615 final ApplicationErrorReport.CrashInfo crashInfo) {
8616 // NOTE -- this must never acquire the ActivityManagerService lock,
8617 // otherwise the watchdog may be prevented from resetting the system.
8618
8619 final String dropboxTag = processClass(process) + "_" + eventType;
8620 final DropBoxManager dbox = (DropBoxManager)
8621 mContext.getSystemService(Context.DROPBOX_SERVICE);
8622
8623 // Exit early if the dropbox isn't configured to accept this report type.
8624 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8625
8626 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008627 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008628 if (activity != null) {
8629 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8630 }
8631 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8632 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8633 }
8634 if (parent != null && parent != activity) {
8635 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8636 }
8637 if (subject != null) {
8638 sb.append("Subject: ").append(subject).append("\n");
8639 }
8640 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008641 if (Debug.isDebuggerConnected()) {
8642 sb.append("Debugger: Connected\n");
8643 }
Dan Egnora455d192010-03-12 08:52:28 -08008644 sb.append("\n");
8645
8646 // Do the rest in a worker thread to avoid blocking the caller on I/O
8647 // (After this point, we shouldn't access AMS internal data structures.)
8648 Thread worker = new Thread("Error dump: " + dropboxTag) {
8649 @Override
8650 public void run() {
8651 if (report != null) {
8652 sb.append(report);
8653 }
8654 if (logFile != null) {
8655 try {
8656 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8657 } catch (IOException e) {
8658 Slog.e(TAG, "Error reading " + logFile, e);
8659 }
8660 }
8661 if (crashInfo != null && crashInfo.stackTrace != null) {
8662 sb.append(crashInfo.stackTrace);
8663 }
8664
Jeff Sharkey625239a2012-09-26 22:03:49 -07008665 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8666 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008667 if (lines > 0) {
8668 sb.append("\n");
8669
8670 // Merge several logcat streams, and take the last N lines
8671 InputStreamReader input = null;
8672 try {
8673 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8674 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8675 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8676
8677 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8678 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8679 input = new InputStreamReader(logcat.getInputStream());
8680
8681 int num;
8682 char[] buf = new char[8192];
8683 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8684 } catch (IOException e) {
8685 Slog.e(TAG, "Error running logcat", e);
8686 } finally {
8687 if (input != null) try { input.close(); } catch (IOException e) {}
8688 }
8689 }
8690
8691 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008692 }
Dan Egnora455d192010-03-12 08:52:28 -08008693 };
8694
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008695 if (process == null) {
8696 // If process is null, we are being called from some internal code
8697 // and may be about to die -- run this synchronously.
8698 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008699 } else {
8700 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008701 }
8702 }
8703
8704 /**
8705 * Bring up the "unexpected error" dialog box for a crashing app.
8706 * Deal with edge cases (intercepts from instrumented applications,
8707 * ActivityController, error intent receivers, that sort of thing).
8708 * @param r the application crashing
8709 * @param crashInfo describing the failure
8710 */
8711 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008712 long timeMillis = System.currentTimeMillis();
8713 String shortMsg = crashInfo.exceptionClassName;
8714 String longMsg = crashInfo.exceptionMessage;
8715 String stackTrace = crashInfo.stackTrace;
8716 if (shortMsg != null && longMsg != null) {
8717 longMsg = shortMsg + ": " + longMsg;
8718 } else if (shortMsg != null) {
8719 longMsg = shortMsg;
8720 }
8721
Dan Egnor60d87622009-12-16 16:32:58 -08008722 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008724 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 try {
8726 String name = r != null ? r.processName : null;
8727 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008728 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008729 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008730 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 + " at watcher's request");
8732 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008733 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008734 }
8735 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008736 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 }
8738 }
8739
8740 final long origId = Binder.clearCallingIdentity();
8741
8742 // If this process is running instrumentation, finish it.
8743 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008744 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008746 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8747 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 Bundle info = new Bundle();
8749 info.putString("shortMsg", shortMsg);
8750 info.putString("longMsg", longMsg);
8751 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8752 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008753 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008754 }
8755
Dan Egnor60d87622009-12-16 16:32:58 -08008756 // If we can't identify the process or it's already exceeded its crash quota,
8757 // quit right away without showing a crash dialog.
8758 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008760 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 }
8762
8763 Message msg = Message.obtain();
8764 msg.what = SHOW_ERROR_MSG;
8765 HashMap data = new HashMap();
8766 data.put("result", result);
8767 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 msg.obj = data;
8769 mHandler.sendMessage(msg);
8770
8771 Binder.restoreCallingIdentity(origId);
8772 }
8773
8774 int res = result.get();
8775
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008776 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008778 if (r != null && !r.isolated) {
8779 // XXX Can't keep track of crash time for isolated processes,
8780 // since they don't have a persistent identity.
8781 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 SystemClock.uptimeMillis());
8783 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008784 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008785 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008786 }
8787 }
8788
8789 if (appErrorIntent != null) {
8790 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008791 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008792 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008793 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008797
8798 Intent createAppErrorIntentLocked(ProcessRecord r,
8799 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8800 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008801 if (report == null) {
8802 return null;
8803 }
8804 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8805 result.setComponent(r.errorReportReceiver);
8806 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8807 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8808 return result;
8809 }
8810
Dan Egnorb7f03672009-12-09 16:22:32 -08008811 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8812 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008813 if (r.errorReportReceiver == null) {
8814 return null;
8815 }
8816
8817 if (!r.crashing && !r.notResponding) {
8818 return null;
8819 }
8820
Dan Egnorb7f03672009-12-09 16:22:32 -08008821 ApplicationErrorReport report = new ApplicationErrorReport();
8822 report.packageName = r.info.packageName;
8823 report.installerPackageName = r.errorReportReceiver.getPackageName();
8824 report.processName = r.processName;
8825 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008826 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008827
Dan Egnorb7f03672009-12-09 16:22:32 -08008828 if (r.crashing) {
8829 report.type = ApplicationErrorReport.TYPE_CRASH;
8830 report.crashInfo = crashInfo;
8831 } else if (r.notResponding) {
8832 report.type = ApplicationErrorReport.TYPE_ANR;
8833 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008834
Dan Egnorb7f03672009-12-09 16:22:32 -08008835 report.anrInfo.activity = r.notRespondingReport.tag;
8836 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8837 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008838 }
8839
Dan Egnorb7f03672009-12-09 16:22:32 -08008840 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008841 }
8842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008844 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 // assume our apps are happy - lazy create the list
8846 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8847
Dianne Hackborn0c380492012-08-20 17:23:30 -07008848 final boolean allUsers = ActivityManager.checkUidPermission(
8849 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8850 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8851 int userId = UserHandle.getUserId(Binder.getCallingUid());
8852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 synchronized (this) {
8854
8855 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008856 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8857 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008858 if (!allUsers && app.userId != userId) {
8859 continue;
8860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8862 // This one's in trouble, so we'll generate a report for it
8863 // crashes are higher priority (in case there's a crash *and* an anr)
8864 ActivityManager.ProcessErrorStateInfo report = null;
8865 if (app.crashing) {
8866 report = app.crashingReport;
8867 } else if (app.notResponding) {
8868 report = app.notRespondingReport;
8869 }
8870
8871 if (report != null) {
8872 if (errList == null) {
8873 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8874 }
8875 errList.add(report);
8876 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008877 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878 " crashing = " + app.crashing +
8879 " notResponding = " + app.notResponding);
8880 }
8881 }
8882 }
8883 }
8884
8885 return errList;
8886 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008887
8888 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008889 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008890 if (currApp != null) {
8891 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8892 }
8893 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008894 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8895 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008896 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8897 if (currApp != null) {
8898 currApp.lru = 0;
8899 }
8900 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008901 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008902 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8903 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8904 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8905 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8906 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8907 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8908 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8909 } else {
8910 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8911 }
8912 }
8913
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008914 private void fillInProcMemInfo(ProcessRecord app,
8915 ActivityManager.RunningAppProcessInfo outInfo) {
8916 outInfo.pid = app.pid;
8917 outInfo.uid = app.info.uid;
8918 if (mHeavyWeightProcess == app) {
8919 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8920 }
8921 if (app.persistent) {
8922 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8923 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008924 if (app.hasActivities) {
8925 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8926 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008927 outInfo.lastTrimLevel = app.trimMemoryLevel;
8928 int adj = app.curAdj;
8929 outInfo.importance = oomAdjToImportance(adj, outInfo);
8930 outInfo.importanceReasonCode = app.adjTypeCode;
8931 }
8932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008934 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 // Lazy instantiation of list
8936 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008937 final boolean allUsers = ActivityManager.checkUidPermission(
8938 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8939 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8940 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 synchronized (this) {
8942 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008943 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8944 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008945 if (!allUsers && app.userId != userId) {
8946 continue;
8947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8949 // Generate process state info for running application
8950 ActivityManager.RunningAppProcessInfo currApp =
8951 new ActivityManager.RunningAppProcessInfo(app.processName,
8952 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008953 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008954 if (app.adjSource instanceof ProcessRecord) {
8955 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008956 currApp.importanceReasonImportance = oomAdjToImportance(
8957 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008958 } else if (app.adjSource instanceof ActivityRecord) {
8959 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008960 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8961 }
8962 if (app.adjTarget instanceof ComponentName) {
8963 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8964 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008965 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 // + " lru=" + currApp.lru);
8967 if (runList == null) {
8968 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8969 }
8970 runList.add(currApp);
8971 }
8972 }
8973 }
8974 return runList;
8975 }
8976
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008977 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008978 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008979 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8980 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8981 if (runningApps != null && runningApps.size() > 0) {
8982 Set<String> extList = new HashSet<String>();
8983 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8984 if (app.pkgList != null) {
8985 for (String pkg : app.pkgList) {
8986 extList.add(pkg);
8987 }
8988 }
8989 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008990 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008991 for (String pkg : extList) {
8992 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008993 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008994 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8995 retList.add(info);
8996 }
8997 } catch (RemoteException e) {
8998 }
8999 }
9000 }
9001 return retList;
9002 }
9003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009005 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
9006 enforceNotIsolatedCaller("getMyMemoryState");
9007 synchronized (this) {
9008 ProcessRecord proc;
9009 synchronized (mPidsSelfLocked) {
9010 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9011 }
9012 fillInProcMemInfo(proc, outInfo);
9013 }
9014 }
9015
9016 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009017 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 if (checkCallingPermission(android.Manifest.permission.DUMP)
9019 != PackageManager.PERMISSION_GRANTED) {
9020 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9021 + Binder.getCallingPid()
9022 + ", uid=" + Binder.getCallingUid()
9023 + " without permission "
9024 + android.Manifest.permission.DUMP);
9025 return;
9026 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009027
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009028 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009029 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009030 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009031
9032 int opti = 0;
9033 while (opti < args.length) {
9034 String opt = args[opti];
9035 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9036 break;
9037 }
9038 opti++;
9039 if ("-a".equals(opt)) {
9040 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009041 } else if ("-c".equals(opt)) {
9042 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043 } else if ("-h".equals(opt)) {
9044 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009045 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009047 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009048 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009049 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
9050 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009051 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009052 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08009053 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009054 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009055 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009056 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009057 pw.println(" all: dump all activities");
9058 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009059 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009060 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
9061 pw.println(" a partial substring in a component name, a");
9062 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 pw.println(" -a: include all available server state.");
9064 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009066 } else {
9067 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009069 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009070
9071 long origId = Binder.clearCallingIdentity();
9072 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009073 // Is the caller requesting to dump a particular piece of data?
9074 if (opti < args.length) {
9075 String cmd = args[opti];
9076 opti++;
9077 if ("activities".equals(cmd) || "a".equals(cmd)) {
9078 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009079 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009081 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009082 String[] newArgs;
9083 String name;
9084 if (opti >= args.length) {
9085 name = null;
9086 newArgs = EMPTY_STRING_ARRAY;
9087 } else {
9088 name = args[opti];
9089 opti++;
9090 newArgs = new String[args.length - opti];
9091 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9092 args.length - opti);
9093 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009095 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009096 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009098 String[] newArgs;
9099 String name;
9100 if (opti >= args.length) {
9101 name = null;
9102 newArgs = EMPTY_STRING_ARRAY;
9103 } else {
9104 name = args[opti];
9105 opti++;
9106 newArgs = new String[args.length - opti];
9107 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9108 args.length - opti);
9109 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009110 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009111 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009112 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009113 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009114 String[] newArgs;
9115 String name;
9116 if (opti >= args.length) {
9117 name = null;
9118 newArgs = EMPTY_STRING_ARRAY;
9119 } else {
9120 name = args[opti];
9121 opti++;
9122 newArgs = new String[args.length - opti];
9123 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9124 args.length - opti);
9125 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009126 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009127 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009128 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009129 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9130 synchronized (this) {
9131 dumpOomLocked(fd, pw, args, opti, true);
9132 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009133 } else if ("provider".equals(cmd)) {
9134 String[] newArgs;
9135 String name;
9136 if (opti >= args.length) {
9137 name = null;
9138 newArgs = EMPTY_STRING_ARRAY;
9139 } else {
9140 name = args[opti];
9141 opti++;
9142 newArgs = new String[args.length - opti];
9143 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9144 }
9145 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9146 pw.println("No providers match: " + name);
9147 pw.println("Use -h for help.");
9148 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009149 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9150 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009151 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009152 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009153 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009154 String[] newArgs;
9155 String name;
9156 if (opti >= args.length) {
9157 name = null;
9158 newArgs = EMPTY_STRING_ARRAY;
9159 } else {
9160 name = args[opti];
9161 opti++;
9162 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009163 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9164 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009165 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009166 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009167 pw.println("No services match: " + name);
9168 pw.println("Use -h for help.");
9169 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009170 } else if ("package".equals(cmd)) {
9171 String[] newArgs;
9172 if (opti >= args.length) {
9173 pw.println("package: no package name specified");
9174 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009175 } else {
9176 dumpPackage = args[opti];
9177 opti++;
9178 newArgs = new String[args.length - opti];
9179 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9180 args.length - opti);
9181 args = newArgs;
9182 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009183 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009184 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009185 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9186 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009187 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009188 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009189 } else {
9190 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009191 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9192 pw.println("Bad activity command, or no activities match: " + cmd);
9193 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009194 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009195 }
9196 if (!more) {
9197 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009198 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009199 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009200 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009201
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202 // No piece of data specified, dump everything.
9203 synchronized (this) {
9204 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009205 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009206 if (needSep) {
9207 pw.println(" ");
9208 }
9209 if (dumpAll) {
9210 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009211 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009212 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009213 if (needSep) {
9214 pw.println(" ");
9215 }
9216 if (dumpAll) {
9217 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009218 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009219 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220 if (needSep) {
9221 pw.println(" ");
9222 }
9223 if (dumpAll) {
9224 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009225 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009226 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009227 if (needSep) {
9228 pw.println(" ");
9229 }
9230 if (dumpAll) {
9231 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009232 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009233 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009234 if (needSep) {
9235 pw.println(" ");
9236 }
9237 if (dumpAll) {
9238 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009239 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009240 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009242 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009244
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009245 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009246 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009247 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9248 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009249 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9250 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009251 pw.println(" ");
9252 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009253 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9254 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009255 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009256 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009257 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009258 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009259 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009260 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009261 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009262 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009263 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009264 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009265 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009266 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009267 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9268 pw.println(" ");
9269 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009270 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009271 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009272 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009273 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009274 pw.println(" ");
9275 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009276 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009277 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009279
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009280 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009281 if (mMainStack.mPausingActivity != null) {
9282 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009283 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009284 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009285 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009286 if (dumpAll) {
9287 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9288 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009289 pw.println(" mDismissKeyguardOnNextActivity: "
9290 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009293 if (mRecentTasks.size() > 0) {
9294 pw.println();
9295 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009296
9297 final int N = mRecentTasks.size();
9298 for (int i=0; i<N; i++) {
9299 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009300 if (dumpPackage != null) {
9301 if (tr.realActivity == null ||
9302 !dumpPackage.equals(tr.realActivity)) {
9303 continue;
9304 }
9305 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009306 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9307 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009308 if (dumpAll) {
9309 mRecentTasks.get(i).dump(pw, " ");
9310 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 }
9312 }
9313
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009314 if (dumpAll) {
9315 pw.println(" ");
9316 pw.println(" mCurTask: " + mCurTask);
9317 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009318
9319 return true;
9320 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009321
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009322 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009323 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009324 boolean needSep = false;
9325 int numPers = 0;
9326
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009327 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9328
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009329 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9331 final int NA = procs.size();
9332 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009333 ProcessRecord r = procs.valueAt(ia);
9334 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9335 continue;
9336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 if (!needSep) {
9338 pw.println(" All known processes:");
9339 needSep = true;
9340 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009341 pw.print(r.persistent ? " *PERS*" : " *APP*");
9342 pw.print(" UID "); pw.print(procs.keyAt(ia));
9343 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344 r.dump(pw, " ");
9345 if (r.persistent) {
9346 numPers++;
9347 }
9348 }
9349 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009350 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009351
9352 if (mIsolatedProcesses.size() > 0) {
9353 if (needSep) pw.println(" ");
9354 needSep = true;
9355 pw.println(" Isolated process list (sorted by uid):");
9356 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9357 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9358 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9359 continue;
9360 }
9361 pw.println(String.format("%sIsolated #%2d: %s",
9362 " ", i, r.toString()));
9363 }
9364 }
9365
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009366 if (mLruProcesses.size() > 0) {
9367 if (needSep) pw.println(" ");
9368 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009369 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009370 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009371 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009372 needSep = true;
9373 }
9374
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009375 if (dumpAll) {
9376 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009377 boolean printed = false;
9378 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9379 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9380 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9381 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009382 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009383 if (!printed) {
9384 if (needSep) pw.println(" ");
9385 needSep = true;
9386 pw.println(" PID mappings:");
9387 printed = true;
9388 }
9389 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9390 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 }
9392 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009393 }
9394
9395 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009396 synchronized (mPidsSelfLocked) {
9397 boolean printed = false;
9398 for (int i=0; i<mForegroundProcesses.size(); i++) {
9399 ProcessRecord r = mPidsSelfLocked.get(
9400 mForegroundProcesses.valueAt(i).pid);
9401 if (dumpPackage != null && (r == null
9402 || !dumpPackage.equals(r.info.packageName))) {
9403 continue;
9404 }
9405 if (!printed) {
9406 if (needSep) pw.println(" ");
9407 needSep = true;
9408 pw.println(" Foreground Processes:");
9409 printed = true;
9410 }
9411 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9412 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009415 }
9416
9417 if (mPersistentStartingProcesses.size() > 0) {
9418 if (needSep) pw.println(" ");
9419 needSep = true;
9420 pw.println(" Persisent processes that are starting:");
9421 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009422 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009425 if (mRemovedProcesses.size() > 0) {
9426 if (needSep) pw.println(" ");
9427 needSep = true;
9428 pw.println(" Processes that are being removed:");
9429 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009430 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009431 }
9432
9433 if (mProcessesOnHold.size() > 0) {
9434 if (needSep) pw.println(" ");
9435 needSep = true;
9436 pw.println(" Processes that are on old until the system is ready:");
9437 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009438 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009440
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009441 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009442
9443 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009444 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009445 long now = SystemClock.uptimeMillis();
9446 for (Map.Entry<String, SparseArray<Long>> procs
9447 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009448 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009449 SparseArray<Long> uids = procs.getValue();
9450 final int N = uids.size();
9451 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009452 int puid = uids.keyAt(i);
9453 ProcessRecord r = mProcessNames.get(pname, puid);
9454 if (dumpPackage != null && (r == null
9455 || !dumpPackage.equals(r.info.packageName))) {
9456 continue;
9457 }
9458 if (!printed) {
9459 if (needSep) pw.println(" ");
9460 needSep = true;
9461 pw.println(" Time since processes crashed:");
9462 printed = true;
9463 }
9464 pw.print(" Process "); pw.print(pname);
9465 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009466 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009467 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9468 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009469 }
9470 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009473 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009474 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009475 for (Map.Entry<String, SparseArray<Long>> procs
9476 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009477 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009478 SparseArray<Long> uids = procs.getValue();
9479 final int N = uids.size();
9480 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009481 int puid = uids.keyAt(i);
9482 ProcessRecord r = mProcessNames.get(pname, puid);
9483 if (dumpPackage != null && (r == null
9484 || !dumpPackage.equals(r.info.packageName))) {
9485 continue;
9486 }
9487 if (!printed) {
9488 if (needSep) pw.println(" ");
9489 needSep = true;
9490 pw.println(" Bad processes:");
9491 }
9492 pw.print(" Bad process "); pw.print(pname);
9493 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009494 pw.print(": crashed at time ");
9495 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009496 }
9497 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009499
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009500 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009501 pw.println(" mStartedUsers:");
9502 for (int i=0; i<mStartedUsers.size(); i++) {
9503 UserStartedState uss = mStartedUsers.valueAt(i);
9504 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009505 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009506 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009507 pw.print(" mStartedUserArray: [");
9508 for (int i=0; i<mStartedUserArray.length; i++) {
9509 if (i > 0) pw.print(", ");
9510 pw.print(mStartedUserArray[i]);
9511 }
9512 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009513 pw.print(" mUserLru: [");
9514 for (int i=0; i<mUserLru.size(); i++) {
9515 if (i > 0) pw.print(", ");
9516 pw.print(mUserLru.get(i));
9517 }
9518 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009519 if (dumpAll) {
9520 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9521 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009523 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009524 if (dumpAll) {
9525 StringBuilder sb = new StringBuilder(128);
9526 sb.append(" mPreviousProcessVisibleTime: ");
9527 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9528 pw.println(sb);
9529 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009530 if (mHeavyWeightProcess != null) {
9531 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9532 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009533 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009534 if (dumpAll) {
9535 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009536 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009537 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009538 for (Map.Entry<String, Integer> entry
9539 : mCompatModePackages.getPackages().entrySet()) {
9540 String pkg = entry.getKey();
9541 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009542 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9543 continue;
9544 }
9545 if (!printed) {
9546 pw.println(" mScreenCompatPackages:");
9547 printed = true;
9548 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009549 pw.print(" "); pw.print(pkg); pw.print(": ");
9550 pw.print(mode); pw.println();
9551 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009552 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009553 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009554 if (mSleeping || mWentToSleep || mLockScreenShown) {
9555 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9556 + " mLockScreenShown " + mLockScreenShown);
9557 }
9558 if (mShuttingDown) {
9559 pw.println(" mShuttingDown=" + mShuttingDown);
9560 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009561 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9562 || mOrigWaitForDebugger) {
9563 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9564 + " mDebugTransient=" + mDebugTransient
9565 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9566 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009567 if (mOpenGlTraceApp != null) {
9568 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9569 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009570 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9571 || mProfileFd != null) {
9572 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9573 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9574 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9575 + mAutoStopProfiler);
9576 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009577 if (mAlwaysFinishActivities || mController != null) {
9578 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9579 + " mController=" + mController);
9580 }
9581 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009584 + " mProcessesReady=" + mProcessesReady
9585 + " mSystemReady=" + mSystemReady);
9586 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 + " mBooted=" + mBooted
9588 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009589 pw.print(" mLastPowerCheckRealtime=");
9590 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9591 pw.println("");
9592 pw.print(" mLastPowerCheckUptime=");
9593 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9594 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009595 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9596 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009597 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009598 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9599 + " mNumHiddenProcs=" + mNumHiddenProcs
9600 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009601 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009603
9604 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605 }
9606
Dianne Hackborn287952c2010-09-22 22:34:31 -07009607 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009608 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009609 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009610 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009611 long now = SystemClock.uptimeMillis();
9612 for (int i=0; i<mProcessesToGc.size(); i++) {
9613 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009614 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9615 continue;
9616 }
9617 if (!printed) {
9618 if (needSep) pw.println(" ");
9619 needSep = true;
9620 pw.println(" Processes that are waiting to GC:");
9621 printed = true;
9622 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009623 pw.print(" Process "); pw.println(proc);
9624 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9625 pw.print(", last gced=");
9626 pw.print(now-proc.lastRequestedGc);
9627 pw.print(" ms ago, last lowMem=");
9628 pw.print(now-proc.lastLowMemory);
9629 pw.println(" ms ago");
9630
9631 }
9632 }
9633 return needSep;
9634 }
9635
9636 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9637 int opti, boolean dumpAll) {
9638 boolean needSep = false;
9639
9640 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009641 if (needSep) pw.println(" ");
9642 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009643 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009644 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009645 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009646 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9647 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9648 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9649 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9650 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009651 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009652 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009653 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009654 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009655 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009656 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009657
9658 if (needSep) pw.println(" ");
9659 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009660 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009661 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009662 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009663 needSep = true;
9664 }
9665
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009666 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009667
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009668 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009669 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009670 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009671 if (mHeavyWeightProcess != null) {
9672 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9673 }
9674
9675 return true;
9676 }
9677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009678 /**
9679 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009680 * - no provider specified: dump all the providers
9681 * - a flattened component name that matched an existing provider was specified as the
9682 * first arg: dump that one provider
9683 * - the first arg isn't the flattened component name of an existing provider:
9684 * dump all providers whose component contains the first arg as a substring
9685 */
9686 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9687 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009688 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009689 }
9690
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009691 static class ItemMatcher {
9692 ArrayList<ComponentName> components;
9693 ArrayList<String> strings;
9694 ArrayList<Integer> objects;
9695 boolean all;
9696
9697 ItemMatcher() {
9698 all = true;
9699 }
9700
9701 void build(String name) {
9702 ComponentName componentName = ComponentName.unflattenFromString(name);
9703 if (componentName != null) {
9704 if (components == null) {
9705 components = new ArrayList<ComponentName>();
9706 }
9707 components.add(componentName);
9708 all = false;
9709 } else {
9710 int objectId = 0;
9711 // Not a '/' separated full component name; maybe an object ID?
9712 try {
9713 objectId = Integer.parseInt(name, 16);
9714 if (objects == null) {
9715 objects = new ArrayList<Integer>();
9716 }
9717 objects.add(objectId);
9718 all = false;
9719 } catch (RuntimeException e) {
9720 // Not an integer; just do string match.
9721 if (strings == null) {
9722 strings = new ArrayList<String>();
9723 }
9724 strings.add(name);
9725 all = false;
9726 }
9727 }
9728 }
9729
9730 int build(String[] args, int opti) {
9731 for (; opti<args.length; opti++) {
9732 String name = args[opti];
9733 if ("--".equals(name)) {
9734 return opti+1;
9735 }
9736 build(name);
9737 }
9738 return opti;
9739 }
9740
9741 boolean match(Object object, ComponentName comp) {
9742 if (all) {
9743 return true;
9744 }
9745 if (components != null) {
9746 for (int i=0; i<components.size(); i++) {
9747 if (components.get(i).equals(comp)) {
9748 return true;
9749 }
9750 }
9751 }
9752 if (objects != null) {
9753 for (int i=0; i<objects.size(); i++) {
9754 if (System.identityHashCode(object) == objects.get(i)) {
9755 return true;
9756 }
9757 }
9758 }
9759 if (strings != null) {
9760 String flat = comp.flattenToString();
9761 for (int i=0; i<strings.size(); i++) {
9762 if (flat.contains(strings.get(i))) {
9763 return true;
9764 }
9765 }
9766 }
9767 return false;
9768 }
9769 }
9770
Dianne Hackborn625ac272010-09-17 18:29:22 -07009771 /**
9772 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009773 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009774 * - the cmd arg isn't the flattened component name of an existing activity:
9775 * dump all activity whose component contains the cmd as a substring
9776 * - A hex number of the ActivityRecord object instance.
9777 */
9778 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9779 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009780 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009781
9782 if ("all".equals(name)) {
9783 synchronized (this) {
9784 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009785 activities.add(r1);
9786 }
9787 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009788 } else if ("top".equals(name)) {
9789 synchronized (this) {
9790 final int N = mMainStack.mHistory.size();
9791 if (N > 0) {
9792 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9793 }
9794 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009795 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009796 ItemMatcher matcher = new ItemMatcher();
9797 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009798
9799 synchronized (this) {
9800 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009801 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009802 activities.add(r1);
9803 }
9804 }
9805 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009806 }
9807
9808 if (activities.size() <= 0) {
9809 return false;
9810 }
9811
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009812 String[] newArgs = new String[args.length - opti];
9813 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9814
Dianne Hackborn30d71892010-12-11 10:37:55 -08009815 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009816 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009817 for (int i=activities.size()-1; i>=0; i--) {
9818 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009819 if (needSep) {
9820 pw.println();
9821 }
9822 needSep = true;
9823 synchronized (this) {
9824 if (lastTask != r.task) {
9825 lastTask = r.task;
9826 pw.print("TASK "); pw.print(lastTask.affinity);
9827 pw.print(" id="); pw.println(lastTask.taskId);
9828 if (dumpAll) {
9829 lastTask.dump(pw, " ");
9830 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009831 }
9832 }
9833 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009834 }
9835 return true;
9836 }
9837
9838 /**
9839 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9840 * there is a thread associated with the activity.
9841 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009842 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 final ActivityRecord r, String[] args, boolean dumpAll) {
9844 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009845 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009846 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9847 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9848 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009849 if (r.app != null) pw.println(r.app.pid);
9850 else pw.println("(not running)");
9851 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009852 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009853 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009854 }
9855 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009856 // flush anything that is already in the PrintWriter since the thread is going
9857 // to write to the file descriptor directly
9858 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009859 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 TransferPipe tp = new TransferPipe();
9861 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009862 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9863 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009864 tp.go(fd);
9865 } finally {
9866 tp.kill();
9867 }
9868 } catch (IOException e) {
9869 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009870 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009871 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009872 }
9873 }
9874 }
9875
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009876 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009877 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009878 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009879 boolean onlyHistory = false;
9880
9881 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009882 if (opti < args.length && "-s".equals(args[opti])) {
9883 dumpAll = false;
9884 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009885 onlyHistory = true;
9886 dumpPackage = null;
9887 }
9888
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009889 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009890 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009891 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009892 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009893 Iterator it = mRegisteredReceivers.values().iterator();
9894 while (it.hasNext()) {
9895 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009896 if (dumpPackage != null && (r.app == null ||
9897 !dumpPackage.equals(r.app.info.packageName))) {
9898 continue;
9899 }
9900 if (!printed) {
9901 pw.println(" Registered Receivers:");
9902 needSep = true;
9903 printed = true;
9904 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009905 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009906 r.dump(pw, " ");
9907 }
9908 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009909
9910 if (mReceiverResolver.dump(pw, needSep ?
9911 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9912 " ", dumpPackage, false)) {
9913 needSep = true;
9914 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009915 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009916
9917 for (BroadcastQueue q : mBroadcastQueues) {
9918 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009920
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009921 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009922
Dianne Hackborn786b4402012-08-27 15:14:02 -07009923 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009924 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9925 if (needSep) {
9926 pw.println();
9927 }
9928 needSep = true;
9929 pw.print(" Sticky broadcasts for user ");
9930 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9931 StringBuilder sb = new StringBuilder(128);
9932 for (Map.Entry<String, ArrayList<Intent>> ent
9933 : mStickyBroadcasts.valueAt(user).entrySet()) {
9934 pw.print(" * Sticky action "); pw.print(ent.getKey());
9935 if (dumpAll) {
9936 pw.println(":");
9937 ArrayList<Intent> intents = ent.getValue();
9938 final int N = intents.size();
9939 for (int i=0; i<N; i++) {
9940 sb.setLength(0);
9941 sb.append(" Intent: ");
9942 intents.get(i).toShortString(sb, false, true, false, false);
9943 pw.println(sb.toString());
9944 Bundle bundle = intents.get(i).getExtras();
9945 if (bundle != null) {
9946 pw.print(" ");
9947 pw.println(bundle.toString());
9948 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009949 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009950 } else {
9951 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009952 }
9953 }
9954 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009955 }
9956
Dianne Hackborn786b4402012-08-27 15:14:02 -07009957 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009958 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009959 for (BroadcastQueue queue : mBroadcastQueues) {
9960 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9961 + queue.mBroadcastsScheduled);
9962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009963 pw.println(" mHandler:");
9964 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009965 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009967
9968 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009969 }
9970
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009971 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009972 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009973 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009974
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009975 ItemMatcher matcher = new ItemMatcher();
9976 matcher.build(args, opti);
9977
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009978 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009979
9980 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009981
9982 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009983 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009984 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009985 ContentProviderRecord r = mLaunchingProviders.get(i);
9986 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9987 continue;
9988 }
9989 if (!printed) {
9990 if (needSep) pw.println(" ");
9991 needSep = true;
9992 pw.println(" Launching content providers:");
9993 printed = true;
9994 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009995 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009996 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009997 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009998 }
9999
10000 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010001 if (needSep) pw.println();
10002 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010003 pw.println("Granted Uri Permissions:");
10004 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
10005 int uid = mGrantedUriPermissions.keyAt(i);
10006 HashMap<Uri, UriPermission> perms
10007 = mGrantedUriPermissions.valueAt(i);
10008 pw.print(" * UID "); pw.print(uid);
10009 pw.println(" holds:");
10010 for (UriPermission perm : perms.values()) {
10011 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010012 if (dumpAll) {
10013 perm.dump(pw, " ");
10014 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010015 }
10016 }
10017 needSep = true;
10018 }
10019
10020 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010021 }
10022
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010023 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010024 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010025 boolean needSep = false;
10026
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010027 if (mIntentSenderRecords.size() > 0) {
10028 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010029 Iterator<WeakReference<PendingIntentRecord>> it
10030 = mIntentSenderRecords.values().iterator();
10031 while (it.hasNext()) {
10032 WeakReference<PendingIntentRecord> ref = it.next();
10033 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010034 if (dumpPackage != null && (rec == null
10035 || !dumpPackage.equals(rec.key.packageName))) {
10036 continue;
10037 }
10038 if (!printed) {
10039 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10040 printed = true;
10041 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010042 needSep = true;
10043 if (rec != null) {
10044 pw.print(" * "); pw.println(rec);
10045 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010046 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010048 } else {
10049 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010050 }
10051 }
10052 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010053
10054 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010055 }
10056
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010057 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010058 String prefix, String label, boolean complete, boolean brief, boolean client,
10059 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010061 boolean needNL = false;
10062 final String innerPrefix = prefix + " ";
10063 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010064 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010065 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010066 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10067 continue;
10068 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010069 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010070 if (needNL) {
10071 pw.println(" ");
10072 needNL = false;
10073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010074 if (lastTask != r.task) {
10075 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010076 pw.print(prefix);
10077 pw.print(full ? "* " : " ");
10078 pw.println(lastTask);
10079 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010080 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010081 } else if (complete) {
10082 // Complete + brief == give a summary. Isn't that obvious?!?
10083 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010084 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010085 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010086 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010088 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010089 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10090 pw.print(" #"); pw.print(i); pw.print(": ");
10091 pw.println(r);
10092 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010093 r.dump(pw, innerPrefix);
10094 } else if (complete) {
10095 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010096 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010097 if (r.app != null) {
10098 pw.print(innerPrefix); pw.println(r.app);
10099 }
10100 }
10101 if (client && r.app != null && r.app.thread != null) {
10102 // flush anything that is already in the PrintWriter since the thread is going
10103 // to write to the file descriptor directly
10104 pw.flush();
10105 try {
10106 TransferPipe tp = new TransferPipe();
10107 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010108 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10109 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010110 // Short timeout, since blocking here can
10111 // deadlock with the application.
10112 tp.go(fd, 2000);
10113 } finally {
10114 tp.kill();
10115 }
10116 } catch (IOException e) {
10117 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10118 } catch (RemoteException e) {
10119 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10120 }
10121 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010123 }
10124 }
10125
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010126 private static String buildOomTag(String prefix, String space, int val, int base) {
10127 if (val == base) {
10128 if (space == null) return prefix;
10129 return prefix + " ";
10130 }
10131 return prefix + "+" + Integer.toString(val-base);
10132 }
10133
10134 private static final int dumpProcessList(PrintWriter pw,
10135 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010136 String prefix, String normalLabel, String persistentLabel,
10137 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010138 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010139 final int N = list.size()-1;
10140 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010141 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010142 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10143 continue;
10144 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010145 pw.println(String.format("%s%s #%2d: %s",
10146 prefix, (r.persistent ? persistentLabel : normalLabel),
10147 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010148 if (r.persistent) {
10149 numPers++;
10150 }
10151 }
10152 return numPers;
10153 }
10154
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010155 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010156 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010157 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010158 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010159
Dianne Hackborn905577f2011-09-07 18:31:28 -070010160 ArrayList<Pair<ProcessRecord, Integer>> list
10161 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10162 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010163 ProcessRecord r = origList.get(i);
10164 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10165 continue;
10166 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010167 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10168 }
10169
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010170 if (list.size() <= 0) {
10171 return false;
10172 }
10173
Dianne Hackborn905577f2011-09-07 18:31:28 -070010174 Comparator<Pair<ProcessRecord, Integer>> comparator
10175 = new Comparator<Pair<ProcessRecord, Integer>>() {
10176 @Override
10177 public int compare(Pair<ProcessRecord, Integer> object1,
10178 Pair<ProcessRecord, Integer> object2) {
10179 if (object1.first.setAdj != object2.first.setAdj) {
10180 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10181 }
10182 if (object1.second.intValue() != object2.second.intValue()) {
10183 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10184 }
10185 return 0;
10186 }
10187 };
10188
10189 Collections.sort(list, comparator);
10190
Dianne Hackborn287952c2010-09-22 22:34:31 -070010191 final long curRealtime = SystemClock.elapsedRealtime();
10192 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10193 final long curUptime = SystemClock.uptimeMillis();
10194 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10195
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010196 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010197 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010198 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010199 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010200 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010201 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10202 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010203 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10204 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010205 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10206 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010207 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10208 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010209 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010210 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010211 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10212 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10213 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10214 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10215 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10216 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10217 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10218 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010219 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10220 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010221 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10222 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010223 } else {
10224 oomAdj = Integer.toString(r.setAdj);
10225 }
10226 String schedGroup;
10227 switch (r.setSchedGroup) {
10228 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10229 schedGroup = "B";
10230 break;
10231 case Process.THREAD_GROUP_DEFAULT:
10232 schedGroup = "F";
10233 break;
10234 default:
10235 schedGroup = Integer.toString(r.setSchedGroup);
10236 break;
10237 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010238 String foreground;
10239 if (r.foregroundActivities) {
10240 foreground = "A";
10241 } else if (r.foregroundServices) {
10242 foreground = "S";
10243 } else {
10244 foreground = " ";
10245 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010246 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010247 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010248 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10249 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010250 if (r.adjSource != null || r.adjTarget != null) {
10251 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010252 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010253 if (r.adjTarget instanceof ComponentName) {
10254 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10255 } else if (r.adjTarget != null) {
10256 pw.print(r.adjTarget.toString());
10257 } else {
10258 pw.print("{null}");
10259 }
10260 pw.print("<=");
10261 if (r.adjSource instanceof ProcessRecord) {
10262 pw.print("Proc{");
10263 pw.print(((ProcessRecord)r.adjSource).toShortString());
10264 pw.println("}");
10265 } else if (r.adjSource != null) {
10266 pw.println(r.adjSource.toString());
10267 } else {
10268 pw.println("{null}");
10269 }
10270 }
10271 if (inclDetails) {
10272 pw.print(prefix);
10273 pw.print(" ");
10274 pw.print("oom: max="); pw.print(r.maxAdj);
10275 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010276 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010277 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010278 pw.print(" curRaw="); pw.print(r.curRawAdj);
10279 pw.print(" setRaw="); pw.print(r.setRawAdj);
10280 pw.print(" cur="); pw.print(r.curAdj);
10281 pw.print(" set="); pw.println(r.setAdj);
10282 pw.print(prefix);
10283 pw.print(" ");
10284 pw.print("keeping="); pw.print(r.keeping);
10285 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010286 pw.print(" empty="); pw.print(r.empty);
10287 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010288
10289 if (!r.keeping) {
10290 if (r.lastWakeTime != 0) {
10291 long wtime;
10292 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10293 synchronized (stats) {
10294 wtime = stats.getProcessWakeTime(r.info.uid,
10295 r.pid, curRealtime);
10296 }
10297 long timeUsed = wtime - r.lastWakeTime;
10298 pw.print(prefix);
10299 pw.print(" ");
10300 pw.print("keep awake over ");
10301 TimeUtils.formatDuration(realtimeSince, pw);
10302 pw.print(" used ");
10303 TimeUtils.formatDuration(timeUsed, pw);
10304 pw.print(" (");
10305 pw.print((timeUsed*100)/realtimeSince);
10306 pw.println("%)");
10307 }
10308 if (r.lastCpuTime != 0) {
10309 long timeUsed = r.curCpuTime - r.lastCpuTime;
10310 pw.print(prefix);
10311 pw.print(" ");
10312 pw.print("run cpu over ");
10313 TimeUtils.formatDuration(uptimeSince, pw);
10314 pw.print(" used ");
10315 TimeUtils.formatDuration(timeUsed, pw);
10316 pw.print(" (");
10317 pw.print((timeUsed*100)/uptimeSince);
10318 pw.println("%)");
10319 }
10320 }
10321 }
10322 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010323 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010324 }
10325
Dianne Hackbornb437e092011-08-05 17:50:29 -070010326 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010327 ArrayList<ProcessRecord> procs;
10328 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010329 if (args != null && args.length > start
10330 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010331 procs = new ArrayList<ProcessRecord>();
10332 int pid = -1;
10333 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010334 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010335 } catch (NumberFormatException e) {
10336
10337 }
10338 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10339 ProcessRecord proc = mLruProcesses.get(i);
10340 if (proc.pid == pid) {
10341 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010342 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010343 procs.add(proc);
10344 }
10345 }
10346 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010347 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010348 return null;
10349 }
10350 } else {
10351 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10352 }
10353 }
10354 return procs;
10355 }
10356
10357 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10358 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010359 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010360 if (procs == null) {
10361 return;
10362 }
10363
10364 long uptime = SystemClock.uptimeMillis();
10365 long realtime = SystemClock.elapsedRealtime();
10366 pw.println("Applications Graphics Acceleration Info:");
10367 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10368
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010369 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10370 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010371 if (r.thread != null) {
10372 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10373 pw.flush();
10374 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010375 TransferPipe tp = new TransferPipe();
10376 try {
10377 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10378 tp.go(fd);
10379 } finally {
10380 tp.kill();
10381 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010382 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010383 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010384 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010385 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010386 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010387 pw.flush();
10388 }
10389 }
10390 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010391 }
10392
Jeff Brown6754ba22011-12-14 20:20:01 -080010393 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10394 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10395 if (procs == null) {
10396 return;
10397 }
10398
10399 pw.println("Applications Database Info:");
10400
10401 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10402 ProcessRecord r = procs.get(i);
10403 if (r.thread != null) {
10404 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10405 pw.flush();
10406 try {
10407 TransferPipe tp = new TransferPipe();
10408 try {
10409 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10410 tp.go(fd);
10411 } finally {
10412 tp.kill();
10413 }
10414 } catch (IOException e) {
10415 pw.println("Failure while dumping the app: " + r);
10416 pw.flush();
10417 } catch (RemoteException e) {
10418 pw.println("Got a RemoteException while dumping the app " + r);
10419 pw.flush();
10420 }
10421 }
10422 }
10423 }
10424
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010425 final static class MemItem {
10426 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010427 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010428 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010429 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010430 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010431
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010432 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010433 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010434 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010435 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010436 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010437 }
10438 }
10439
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010440 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010441 boolean sort) {
10442 if (sort) {
10443 Collections.sort(items, new Comparator<MemItem>() {
10444 @Override
10445 public int compare(MemItem lhs, MemItem rhs) {
10446 if (lhs.pss < rhs.pss) {
10447 return 1;
10448 } else if (lhs.pss > rhs.pss) {
10449 return -1;
10450 }
10451 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010452 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010453 });
10454 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010455
10456 for (int i=0; i<items.size(); i++) {
10457 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010458 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010459 if (mi.subitems != null) {
10460 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10461 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010462 }
10463 }
10464
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010465 // These are in KB.
10466 static final long[] DUMP_MEM_BUCKETS = new long[] {
10467 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10468 120*1024, 160*1024, 200*1024,
10469 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10470 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10471 };
10472
Dianne Hackborn672342c2011-11-29 11:29:02 -080010473 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10474 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010475 int start = label.lastIndexOf('.');
10476 if (start >= 0) start++;
10477 else start = 0;
10478 int end = label.length();
10479 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10480 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10481 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10482 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010483 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010484 out.append(label, start, end);
10485 return;
10486 }
10487 }
10488 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010489 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010490 out.append(label, start, end);
10491 }
10492
10493 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10494 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10495 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10496 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10497 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10498 };
10499 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10500 "System", "Persistent", "Foreground",
10501 "Visible", "Perceptible", "Heavy Weight",
10502 "Backup", "A Services", "Home", "Previous",
10503 "B Services", "Background"
10504 };
10505
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010506 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010507 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010508 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010509 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010510 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010511
10512 int opti = 0;
10513 while (opti < args.length) {
10514 String opt = args[opti];
10515 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10516 break;
10517 }
10518 opti++;
10519 if ("-a".equals(opt)) {
10520 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010521 } else if ("--oom".equals(opt)) {
10522 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010523 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010524 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010525 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010526 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010527 pw.println("If [process] is specified it can be the name or ");
10528 pw.println("pid of a specific process to dump.");
10529 return;
10530 } else {
10531 pw.println("Unknown argument: " + opt + "; use -h for help");
10532 }
10533 }
10534
10535 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010536 if (procs == null) {
10537 return;
10538 }
10539
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010540 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010541 long uptime = SystemClock.uptimeMillis();
10542 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010543
10544 if (procs.size() == 1 || isCheckinRequest) {
10545 dumpAll = true;
10546 }
10547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010548 if (isCheckinRequest) {
10549 // short checkin version
10550 pw.println(uptime + "," + realtime);
10551 pw.flush();
10552 } else {
10553 pw.println("Applications Memory Usage (kB):");
10554 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10555 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010556
Dianne Hackbornb437e092011-08-05 17:50:29 -070010557 String[] innerArgs = new String[args.length-opti];
10558 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10559
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010560 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10561 long nativePss=0, dalvikPss=0, otherPss=0;
10562 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10563
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010564 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10565 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10566 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010567
10568 long totalPss = 0;
10569
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010570 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10571 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010573 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10575 pw.flush();
10576 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010577 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010578 if (dumpAll) {
10579 try {
10580 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10581 } catch (RemoteException e) {
10582 if (!isCheckinRequest) {
10583 pw.println("Got RemoteException!");
10584 pw.flush();
10585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010587 } else {
10588 mi = new Debug.MemoryInfo();
10589 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010590 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010591
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010592 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010593 long myTotalPss = mi.getTotalPss();
10594 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010595 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010596 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010597 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010598
10599 nativePss += mi.nativePss;
10600 dalvikPss += mi.dalvikPss;
10601 otherPss += mi.otherPss;
10602 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10603 long mem = mi.getOtherPss(j);
10604 miscPss[j] += mem;
10605 otherPss -= mem;
10606 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010607
10608 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010609 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10610 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010611 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010612 if (oomProcs[oomIndex] == null) {
10613 oomProcs[oomIndex] = new ArrayList<MemItem>();
10614 }
10615 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010616 break;
10617 }
10618 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010620 }
10621 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010622
10623 if (!isCheckinRequest && procs.size() > 1) {
10624 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10625
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010626 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10627 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10628 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010629 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010630 String label = Debug.MemoryInfo.getOtherLabel(j);
10631 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010632 }
10633
Dianne Hackbornb437e092011-08-05 17:50:29 -070010634 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10635 for (int j=0; j<oomPss.length; j++) {
10636 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010637 String label = DUMP_MEM_OOM_LABEL[j];
10638 MemItem item = new MemItem(label, label, oomPss[j],
10639 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010640 item.subitems = oomProcs[j];
10641 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010642 }
10643 }
10644
Dianne Hackborn672342c2011-11-29 11:29:02 -080010645 if (outTag != null || outStack != null) {
10646 if (outTag != null) {
10647 appendMemBucket(outTag, totalPss, "total", false);
10648 }
10649 if (outStack != null) {
10650 appendMemBucket(outStack, totalPss, "total", true);
10651 }
10652 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010653 for (int i=0; i<oomMems.size(); i++) {
10654 MemItem miCat = oomMems.get(i);
10655 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10656 continue;
10657 }
10658 if (miCat.id < ProcessList.SERVICE_ADJ
10659 || miCat.id == ProcessList.HOME_APP_ADJ
10660 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010661 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10662 outTag.append(" / ");
10663 }
10664 if (outStack != null) {
10665 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10666 if (firstLine) {
10667 outStack.append(":");
10668 firstLine = false;
10669 }
10670 outStack.append("\n\t at ");
10671 } else {
10672 outStack.append("$");
10673 }
10674 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010675 for (int j=0; j<miCat.subitems.size(); j++) {
10676 MemItem mi = miCat.subitems.get(j);
10677 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010678 if (outTag != null) {
10679 outTag.append(" ");
10680 }
10681 if (outStack != null) {
10682 outStack.append("$");
10683 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010684 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010685 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10686 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10687 }
10688 if (outStack != null) {
10689 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10690 }
10691 }
10692 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10693 outStack.append("(");
10694 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10695 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10696 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10697 outStack.append(":");
10698 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10699 }
10700 }
10701 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010702 }
10703 }
10704 }
10705 }
10706
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010707 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010708 pw.println();
10709 pw.println("Total PSS by process:");
10710 dumpMemItems(pw, " ", procMems, true);
10711 pw.println();
10712 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010713 pw.println("Total PSS by OOM adjustment:");
10714 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010715 if (!oomOnly) {
10716 PrintWriter out = categoryPw != null ? categoryPw : pw;
10717 out.println();
10718 out.println("Total PSS by category:");
10719 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010720 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010721 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010722 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010723 final int[] SINGLE_LONG_FORMAT = new int[] {
10724 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10725 };
10726 long[] longOut = new long[1];
10727 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10728 SINGLE_LONG_FORMAT, null, longOut, null);
10729 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10730 longOut[0] = 0;
10731 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10732 SINGLE_LONG_FORMAT, null, longOut, null);
10733 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10734 longOut[0] = 0;
10735 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10736 SINGLE_LONG_FORMAT, null, longOut, null);
10737 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10738 longOut[0] = 0;
10739 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10740 SINGLE_LONG_FORMAT, null, longOut, null);
10741 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10742 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10743 pw.print(shared); pw.println(" kB");
10744 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10745 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010747 }
10748
10749 /**
10750 * Searches array of arguments for the specified string
10751 * @param args array of argument strings
10752 * @param value value to search for
10753 * @return true if the value is contained in the array
10754 */
10755 private static boolean scanArgs(String[] args, String value) {
10756 if (args != null) {
10757 for (String arg : args) {
10758 if (value.equals(arg)) {
10759 return true;
10760 }
10761 }
10762 }
10763 return false;
10764 }
10765
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010766 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10767 ContentProviderRecord cpr, boolean always) {
10768 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10769
10770 if (!inLaunching || always) {
10771 synchronized (cpr) {
10772 cpr.launchingApp = null;
10773 cpr.notifyAll();
10774 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010775 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010776 String names[] = cpr.info.authority.split(";");
10777 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010778 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 }
10780 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010781
10782 for (int i=0; i<cpr.connections.size(); i++) {
10783 ContentProviderConnection conn = cpr.connections.get(i);
10784 if (conn.waiting) {
10785 // If this connection is waiting for the provider, then we don't
10786 // need to mess with its process unless we are always removing
10787 // or for some reason the provider is not currently launching.
10788 if (inLaunching && !always) {
10789 continue;
10790 }
10791 }
10792 ProcessRecord capp = conn.client;
10793 conn.dead = true;
10794 if (conn.stableCount > 0) {
10795 if (!capp.persistent && capp.thread != null
10796 && capp.pid != 0
10797 && capp.pid != MY_PID) {
10798 Slog.i(TAG, "Kill " + capp.processName
10799 + " (pid " + capp.pid + "): provider " + cpr.info.name
10800 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010801 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010802 capp.processName, capp.setAdj, "dying provider "
10803 + cpr.name.toShortString());
10804 Process.killProcessQuiet(capp.pid);
10805 }
10806 } else if (capp.thread != null && conn.provider.provider != null) {
10807 try {
10808 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10809 } catch (RemoteException e) {
10810 }
10811 // In the protocol here, we don't expect the client to correctly
10812 // clean up this connection, we'll just remove it.
10813 cpr.connections.remove(i);
10814 conn.client.conProviders.remove(conn);
10815 }
10816 }
10817
10818 if (inLaunching && always) {
10819 mLaunchingProviders.remove(cpr);
10820 }
10821 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 }
10823
10824 /**
10825 * Main code for cleaning up a process when it has gone away. This is
10826 * called both as a result of the process dying, or directly when stopping
10827 * a process when running in single process mode.
10828 */
10829 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010830 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010832 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 }
10834
Dianne Hackborn36124872009-10-08 16:22:03 -070010835 mProcessesToGc.remove(app);
10836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 // Dismiss any open dialogs.
10838 if (app.crashDialog != null) {
10839 app.crashDialog.dismiss();
10840 app.crashDialog = null;
10841 }
10842 if (app.anrDialog != null) {
10843 app.anrDialog.dismiss();
10844 app.anrDialog = null;
10845 }
10846 if (app.waitDialog != null) {
10847 app.waitDialog.dismiss();
10848 app.waitDialog = null;
10849 }
10850
10851 app.crashing = false;
10852 app.notResponding = false;
10853
10854 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010855 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 app.thread = null;
10857 app.forcingToForeground = null;
10858 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010859 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010860 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010861 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010863 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010864
10865 boolean restart = false;
10866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 // Remove published content providers.
10868 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010869 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010871 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010872
10873 final boolean always = app.bad || !allowRestart;
10874 if (removeDyingProviderLocked(app, cpr, always) || always) {
10875 // We left the provider in the launching list, need to
10876 // restart it.
10877 restart = true;
10878 }
10879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010881 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 }
10883 app.pubProviders.clear();
10884 }
10885
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010886 // Take care of any launching providers waiting for this process.
10887 if (checkAppInLaunchingProvidersLocked(app, false)) {
10888 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010889 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 // Unregister from connected content providers.
10892 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010893 for (int i=0; i<app.conProviders.size(); i++) {
10894 ContentProviderConnection conn = app.conProviders.get(i);
10895 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010896 }
10897 app.conProviders.clear();
10898 }
10899
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010900 // At this point there may be remaining entries in mLaunchingProviders
10901 // where we were the only one waiting, so they are no longer of use.
10902 // Look for these and clean up if found.
10903 // XXX Commented out for now. Trying to figure out a way to reproduce
10904 // the actual situation to identify what is actually going on.
10905 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010906 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010907 ContentProviderRecord cpr = (ContentProviderRecord)
10908 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010909 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010910 synchronized (cpr) {
10911 cpr.launchingApp = null;
10912 cpr.notifyAll();
10913 }
10914 }
10915 }
10916 }
10917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010918 skipCurrentReceiverLocked(app);
10919
10920 // Unregister any receivers.
10921 if (app.receivers.size() > 0) {
10922 Iterator<ReceiverList> it = app.receivers.iterator();
10923 while (it.hasNext()) {
10924 removeReceiverLocked(it.next());
10925 }
10926 app.receivers.clear();
10927 }
10928
Christopher Tate181fafa2009-05-14 11:12:14 -070010929 // If the app is undergoing backup, tell the backup manager about it
10930 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010931 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10932 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010933 try {
10934 IBackupManager bm = IBackupManager.Stub.asInterface(
10935 ServiceManager.getService(Context.BACKUP_SERVICE));
10936 bm.agentDisconnected(app.info.packageName);
10937 } catch (RemoteException e) {
10938 // can't happen; backup manager is local
10939 }
10940 }
10941
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010942 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10943 ProcessChangeItem item = mPendingProcessChanges.get(i);
10944 if (item.pid == app.pid) {
10945 mPendingProcessChanges.remove(i);
10946 mAvailProcessChanges.add(item);
10947 }
10948 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010949 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 // If the caller is restarting this app, then leave it in its
10952 // current lists and let the caller take care of it.
10953 if (restarting) {
10954 return;
10955 }
10956
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010957 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010958 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010960 mProcessNames.remove(app.processName, app.uid);
10961 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010962 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010963 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10964 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010965 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010967 } else if (!app.removed) {
10968 // This app is persistent, so we need to keep its record around.
10969 // If it is not already on the pending app list, add it there
10970 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10972 mPersistentStartingProcesses.add(app);
10973 restart = true;
10974 }
10975 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010976 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010977 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010978 mProcessesOnHold.remove(app);
10979
The Android Open Source Project4df24232009-03-05 14:34:35 -080010980 if (app == mHomeProcess) {
10981 mHomeProcess = null;
10982 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010983 if (app == mPreviousProcess) {
10984 mPreviousProcess = null;
10985 }
10986
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010987 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010988 // We have components that still need to be running in the
10989 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010990 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 startProcessLocked(app, "restart", app.processName);
10992 } else if (app.pid > 0 && app.pid != MY_PID) {
10993 // Goodbye!
10994 synchronized (mPidsSelfLocked) {
10995 mPidsSelfLocked.remove(app.pid);
10996 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10997 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010998 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 }
11000 }
11001
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011002 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
11003 // Look through the content providers we are waiting to have launched,
11004 // and if any run in this process then either schedule a restart of
11005 // the process or kill the client waiting for it if this process has
11006 // gone bad.
11007 int NL = mLaunchingProviders.size();
11008 boolean restart = false;
11009 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011010 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011011 if (cpr.launchingApp == app) {
11012 if (!alwaysBad && !app.bad) {
11013 restart = true;
11014 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011015 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011016 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011017 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011018 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011019 }
11020 }
11021 }
11022 return restart;
11023 }
11024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 // =========================================================
11026 // SERVICES
11027 // =========================================================
11028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11030 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011031 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011033 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011034 }
11035 }
11036
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011037 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011038 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011039 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011040 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011041 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011042 }
11043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011045 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011046 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047 // Refuse possible leaked file descriptors
11048 if (service != null && service.hasFileDescriptors() == true) {
11049 throw new IllegalArgumentException("File descriptors passed in Intent");
11050 }
11051
Amith Yamasani742a6712011-05-04 14:49:28 -070011052 if (DEBUG_SERVICE)
11053 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011054 synchronized(this) {
11055 final int callingPid = Binder.getCallingPid();
11056 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011057 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011058 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011059 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011060 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 Binder.restoreCallingIdentity(origId);
11062 return res;
11063 }
11064 }
11065
11066 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070011067 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011068 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011069 if (DEBUG_SERVICE)
11070 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011071 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011072 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070011073 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011074 Binder.restoreCallingIdentity(origId);
11075 return res;
11076 }
11077 }
11078
11079 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011080 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011081 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 // Refuse possible leaked file descriptors
11083 if (service != null && service.hasFileDescriptors() == true) {
11084 throw new IllegalArgumentException("File descriptors passed in Intent");
11085 }
11086
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011087 checkValidCaller(Binder.getCallingUid(), userId);
11088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011090 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 }
11093
11094 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011095 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096 // Refuse possible leaked file descriptors
11097 if (service != null && service.hasFileDescriptors() == true) {
11098 throw new IllegalArgumentException("File descriptors passed in Intent");
11099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011101 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 }
11104
11105 public boolean stopServiceToken(ComponentName className, IBinder token,
11106 int startId) {
11107 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011108 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 }
11111
11112 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011113 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011115 mServices.setServiceForegroundLocked(className, token, id, notification,
11116 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 }
11118 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011119
Dianne Hackborn41203752012-08-31 14:05:51 -070011120 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11121 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011122 final int callingUserId = UserHandle.getUserId(callingUid);
11123 if (callingUserId != userId) {
11124 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11125 if ((requireFull || checkComponentPermission(
11126 android.Manifest.permission.INTERACT_ACROSS_USERS,
11127 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
11128 && checkComponentPermission(
11129 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11130 callingPid, callingUid, -1, true)
11131 != PackageManager.PERMISSION_GRANTED) {
11132 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11133 // In this case, they would like to just execute as their
11134 // owner user instead of failing.
11135 userId = callingUserId;
11136 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011137 StringBuilder builder = new StringBuilder(128);
11138 builder.append("Permission Denial: ");
11139 builder.append(name);
11140 if (callerPackage != null) {
11141 builder.append(" from ");
11142 builder.append(callerPackage);
11143 }
11144 builder.append(" asks to run as user ");
11145 builder.append(userId);
11146 builder.append(" but is calling from user ");
11147 builder.append(UserHandle.getUserId(callingUid));
11148 builder.append("; this requires ");
11149 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11150 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011151 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011152 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11153 }
11154 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011155 Slog.w(TAG, msg);
11156 throw new SecurityException(msg);
11157 }
11158 }
11159 }
11160 if (userId == UserHandle.USER_CURRENT
11161 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011162 // Note that we may be accessing this outside of a lock...
11163 // shouldn't be a big deal, if this is being called outside
11164 // of a locked context there is intrinsically a race with
11165 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011166 userId = mCurrentUserId;
11167 }
11168 if (!allowAll && userId < 0) {
11169 throw new IllegalArgumentException(
11170 "Call does not support special user #" + userId);
11171 }
11172 }
11173 return userId;
11174 }
11175
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011176 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11177 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011178 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011179 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011180 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11181 if (ActivityManager.checkUidPermission(
11182 android.Manifest.permission.INTERACT_ACROSS_USERS,
11183 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11184 ComponentName comp = new ComponentName(aInfo.packageName, className);
11185 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11186 + " requests FLAG_SINGLE_USER, but app does not hold "
11187 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11188 Slog.w(TAG, msg);
11189 throw new SecurityException(msg);
11190 }
11191 result = true;
11192 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011193 } else if (componentProcessName == aInfo.packageName) {
11194 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11195 } else if ("system".equals(componentProcessName)) {
11196 result = true;
11197 }
11198 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011199 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11200 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011201 }
11202 return result;
11203 }
11204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011205 public int bindService(IApplicationThread caller, IBinder token,
11206 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011207 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011208 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209 // Refuse possible leaked file descriptors
11210 if (service != null && service.hasFileDescriptors() == true) {
11211 throw new IllegalArgumentException("File descriptors passed in Intent");
11212 }
11213
11214 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011215 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11216 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217 }
11218 }
11219
11220 public boolean unbindService(IServiceConnection connection) {
11221 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011222 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 }
11225
11226 public void publishService(IBinder token, Intent intent, IBinder service) {
11227 // Refuse possible leaked file descriptors
11228 if (intent != null && intent.hasFileDescriptors() == true) {
11229 throw new IllegalArgumentException("File descriptors passed in Intent");
11230 }
11231
11232 synchronized(this) {
11233 if (!(token instanceof ServiceRecord)) {
11234 throw new IllegalArgumentException("Invalid service token");
11235 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011236 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 }
11238 }
11239
11240 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11241 // Refuse possible leaked file descriptors
11242 if (intent != null && intent.hasFileDescriptors() == true) {
11243 throw new IllegalArgumentException("File descriptors passed in Intent");
11244 }
11245
11246 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011247 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 }
11249 }
11250
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011251 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 synchronized(this) {
11253 if (!(token instanceof ServiceRecord)) {
11254 throw new IllegalArgumentException("Invalid service token");
11255 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011256 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011258 }
11259
11260 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011261 // BACKUP AND RESTORE
11262 // =========================================================
11263
11264 // Cause the target app to be launched if necessary and its backup agent
11265 // instantiated. The backup agent will invoke backupAgentCreated() on the
11266 // activity manager to announce its creation.
11267 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011268 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11269 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011270
11271 synchronized(this) {
11272 // !!! TODO: currently no check here that we're already bound
11273 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11274 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11275 synchronized (stats) {
11276 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11277 }
11278
Dianne Hackborne7f97212011-02-24 14:40:20 -080011279 // Backup agent is now in use, its package can't be stopped.
11280 try {
11281 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011282 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011283 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011284 } catch (IllegalArgumentException e) {
11285 Slog.w(TAG, "Failed trying to unstop package "
11286 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011287 }
11288
Christopher Tate181fafa2009-05-14 11:12:14 -070011289 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011290 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11291 ? new ComponentName(app.packageName, app.backupAgentName)
11292 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011293 // startProcessLocked() returns existing proc's record if it's already running
11294 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011295 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011296 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011297 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011298 return false;
11299 }
11300
11301 r.app = proc;
11302 mBackupTarget = r;
11303 mBackupAppName = app.packageName;
11304
Christopher Tate6fa95972009-06-05 18:43:55 -070011305 // Try not to kill the process during backup
11306 updateOomAdjLocked(proc);
11307
Christopher Tate181fafa2009-05-14 11:12:14 -070011308 // If the process is already attached, schedule the creation of the backup agent now.
11309 // If it is not yet live, this will be done when it attaches to the framework.
11310 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011311 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011312 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011313 proc.thread.scheduleCreateBackupAgent(app,
11314 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011315 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011316 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011317 }
11318 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011319 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011320 }
11321 // Invariants: at this point, the target app process exists and the application
11322 // is either already running or in the process of coming up. mBackupTarget and
11323 // mBackupAppName describe the app, so that when it binds back to the AM we
11324 // know that it's scheduled for a backup-agent operation.
11325 }
11326
11327 return true;
11328 }
11329
Christopher Tate346acb12012-10-15 19:20:25 -070011330 @Override
11331 public void clearPendingBackup() {
11332 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11333 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11334
11335 synchronized (this) {
11336 mBackupTarget = null;
11337 mBackupAppName = null;
11338 }
11339 }
11340
Christopher Tate181fafa2009-05-14 11:12:14 -070011341 // A backup agent has just come up
11342 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011343 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011344 + " = " + agent);
11345
11346 synchronized(this) {
11347 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011348 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011349 return;
11350 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011351 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011352
Dianne Hackborn06740692010-09-22 22:46:21 -070011353 long oldIdent = Binder.clearCallingIdentity();
11354 try {
11355 IBackupManager bm = IBackupManager.Stub.asInterface(
11356 ServiceManager.getService(Context.BACKUP_SERVICE));
11357 bm.agentConnected(agentPackageName, agent);
11358 } catch (RemoteException e) {
11359 // can't happen; the backup manager service is local
11360 } catch (Exception e) {
11361 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11362 e.printStackTrace();
11363 } finally {
11364 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011365 }
11366 }
11367
11368 // done with this agent
11369 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011370 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011371 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011372 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011373 return;
11374 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011375
11376 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011377 try {
11378 if (mBackupAppName == null) {
11379 Slog.w(TAG, "Unbinding backup agent with no active backup");
11380 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011381 }
Christopher Tate346acb12012-10-15 19:20:25 -070011382
11383 if (!mBackupAppName.equals(appInfo.packageName)) {
11384 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11385 return;
11386 }
11387
11388 // Not backing this app up any more; reset its OOM adjustment
11389 final ProcessRecord proc = mBackupTarget.app;
11390 updateOomAdjLocked(proc);
11391
11392 // If the app crashed during backup, 'thread' will be null here
11393 if (proc.thread != null) {
11394 try {
11395 proc.thread.scheduleDestroyBackupAgent(appInfo,
11396 compatibilityInfoForPackageLocked(appInfo));
11397 } catch (Exception e) {
11398 Slog.e(TAG, "Exception when unbinding backup agent:");
11399 e.printStackTrace();
11400 }
11401 }
11402 } finally {
11403 mBackupTarget = null;
11404 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011405 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011406 }
11407 }
11408 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011409 // BROADCASTS
11410 // =========================================================
11411
Josh Bartel7f208742010-02-25 11:01:44 -060011412 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011413 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011415 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11416 if (stickies == null) {
11417 return cur;
11418 }
11419 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 if (list == null) {
11421 return cur;
11422 }
11423 int N = list.size();
11424 for (int i=0; i<N; i++) {
11425 Intent intent = list.get(i);
11426 if (filter.match(resolver, intent, true, TAG) >= 0) {
11427 if (cur == null) {
11428 cur = new ArrayList<Intent>();
11429 }
11430 cur.add(intent);
11431 }
11432 }
11433 return cur;
11434 }
11435
Christopher Tatef46723b2012-01-26 14:19:24 -080011436 boolean isPendingBroadcastProcessLocked(int pid) {
11437 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11438 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011440
Christopher Tatef46723b2012-01-26 14:19:24 -080011441 void skipPendingBroadcastLocked(int pid) {
11442 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11443 for (BroadcastQueue queue : mBroadcastQueues) {
11444 queue.skipPendingBroadcastLocked(pid);
11445 }
11446 }
11447
11448 // The app just attached; send any pending broadcasts that it should receive
11449 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11450 boolean didSomething = false;
11451 for (BroadcastQueue queue : mBroadcastQueues) {
11452 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011454 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011455 }
11456
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011457 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011458 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011459 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011460 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011461 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011462 synchronized(this) {
11463 ProcessRecord callerApp = null;
11464 if (caller != null) {
11465 callerApp = getRecordForAppLocked(caller);
11466 if (callerApp == null) {
11467 throw new SecurityException(
11468 "Unable to find app for caller " + caller
11469 + " (pid=" + Binder.getCallingPid()
11470 + ") when registering receiver " + receiver);
11471 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011472 if (callerApp.info.uid != Process.SYSTEM_UID &&
11473 !callerApp.pkgList.contains(callerPackage)) {
11474 throw new SecurityException("Given caller package " + callerPackage
11475 + " is not running in process " + callerApp);
11476 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011477 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011478 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011479 } else {
11480 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011481 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011482 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 }
11484
Dianne Hackborn139748f2012-09-24 11:36:57 -070011485 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011486 true, true, "registerReceiver", callerPackage);
11487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011488 List allSticky = null;
11489
11490 // Look for any matching sticky broadcasts...
11491 Iterator actions = filter.actionsIterator();
11492 if (actions != null) {
11493 while (actions.hasNext()) {
11494 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011495 allSticky = getStickiesLocked(action, filter, allSticky,
11496 UserHandle.USER_ALL);
11497 allSticky = getStickiesLocked(action, filter, allSticky,
11498 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 }
11500 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011501 allSticky = getStickiesLocked(null, filter, allSticky,
11502 UserHandle.USER_ALL);
11503 allSticky = getStickiesLocked(null, filter, allSticky,
11504 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 }
11506
11507 // The first sticky in the list is returned directly back to
11508 // the client.
11509 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11510
Joe Onorato8a9b2202010-02-26 18:56:32 -080011511 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011512 + ": " + sticky);
11513
11514 if (receiver == null) {
11515 return sticky;
11516 }
11517
11518 ReceiverList rl
11519 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11520 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011521 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11522 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011523 if (rl.app != null) {
11524 rl.app.receivers.add(rl);
11525 } else {
11526 try {
11527 receiver.asBinder().linkToDeath(rl, 0);
11528 } catch (RemoteException e) {
11529 return sticky;
11530 }
11531 rl.linkedToDeath = true;
11532 }
11533 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011534 } else if (rl.uid != callingUid) {
11535 throw new IllegalArgumentException(
11536 "Receiver requested to register for uid " + callingUid
11537 + " was previously registered for uid " + rl.uid);
11538 } else if (rl.pid != callingPid) {
11539 throw new IllegalArgumentException(
11540 "Receiver requested to register for pid " + callingPid
11541 + " was previously registered for pid " + rl.pid);
11542 } else if (rl.userId != userId) {
11543 throw new IllegalArgumentException(
11544 "Receiver requested to register for user " + userId
11545 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011547 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011548 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011549 rl.add(bf);
11550 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011551 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011552 }
11553 mReceiverResolver.addFilter(bf);
11554
11555 // Enqueue broadcasts for all existing stickies that match
11556 // this filter.
11557 if (allSticky != null) {
11558 ArrayList receivers = new ArrayList();
11559 receivers.add(bf);
11560
11561 int N = allSticky.size();
11562 for (int i=0; i<N; i++) {
11563 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011564 BroadcastQueue queue = broadcastQueueForIntent(intent);
11565 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011567 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011568 queue.enqueueParallelBroadcastLocked(r);
11569 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570 }
11571 }
11572
11573 return sticky;
11574 }
11575 }
11576
11577 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011578 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011579
Christopher Tatef46723b2012-01-26 14:19:24 -080011580 final long origId = Binder.clearCallingIdentity();
11581 try {
11582 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583
Christopher Tatef46723b2012-01-26 14:19:24 -080011584 synchronized(this) {
11585 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011586 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011587 if (rl != null) {
11588 if (rl.curBroadcast != null) {
11589 BroadcastRecord r = rl.curBroadcast;
11590 final boolean doNext = finishReceiverLocked(
11591 receiver.asBinder(), r.resultCode, r.resultData,
11592 r.resultExtras, r.resultAbort, true);
11593 if (doNext) {
11594 doTrim = true;
11595 r.queue.processNextBroadcast(false);
11596 }
11597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598
Christopher Tatef46723b2012-01-26 14:19:24 -080011599 if (rl.app != null) {
11600 rl.app.receivers.remove(rl);
11601 }
11602 removeReceiverLocked(rl);
11603 if (rl.linkedToDeath) {
11604 rl.linkedToDeath = false;
11605 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 }
11608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609
Christopher Tatef46723b2012-01-26 14:19:24 -080011610 // If we actually concluded any broadcasts, we might now be able
11611 // to trim the recipients' apps from our working set
11612 if (doTrim) {
11613 trimApplications();
11614 return;
11615 }
11616
11617 } finally {
11618 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 }
11621
11622 void removeReceiverLocked(ReceiverList rl) {
11623 mRegisteredReceivers.remove(rl.receiver.asBinder());
11624 int N = rl.size();
11625 for (int i=0; i<N; i++) {
11626 mReceiverResolver.removeFilter(rl.get(i));
11627 }
11628 }
11629
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011630 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011631 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11632 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011633 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011634 try {
11635 r.thread.dispatchPackageBroadcast(cmd, packages);
11636 } catch (RemoteException ex) {
11637 }
11638 }
11639 }
11640 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011641
11642 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11643 int[] users) {
11644 List<ResolveInfo> receivers = null;
11645 try {
11646 HashSet<ComponentName> singleUserReceivers = null;
11647 boolean scannedFirstReceivers = false;
11648 for (int user : users) {
11649 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11650 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011651 if (user != 0 && newReceivers != null) {
11652 // If this is not the primary user, we need to check for
11653 // any receivers that should be filtered out.
11654 for (int i=0; i<newReceivers.size(); i++) {
11655 ResolveInfo ri = newReceivers.get(i);
11656 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11657 newReceivers.remove(i);
11658 i--;
11659 }
11660 }
11661 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011662 if (newReceivers != null && newReceivers.size() == 0) {
11663 newReceivers = null;
11664 }
11665 if (receivers == null) {
11666 receivers = newReceivers;
11667 } else if (newReceivers != null) {
11668 // We need to concatenate the additional receivers
11669 // found with what we have do far. This would be easy,
11670 // but we also need to de-dup any receivers that are
11671 // singleUser.
11672 if (!scannedFirstReceivers) {
11673 // Collect any single user receivers we had already retrieved.
11674 scannedFirstReceivers = true;
11675 for (int i=0; i<receivers.size(); i++) {
11676 ResolveInfo ri = receivers.get(i);
11677 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11678 ComponentName cn = new ComponentName(
11679 ri.activityInfo.packageName, ri.activityInfo.name);
11680 if (singleUserReceivers == null) {
11681 singleUserReceivers = new HashSet<ComponentName>();
11682 }
11683 singleUserReceivers.add(cn);
11684 }
11685 }
11686 }
11687 // Add the new results to the existing results, tracking
11688 // and de-dupping single user receivers.
11689 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011690 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011691 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11692 ComponentName cn = new ComponentName(
11693 ri.activityInfo.packageName, ri.activityInfo.name);
11694 if (singleUserReceivers == null) {
11695 singleUserReceivers = new HashSet<ComponentName>();
11696 }
11697 if (!singleUserReceivers.contains(cn)) {
11698 singleUserReceivers.add(cn);
11699 receivers.add(ri);
11700 }
11701 } else {
11702 receivers.add(ri);
11703 }
11704 }
11705 }
11706 }
11707 } catch (RemoteException ex) {
11708 // pm is in same process, this will never happen.
11709 }
11710 return receivers;
11711 }
11712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 private final int broadcastIntentLocked(ProcessRecord callerApp,
11714 String callerPackage, Intent intent, String resolvedType,
11715 IIntentReceiver resultTo, int resultCode, String resultData,
11716 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011717 boolean ordered, boolean sticky, int callingPid, int callingUid,
11718 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 intent = new Intent(intent);
11720
Dianne Hackborne7f97212011-02-24 14:40:20 -080011721 // By default broadcasts do not go to stopped apps.
11722 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11723
Joe Onorato8a9b2202010-02-26 18:56:32 -080011724 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011725 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011726 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011728 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011729 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011730
Dianne Hackborn139748f2012-09-24 11:36:57 -070011731 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011732 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011733
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011734 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011735 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011736 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011737 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11738 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11739 Slog.w(TAG, "Skipping broadcast of " + intent
11740 + ": user " + userId + " is stopped");
11741 return ActivityManager.BROADCAST_SUCCESS;
11742 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011743 }
11744
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011745 /*
11746 * Prevent non-system code (defined here to be non-persistent
11747 * processes) from sending protected broadcasts.
11748 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011749 int callingAppId = UserHandle.getAppId(callingUid);
11750 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11751 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011752 callingUid == 0) {
11753 // Always okay.
11754 } else if (callerApp == null || !callerApp.persistent) {
11755 try {
11756 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11757 intent.getAction())) {
11758 String msg = "Permission Denial: not allowed to send broadcast "
11759 + intent.getAction() + " from pid="
11760 + callingPid + ", uid=" + callingUid;
11761 Slog.w(TAG, msg);
11762 throw new SecurityException(msg);
11763 }
11764 } catch (RemoteException e) {
11765 Slog.w(TAG, "Remote exception", e);
11766 return ActivityManager.BROADCAST_SUCCESS;
11767 }
11768 }
11769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 // Handle special intents: if this broadcast is from the package
11771 // manager about a package being removed, we need to remove all of
11772 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011773 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011774 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011775 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11776 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011777 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 || uidRemoved) {
11779 if (checkComponentPermission(
11780 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011781 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011782 == PackageManager.PERMISSION_GRANTED) {
11783 if (uidRemoved) {
11784 final Bundle intentExtras = intent.getExtras();
11785 final int uid = intentExtras != null
11786 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11787 if (uid >= 0) {
11788 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11789 synchronized (bs) {
11790 bs.removeUidStatsLocked(uid);
11791 }
11792 }
11793 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011794 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011795 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011796 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011797 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11798 if (list != null && (list.length > 0)) {
11799 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011800 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011801 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011802 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011803 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011804 }
11805 } else {
11806 Uri data = intent.getData();
11807 String ssp;
11808 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11809 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11810 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011811 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11812 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011813 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011814 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011815 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011816 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 }
11819 }
11820 }
11821 } else {
11822 String msg = "Permission Denial: " + intent.getAction()
11823 + " broadcast from " + callerPackage + " (pid=" + callingPid
11824 + ", uid=" + callingUid + ")"
11825 + " requires "
11826 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011827 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 throw new SecurityException(msg);
11829 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011830
11831 // Special case for adding a package: by default turn on compatibility
11832 // mode.
11833 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011834 Uri data = intent.getData();
11835 String ssp;
11836 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11837 mCompatModePackages.handlePackageAddedLocked(ssp,
11838 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011840 }
11841
11842 /*
11843 * If this is the time zone changed action, queue up a message that will reset the timezone
11844 * of all currently running processes. This message will get queued up before the broadcast
11845 * happens.
11846 */
11847 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11848 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11849 }
11850
Robert Greenwalt03595d02010-11-02 14:08:23 -070011851 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11852 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11853 }
11854
Robert Greenwalt434203a2010-10-11 16:00:27 -070011855 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11856 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11857 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11858 }
11859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011860 // Add to the sticky list if requested.
11861 if (sticky) {
11862 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11863 callingPid, callingUid)
11864 != PackageManager.PERMISSION_GRANTED) {
11865 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11866 + callingPid + ", uid=" + callingUid
11867 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011868 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011869 throw new SecurityException(msg);
11870 }
11871 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011872 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011873 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011874 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875 }
11876 if (intent.getComponent() != null) {
11877 throw new SecurityException(
11878 "Sticky broadcasts can't target a specific component");
11879 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011880 // We use userId directly here, since the "all" target is maintained
11881 // as a separate set of sticky broadcasts.
11882 if (userId != UserHandle.USER_ALL) {
11883 // But first, if this is not a broadcast to all users, then
11884 // make sure it doesn't conflict with an existing broadcast to
11885 // all users.
11886 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11887 UserHandle.USER_ALL);
11888 if (stickies != null) {
11889 ArrayList<Intent> list = stickies.get(intent.getAction());
11890 if (list != null) {
11891 int N = list.size();
11892 int i;
11893 for (i=0; i<N; i++) {
11894 if (intent.filterEquals(list.get(i))) {
11895 throw new IllegalArgumentException(
11896 "Sticky broadcast " + intent + " for user "
11897 + userId + " conflicts with existing global broadcast");
11898 }
11899 }
11900 }
11901 }
11902 }
11903 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11904 if (stickies == null) {
11905 stickies = new HashMap<String, ArrayList<Intent>>();
11906 mStickyBroadcasts.put(userId, stickies);
11907 }
11908 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011909 if (list == null) {
11910 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011911 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011912 }
11913 int N = list.size();
11914 int i;
11915 for (i=0; i<N; i++) {
11916 if (intent.filterEquals(list.get(i))) {
11917 // This sticky already exists, replace it.
11918 list.set(i, new Intent(intent));
11919 break;
11920 }
11921 }
11922 if (i >= N) {
11923 list.add(new Intent(intent));
11924 }
11925 }
11926
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011927 int[] users;
11928 if (userId == UserHandle.USER_ALL) {
11929 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011930 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011931 } else {
11932 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011933 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011934 }
11935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 // Figure out who all will receive this broadcast.
11937 List receivers = null;
11938 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011939 // Need to resolve the intent to interested receivers...
11940 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11941 == 0) {
11942 receivers = collectReceiverComponents(intent, resolvedType, users);
11943 }
11944 if (intent.getComponent() == null) {
11945 registeredReceivers = mReceiverResolver.queryIntent(intent,
11946 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 }
11948
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011949 final boolean replacePending =
11950 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11951
Joe Onorato8a9b2202010-02-26 18:56:32 -080011952 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011953 + " replacePending=" + replacePending);
11954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011955 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11956 if (!ordered && NR > 0) {
11957 // If we are not serializing this broadcast, then send the
11958 // registered receivers separately so they don't wait for the
11959 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011960 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11961 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 callerPackage, callingPid, callingUid, requiredPermission,
11963 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011964 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011965 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011966 TAG, "Enqueueing parallel broadcast " + r);
11967 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011968 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011969 queue.enqueueParallelBroadcastLocked(r);
11970 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972 registeredReceivers = null;
11973 NR = 0;
11974 }
11975
11976 // Merge into one list.
11977 int ir = 0;
11978 if (receivers != null) {
11979 // A special case for PACKAGE_ADDED: do not allow the package
11980 // being added to see this broadcast. This prevents them from
11981 // using this as a back door to get run as soon as they are
11982 // installed. Maybe in the future we want to have a special install
11983 // broadcast or such for apps, but we'd like to deliberately make
11984 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011985 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011986 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11987 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11988 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011989 Uri data = intent.getData();
11990 if (data != null) {
11991 String pkgName = data.getSchemeSpecificPart();
11992 if (pkgName != null) {
11993 skipPackages = new String[] { pkgName };
11994 }
11995 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011996 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011997 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011998 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011999 if (skipPackages != null && (skipPackages.length > 0)) {
12000 for (String skipPackage : skipPackages) {
12001 if (skipPackage != null) {
12002 int NT = receivers.size();
12003 for (int it=0; it<NT; it++) {
12004 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12005 if (curt.activityInfo.packageName.equals(skipPackage)) {
12006 receivers.remove(it);
12007 it--;
12008 NT--;
12009 }
12010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012011 }
12012 }
12013 }
12014
12015 int NT = receivers != null ? receivers.size() : 0;
12016 int it = 0;
12017 ResolveInfo curt = null;
12018 BroadcastFilter curr = null;
12019 while (it < NT && ir < NR) {
12020 if (curt == null) {
12021 curt = (ResolveInfo)receivers.get(it);
12022 }
12023 if (curr == null) {
12024 curr = registeredReceivers.get(ir);
12025 }
12026 if (curr.getPriority() >= curt.priority) {
12027 // Insert this broadcast record into the final list.
12028 receivers.add(it, curr);
12029 ir++;
12030 curr = null;
12031 it++;
12032 NT++;
12033 } else {
12034 // Skip to the next ResolveInfo in the final list.
12035 it++;
12036 curt = null;
12037 }
12038 }
12039 }
12040 while (ir < NR) {
12041 if (receivers == null) {
12042 receivers = new ArrayList();
12043 }
12044 receivers.add(registeredReceivers.get(ir));
12045 ir++;
12046 }
12047
12048 if ((receivers != null && receivers.size() > 0)
12049 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012050 BroadcastQueue queue = broadcastQueueForIntent(intent);
12051 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012052 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012053 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070012054 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012055 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012057 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 if (DEBUG_BROADCAST) {
12059 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012060 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012061 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012062 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012063 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012064 queue.enqueueOrderedBroadcastLocked(r);
12065 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012067 }
12068
Dianne Hackborna4972e92012-03-14 10:38:05 -070012069 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 }
12071
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012072 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073 // Refuse possible leaked file descriptors
12074 if (intent != null && intent.hasFileDescriptors() == true) {
12075 throw new IllegalArgumentException("File descriptors passed in Intent");
12076 }
12077
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012078 int flags = intent.getFlags();
12079
12080 if (!mProcessesReady) {
12081 // if the caller really truly claims to know what they're doing, go
12082 // ahead and allow the broadcast without launching any receivers
12083 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12084 intent = new Intent(intent);
12085 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12086 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12087 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12088 + " before boot completion");
12089 throw new IllegalStateException("Cannot broadcast before boot completed");
12090 }
12091 }
12092
12093 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12094 throw new IllegalArgumentException(
12095 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12096 }
12097
12098 return intent;
12099 }
12100
12101 public final int broadcastIntent(IApplicationThread caller,
12102 Intent intent, String resolvedType, IIntentReceiver resultTo,
12103 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012104 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012105 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012107 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012109 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12110 final int callingPid = Binder.getCallingPid();
12111 final int callingUid = Binder.getCallingUid();
12112 final long origId = Binder.clearCallingIdentity();
12113 int res = broadcastIntentLocked(callerApp,
12114 callerApp != null ? callerApp.info.packageName : null,
12115 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012116 resultCode, resultData, map, requiredPermission, serialized, sticky,
12117 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012118 Binder.restoreCallingIdentity(origId);
12119 return res;
12120 }
12121 }
12122
12123 int broadcastIntentInPackage(String packageName, int uid,
12124 Intent intent, String resolvedType, IIntentReceiver resultTo,
12125 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012126 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012128 intent = verifyBroadcastLocked(intent);
12129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012130 final long origId = Binder.clearCallingIdentity();
12131 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12132 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012133 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012134 Binder.restoreCallingIdentity(origId);
12135 return res;
12136 }
12137 }
12138
Amith Yamasani742a6712011-05-04 14:49:28 -070012139 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012140 // Refuse possible leaked file descriptors
12141 if (intent != null && intent.hasFileDescriptors() == true) {
12142 throw new IllegalArgumentException("File descriptors passed in Intent");
12143 }
12144
Dianne Hackborn139748f2012-09-24 11:36:57 -070012145 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012146 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012148 synchronized(this) {
12149 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12150 != PackageManager.PERMISSION_GRANTED) {
12151 String msg = "Permission Denial: unbroadcastIntent() from pid="
12152 + Binder.getCallingPid()
12153 + ", uid=" + Binder.getCallingUid()
12154 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012155 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012156 throw new SecurityException(msg);
12157 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012158 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12159 if (stickies != null) {
12160 ArrayList<Intent> list = stickies.get(intent.getAction());
12161 if (list != null) {
12162 int N = list.size();
12163 int i;
12164 for (i=0; i<N; i++) {
12165 if (intent.filterEquals(list.get(i))) {
12166 list.remove(i);
12167 break;
12168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012170 if (list.size() <= 0) {
12171 stickies.remove(intent.getAction());
12172 }
12173 }
12174 if (stickies.size() <= 0) {
12175 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012176 }
12177 }
12178 }
12179 }
12180
12181 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12182 String resultData, Bundle resultExtras, boolean resultAbort,
12183 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012184 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12185 if (r == null) {
12186 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012187 return false;
12188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012189
Christopher Tatef46723b2012-01-26 14:19:24 -080012190 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12191 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012192 }
12193
12194 public void finishReceiver(IBinder who, int resultCode, String resultData,
12195 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012196 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197
12198 // Refuse possible leaked file descriptors
12199 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12200 throw new IllegalArgumentException("File descriptors passed in Bundle");
12201 }
12202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012203 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012204 try {
12205 boolean doNext = false;
12206 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012207
Christopher Tatef46723b2012-01-26 14:19:24 -080012208 synchronized(this) {
12209 r = broadcastRecordForReceiverLocked(who);
12210 if (r != null) {
12211 doNext = r.queue.finishReceiverLocked(r, resultCode,
12212 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012214 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012215
Christopher Tatef46723b2012-01-26 14:19:24 -080012216 if (doNext) {
12217 r.queue.processNextBroadcast(false);
12218 }
12219 trimApplications();
12220 } finally {
12221 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225 // =========================================================
12226 // INSTRUMENTATION
12227 // =========================================================
12228
12229 public boolean startInstrumentation(ComponentName className,
12230 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012231 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012232 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012234 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 // Refuse possible leaked file descriptors
12236 if (arguments != null && arguments.hasFileDescriptors()) {
12237 throw new IllegalArgumentException("File descriptors passed in Bundle");
12238 }
12239
12240 synchronized(this) {
12241 InstrumentationInfo ii = null;
12242 ApplicationInfo ai = null;
12243 try {
12244 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012245 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012246 ai = AppGlobals.getPackageManager().getApplicationInfo(
12247 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012249 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012250 }
12251 if (ii == null) {
12252 reportStartInstrumentationFailure(watcher, className,
12253 "Unable to find instrumentation info for: " + className);
12254 return false;
12255 }
12256 if (ai == null) {
12257 reportStartInstrumentationFailure(watcher, className,
12258 "Unable to find instrumentation target package: " + ii.targetPackage);
12259 return false;
12260 }
12261
12262 int match = mContext.getPackageManager().checkSignatures(
12263 ii.targetPackage, ii.packageName);
12264 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12265 String msg = "Permission Denial: starting instrumentation "
12266 + className + " from pid="
12267 + Binder.getCallingPid()
12268 + ", uid=" + Binder.getCallingPid()
12269 + " not allowed because package " + ii.packageName
12270 + " does not have a signature matching the target "
12271 + ii.targetPackage;
12272 reportStartInstrumentationFailure(watcher, className, msg);
12273 throw new SecurityException(msg);
12274 }
12275
12276 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012277 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012278 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012279 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012280 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012281 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012282 app.instrumentationProfileFile = profileFile;
12283 app.instrumentationArguments = arguments;
12284 app.instrumentationWatcher = watcher;
12285 app.instrumentationResultClass = className;
12286 Binder.restoreCallingIdentity(origId);
12287 }
12288
12289 return true;
12290 }
12291
12292 /**
12293 * Report errors that occur while attempting to start Instrumentation. Always writes the
12294 * error to the logs, but if somebody is watching, send the report there too. This enables
12295 * the "am" command to report errors with more information.
12296 *
12297 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12298 * @param cn The component name of the instrumentation.
12299 * @param report The error report.
12300 */
12301 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12302 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012303 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012304 try {
12305 if (watcher != null) {
12306 Bundle results = new Bundle();
12307 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12308 results.putString("Error", report);
12309 watcher.instrumentationStatus(cn, -1, results);
12310 }
12311 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012312 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012313 }
12314 }
12315
12316 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12317 if (app.instrumentationWatcher != null) {
12318 try {
12319 // NOTE: IInstrumentationWatcher *must* be oneway here
12320 app.instrumentationWatcher.instrumentationFinished(
12321 app.instrumentationClass,
12322 resultCode,
12323 results);
12324 } catch (RemoteException e) {
12325 }
12326 }
12327 app.instrumentationWatcher = null;
12328 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012329 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 app.instrumentationProfileFile = null;
12331 app.instrumentationArguments = null;
12332
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012333 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012334 }
12335
12336 public void finishInstrumentation(IApplicationThread target,
12337 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012338 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012339 // Refuse possible leaked file descriptors
12340 if (results != null && results.hasFileDescriptors()) {
12341 throw new IllegalArgumentException("File descriptors passed in Intent");
12342 }
12343
12344 synchronized(this) {
12345 ProcessRecord app = getRecordForAppLocked(target);
12346 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012347 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012348 return;
12349 }
12350 final long origId = Binder.clearCallingIdentity();
12351 finishInstrumentationLocked(app, resultCode, results);
12352 Binder.restoreCallingIdentity(origId);
12353 }
12354 }
12355
12356 // =========================================================
12357 // CONFIGURATION
12358 // =========================================================
12359
12360 public ConfigurationInfo getDeviceConfigurationInfo() {
12361 ConfigurationInfo config = new ConfigurationInfo();
12362 synchronized (this) {
12363 config.reqTouchScreen = mConfiguration.touchscreen;
12364 config.reqKeyboardType = mConfiguration.keyboard;
12365 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012366 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12367 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012368 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12369 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012370 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12371 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012372 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12373 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012374 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012375 }
12376 return config;
12377 }
12378
12379 public Configuration getConfiguration() {
12380 Configuration ci;
12381 synchronized(this) {
12382 ci = new Configuration(mConfiguration);
12383 }
12384 return ci;
12385 }
12386
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012387 public void updatePersistentConfiguration(Configuration values) {
12388 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12389 "updateConfiguration()");
12390 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12391 "updateConfiguration()");
12392 if (values == null) {
12393 throw new NullPointerException("Configuration must not be null");
12394 }
12395
12396 synchronized(this) {
12397 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012398 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012399 Binder.restoreCallingIdentity(origId);
12400 }
12401 }
12402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 public void updateConfiguration(Configuration values) {
12404 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12405 "updateConfiguration()");
12406
12407 synchronized(this) {
12408 if (values == null && mWindowManager != null) {
12409 // sentinel: fetch the current configuration from the window manager
12410 values = mWindowManager.computeNewConfiguration();
12411 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012412
12413 if (mWindowManager != null) {
12414 mProcessList.applyDisplaySize(mWindowManager);
12415 }
12416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012417 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012418 if (values != null) {
12419 Settings.System.clearConfiguration(values);
12420 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012421 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 Binder.restoreCallingIdentity(origId);
12423 }
12424 }
12425
12426 /**
12427 * Do either or both things: (1) change the current configuration, and (2)
12428 * make sure the given activity is running with the (now) current
12429 * configuration. Returns true if the activity has been left running, or
12430 * false if <var>starting</var> is being destroyed to match the new
12431 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012432 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012433 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012434 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012435 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012436 // do nothing if we are headless
12437 if (mHeadless) return true;
12438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 int changes = 0;
12440
12441 boolean kept = true;
12442
12443 if (values != null) {
12444 Configuration newConfig = new Configuration(mConfiguration);
12445 changes = newConfig.updateFrom(values);
12446 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012447 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012448 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012449 }
12450
Doug Zongker2bec3d42009-12-04 12:52:44 -080012451 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452
Dianne Hackborn813075a62011-11-14 17:45:19 -080012453 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012454 saveLocaleLocked(values.locale,
12455 !values.locale.equals(mConfiguration.locale),
12456 values.userSetLocale);
12457 }
12458
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012459 mConfigurationSeq++;
12460 if (mConfigurationSeq <= 0) {
12461 mConfigurationSeq = 1;
12462 }
12463 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012464 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012465 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012466
12467 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012468
12469 // TODO: If our config changes, should we auto dismiss any currently
12470 // showing dialogs?
12471 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012472
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012473 AttributeCache ac = AttributeCache.instance();
12474 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012475 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012478 // Make sure all resources in our process are updated
12479 // right now, so that anyone who is going to retrieve
12480 // resource values after we return will be sure to get
12481 // the new ones. This is especially important during
12482 // boot, where the first config change needs to guarantee
12483 // all resources have that config before following boot
12484 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012485 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012486
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012487 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012488 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012489 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012490 mHandler.sendMessage(msg);
12491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012493 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12494 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012495 try {
12496 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012497 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012498 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012499 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 }
12501 } catch (Exception e) {
12502 }
12503 }
12504 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012505 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012506 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12507 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012509 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012510 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012511 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12512 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12513 broadcastIntentLocked(null, null, intent,
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012514 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012515 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012517 }
12518 }
12519
12520 if (changes != 0 && starting == null) {
12521 // If the configuration changed, and the caller is not already
12522 // in the process of starting an activity, then find the top
12523 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012524 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012525 }
12526
12527 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012528 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012529 // And we need to make sure at this point that all other activities
12530 // are made visible with the correct configuration.
12531 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012532 }
12533
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012534 if (values != null && mWindowManager != null) {
12535 mWindowManager.setNewConfiguration(mConfiguration);
12536 }
12537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012538 return kept;
12539 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012540
12541 /**
12542 * Decide based on the configuration whether we should shouw the ANR,
12543 * crash, etc dialogs. The idea is that if there is no affordnace to
12544 * press the on-screen buttons, we shouldn't show the dialog.
12545 *
12546 * A thought: SystemUI might also want to get told about this, the Power
12547 * dialog / global actions also might want different behaviors.
12548 */
12549 private static final boolean shouldShowDialogs(Configuration config) {
12550 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12551 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012553
12554 /**
12555 * Save the locale. You must be inside a synchronized (this) block.
12556 */
12557 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12558 if(isDiff) {
12559 SystemProperties.set("user.language", l.getLanguage());
12560 SystemProperties.set("user.region", l.getCountry());
12561 }
12562
12563 if(isPersist) {
12564 SystemProperties.set("persist.sys.language", l.getLanguage());
12565 SystemProperties.set("persist.sys.country", l.getCountry());
12566 SystemProperties.set("persist.sys.localevar", l.getVariant());
12567 }
12568 }
12569
Adam Powelldd8fab22012-03-22 17:47:27 -070012570 @Override
12571 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12572 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012573 return srec != null && srec.task.affinity != null &&
12574 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012575 }
12576
12577 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12578 Intent resultData) {
12579 ComponentName dest = destIntent.getComponent();
12580
12581 synchronized (this) {
12582 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012583 if (srec == null) {
12584 return false;
12585 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012586 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12587 final int start = history.indexOf(srec);
12588 if (start < 0) {
12589 // Current activity is not in history stack; do nothing.
12590 return false;
12591 }
12592 int finishTo = start - 1;
12593 ActivityRecord parent = null;
12594 boolean foundParentInTask = false;
12595 if (dest != null) {
12596 TaskRecord tr = srec.task;
12597 for (int i = start - 1; i >= 0; i--) {
12598 ActivityRecord r = history.get(i);
12599 if (tr != r.task) {
12600 // Couldn't find parent in the same task; stop at the one above this.
12601 // (Root of current task; in-app "home" behavior)
12602 // Always at least finish the current activity.
12603 finishTo = Math.min(start - 1, i + 1);
12604 parent = history.get(finishTo);
12605 break;
12606 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12607 r.info.name.equals(dest.getClassName())) {
12608 finishTo = i;
12609 parent = r;
12610 foundParentInTask = true;
12611 break;
12612 }
12613 }
12614 }
12615
12616 if (mController != null) {
12617 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12618 if (next != null) {
12619 // ask watcher if this is allowed
12620 boolean resumeOK = true;
12621 try {
12622 resumeOK = mController.activityResuming(next.packageName);
12623 } catch (RemoteException e) {
12624 mController = null;
12625 }
12626
12627 if (!resumeOK) {
12628 return false;
12629 }
12630 }
12631 }
12632 final long origId = Binder.clearCallingIdentity();
12633 for (int i = start; i > finishTo; i--) {
12634 ActivityRecord r = history.get(i);
12635 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012636 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012637 // Only return the supplied result for the first activity finished
12638 resultCode = Activity.RESULT_CANCELED;
12639 resultData = null;
12640 }
12641
12642 if (parent != null && foundParentInTask) {
12643 final int parentLaunchMode = parent.info.launchMode;
12644 final int destIntentFlags = destIntent.getFlags();
12645 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12646 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12647 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12648 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012649 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012650 } else {
12651 try {
12652 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012653 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012654 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12655 null, aInfo, parent.appToken, null,
12656 0, -1, parent.launchedFromUid, 0, null, true, null);
12657 foundParentInTask = res == ActivityManager.START_SUCCESS;
12658 } catch (RemoteException e) {
12659 foundParentInTask = false;
12660 }
12661 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012662 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012663 }
12664 }
12665 Binder.restoreCallingIdentity(origId);
12666 return foundParentInTask;
12667 }
12668 }
12669
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012670 public int getLaunchedFromUid(IBinder activityToken) {
12671 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12672 if (srec == null) {
12673 return -1;
12674 }
12675 return srec.launchedFromUid;
12676 }
12677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012678 // =========================================================
12679 // LIFETIME MANAGEMENT
12680 // =========================================================
12681
Christopher Tatef46723b2012-01-26 14:19:24 -080012682 // Returns which broadcast queue the app is the current [or imminent] receiver
12683 // on, or 'null' if the app is not an active broadcast recipient.
12684 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12685 BroadcastRecord r = app.curReceiver;
12686 if (r != null) {
12687 return r.queue;
12688 }
12689
12690 // It's not the current receiver, but it might be starting up to become one
12691 synchronized (this) {
12692 for (BroadcastQueue queue : mBroadcastQueues) {
12693 r = queue.mPendingBroadcast;
12694 if (r != null && r.curApp == app) {
12695 // found it; report which queue it's in
12696 return queue;
12697 }
12698 }
12699 }
12700
12701 return null;
12702 }
12703
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012704 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012705 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012706 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012707 // This adjustment has already been computed. If we are calling
12708 // from the top, we may have already computed our adjustment with
12709 // an earlier hidden adjustment that isn't really for us... if
12710 // so, use the new hidden adjustment.
12711 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012712 if (app.hasActivities) {
12713 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12714 } else if (app.hasClientActivities) {
12715 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12716 } else {
12717 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12718 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012719 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012720 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 }
12722
12723 if (app.thread == null) {
12724 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012725 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012726 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012727 }
12728
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012729 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12730 app.adjSource = null;
12731 app.adjTarget = null;
12732 app.empty = false;
12733 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012734 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012735
12736 final int activitiesSize = app.activities.size();
12737
Dianne Hackborn7d608422011-08-07 16:24:18 -070012738 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012739 // The max adjustment doesn't allow this app to be anything
12740 // below foreground, so it is not worth doing work for it.
12741 app.adjType = "fixed";
12742 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012743 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012744 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012745 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012746 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012747 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012748 // System process can do UI, and when they do we want to have
12749 // them trim their memory after the user leaves the UI. To
12750 // facilitate this, here we need to determine whether or not it
12751 // is currently showing UI.
12752 app.systemNoUi = true;
12753 if (app == TOP_APP) {
12754 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012755 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012756 } else if (activitiesSize > 0) {
12757 for (int j = 0; j < activitiesSize; j++) {
12758 final ActivityRecord r = app.activities.get(j);
12759 if (r.visible) {
12760 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012761 }
12762 if (r.app == app) {
12763 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012764 }
12765 }
12766 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012767 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012768 }
12769
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012770 app.keeping = false;
12771 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012772 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773
The Android Open Source Project4df24232009-03-05 14:34:35 -080012774 // Determine the importance of the process, starting with most
12775 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012776 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012777 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012778 boolean foregroundActivities = false;
12779 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012780 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012781 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012782 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012783 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012784 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012785 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012786 foregroundActivities = true;
12787 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012788 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012789 } else if (app.instrumentationClass != null) {
12790 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012791 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012792 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012793 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012794 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012795 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012797 // counts as being in the foreground for OOM killer purposes.
12798 // It's placed in a sched group based on the nature of the
12799 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012800 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012801 schedGroup = (queue == mFgBroadcastQueue)
12802 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012803 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012804 } else if (app.executingServices.size() > 0) {
12805 // An app that is currently executing a service callback also
12806 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012807 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012808 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012809 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012810 } else {
12811 // Assume process is hidden (has activities); we will correct
12812 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012813 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012814 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012815 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012816 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012818
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012819 boolean hasStoppingActivities = false;
12820
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012821 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012822 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012823 for (int j = 0; j < activitiesSize; j++) {
12824 final ActivityRecord r = app.activities.get(j);
12825 if (r.visible) {
12826 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012827 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12828 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012829 app.adjType = "visible";
12830 }
12831 schedGroup = Process.THREAD_GROUP_DEFAULT;
12832 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012833 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012834 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012835 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012836 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012837 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12838 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012839 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012840 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012841 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012842 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012843 } else if (r.state == ActivityState.STOPPING) {
12844 // We will apply the actual adjustment later, because
12845 // we want to allow this process to immediately go through
12846 // any memory trimming that is in effect.
12847 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012848 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012849 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012850 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012851 if (r.app == app) {
12852 app.hasActivities = true;
12853 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012854 }
12855 }
12856
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012857 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012858 if (app.hasClientActivities) {
12859 adj = clientHiddenAdj;
12860 app.adjType = "bg-client-act";
12861 } else {
12862 // Whoops, this process is completely empty as far as we know
12863 // at this point.
12864 adj = emptyAdj;
12865 app.empty = true;
12866 app.adjType = "bg-empty";
12867 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012868 }
12869
Dianne Hackborn7d608422011-08-07 16:24:18 -070012870 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012871 if (app.foregroundServices) {
12872 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012873 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012874 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012875 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012876 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012877 } else if (app.forcingToForeground != null) {
12878 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012879 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012880 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012881 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012882 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012883 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012884 }
12885 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012886
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012887 if (app.foregroundServices) {
12888 interesting = true;
12889 }
12890
Dianne Hackborn7d608422011-08-07 16:24:18 -070012891 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012892 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012893 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012894 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012895 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012896 app.adjType = "heavy";
12897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012898
Dianne Hackborn7d608422011-08-07 16:24:18 -070012899 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012900 // This process is hosting what we currently consider to be the
12901 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012902 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012903 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012904 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012905 app.adjType = "home";
12906 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012907
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012908 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12909 && app.activities.size() > 0) {
12910 // This was the previous process that showed UI to the user.
12911 // We want to try to keep it around more aggressively, to give
12912 // a good experience around switching between two apps.
12913 adj = ProcessList.PREVIOUS_APP_ADJ;
12914 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12915 app.hidden = false;
12916 app.adjType = "previous";
12917 }
12918
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012919 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12920 + " reason=" + app.adjType);
12921
The Android Open Source Project4df24232009-03-05 14:34:35 -080012922 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012923 // there are applications dependent on our services or providers, but
12924 // this gives us a baseline and makes sure we don't get into an
12925 // infinite recursion.
12926 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012927 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928
Christopher Tate6fa95972009-06-05 18:43:55 -070012929 if (mBackupTarget != null && app == mBackupTarget.app) {
12930 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012931 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012932 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012933 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012934 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012935 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012936 }
12937 }
12938
Dianne Hackborn7d608422011-08-07 16:24:18 -070012939 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012940 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012941 final long now = SystemClock.uptimeMillis();
12942 // This process is more important if the top activity is
12943 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012944 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012945 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012946 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012948 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012949 // If this process has shown some UI, let it immediately
12950 // go to the LRU list because it may be pretty heavy with
12951 // UI stuff. We'll tag it with a label just to help
12952 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012953 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012954 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012955 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012956 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012957 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012958 // This service has seen some activity within
12959 // recent memory, so we will keep its process ahead
12960 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012961 if (adj > ProcessList.SERVICE_ADJ) {
12962 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012963 app.adjType = "started-services";
12964 app.hidden = false;
12965 }
12966 }
12967 // If we have let the service slide into the background
12968 // state, still have some text describing what it is doing
12969 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012970 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012971 app.adjType = "started-bg-services";
12972 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012973 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012974 // Don't kill this process because it is doing work; it
12975 // has said it is doing work.
12976 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012978 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012979 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012980 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012981 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012982 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012983 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012984 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012985 // XXX should compute this based on the max of
12986 // all connected clients.
12987 ConnectionRecord cr = clist.get(i);
12988 if (cr.binding.client == app) {
12989 // Binding to ourself is not interesting.
12990 continue;
12991 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012992 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012993 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012994 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012995 int myHiddenAdj = hiddenAdj;
12996 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012997 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012998 myHiddenAdj = client.hiddenAdj;
12999 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013000 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013001 }
13002 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013003 int myClientHiddenAdj = clientHiddenAdj;
13004 if (myClientHiddenAdj > client.clientHiddenAdj) {
13005 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
13006 myClientHiddenAdj = client.clientHiddenAdj;
13007 } else {
13008 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
13009 }
13010 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013011 int myEmptyAdj = emptyAdj;
13012 if (myEmptyAdj > client.emptyAdj) {
13013 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
13014 myEmptyAdj = client.emptyAdj;
13015 } else {
13016 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
13017 }
13018 }
13019 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013020 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013021 String adjType = null;
13022 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13023 // Not doing bind OOM management, so treat
13024 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013025 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013026 // If this process has shown some UI, let it immediately
13027 // go to the LRU list because it may be pretty heavy with
13028 // UI stuff. We'll tag it with a label just to help
13029 // debug and understand what is going on.
13030 if (adj > clientAdj) {
13031 adjType = "bound-bg-ui-services";
13032 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013033 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013034 clientAdj = adj;
13035 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013036 if (now >= (s.lastActivity
13037 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013038 // This service has not seen activity within
13039 // recent memory, so allow it to drop to the
13040 // LRU list if there is no other reason to keep
13041 // it around. We'll also tag it with a label just
13042 // to help debug and undertand what is going on.
13043 if (adj > clientAdj) {
13044 adjType = "bound-bg-services";
13045 }
13046 clientAdj = adj;
13047 }
13048 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013049 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
13050 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
13051 // If this connection is keeping the service
13052 // created, then we want to try to better follow
13053 // its memory management semantics for activities.
13054 // That is, if it is sitting in the background
13055 // LRU list as a hidden process (with activities),
13056 // we don't want the service it is connected to
13057 // to go into the empty LRU and quickly get killed,
13058 // because I'll we'll do is just end up restarting
13059 // the service.
13060 app.hasClientActivities |= client.hasActivities;
13061 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013062 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013063 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013064 // If this process has recently shown UI, and
13065 // the process that is binding to it is less
13066 // important than being visible, then we don't
13067 // care about the binding as much as we care
13068 // about letting this process get into the LRU
13069 // list to be killed and restarted if needed for
13070 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013071 if (app.hasShownUi && app != mHomeProcess
13072 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013073 adjType = "bound-bg-ui-services";
13074 } else {
13075 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13076 |Context.BIND_IMPORTANT)) != 0) {
13077 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013078 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13079 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13080 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13081 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13082 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013083 adj = clientAdj;
13084 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013085 app.pendingUiClean = true;
13086 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13087 adj = ProcessList.VISIBLE_APP_ADJ;
13088 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013089 }
13090 if (!client.hidden) {
13091 app.hidden = false;
13092 }
13093 if (client.keeping) {
13094 app.keeping = true;
13095 }
13096 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013097 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013098 }
13099 if (adjType != null) {
13100 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013101 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13102 .REASON_SERVICE_IN_USE;
13103 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013104 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013105 app.adjTarget = s.name;
13106 }
13107 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13108 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13109 schedGroup = Process.THREAD_GROUP_DEFAULT;
13110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013111 }
13112 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013113 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013114 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013115 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013116 (a.visible || a.state == ActivityState.RESUMED
13117 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013118 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013119 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13120 schedGroup = Process.THREAD_GROUP_DEFAULT;
13121 }
13122 app.hidden = false;
13123 app.adjType = "service";
13124 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13125 .REASON_SERVICE_IN_USE;
13126 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013127 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013128 app.adjTarget = s.name;
13129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013131 }
13132 }
13133 }
13134 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013135
Dianne Hackborn287952c2010-09-22 22:34:31 -070013136 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013137 // would like to avoid killing it unless it would prevent the current
13138 // application from running. By default we put the process in
13139 // with the rest of the background processes; as we scan through
13140 // its services we may bump it up from there.
13141 if (adj > hiddenAdj) {
13142 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013143 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013144 app.adjType = "bg-services";
13145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013146 }
13147
Dianne Hackborn7d608422011-08-07 16:24:18 -070013148 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013149 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013150 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013151 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013152 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013153 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013154 for (int i = cpr.connections.size()-1;
13155 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13156 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13157 i--) {
13158 ContentProviderConnection conn = cpr.connections.get(i);
13159 ProcessRecord client = conn.client;
13160 if (client == app) {
13161 // Being our own client is not interesting.
13162 continue;
13163 }
13164 int myHiddenAdj = hiddenAdj;
13165 if (myHiddenAdj > client.hiddenAdj) {
13166 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13167 myHiddenAdj = client.hiddenAdj;
13168 } else {
13169 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013170 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013171 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013172 int myClientHiddenAdj = clientHiddenAdj;
13173 if (myClientHiddenAdj > client.clientHiddenAdj) {
13174 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13175 myClientHiddenAdj = client.clientHiddenAdj;
13176 } else {
13177 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13178 }
13179 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013180 int myEmptyAdj = emptyAdj;
13181 if (myEmptyAdj > client.emptyAdj) {
13182 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13183 myEmptyAdj = client.emptyAdj;
13184 } else {
13185 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13186 }
13187 }
13188 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013189 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013190 if (adj > clientAdj) {
13191 if (app.hasShownUi && app != mHomeProcess
13192 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13193 app.adjType = "bg-ui-provider";
13194 } else {
13195 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13196 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13197 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013199 if (!client.hidden) {
13200 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013201 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013202 if (client.keeping) {
13203 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013204 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013205 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13206 .REASON_PROVIDER_IN_USE;
13207 app.adjSource = client;
13208 app.adjSourceOom = clientAdj;
13209 app.adjTarget = cpr.name;
13210 }
13211 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13212 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 }
13214 }
13215 // If the provider has external (non-framework) process
13216 // dependencies, ensure that its adjustment is at least
13217 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013218 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013219 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13220 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013221 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013222 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013223 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013224 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013225 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013226 }
13227 }
13228 }
13229 }
13230
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013231 if (adj == ProcessList.SERVICE_ADJ) {
13232 if (doingAll) {
13233 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13234 mNewNumServiceProcs++;
13235 }
13236 if (app.serviceb) {
13237 adj = ProcessList.SERVICE_B_ADJ;
13238 }
13239 } else {
13240 app.serviceb = false;
13241 }
13242
13243 app.nonStoppingAdj = adj;
13244
13245 if (hasStoppingActivities) {
13246 // Only upgrade adjustment.
13247 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13248 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13249 app.adjType = "stopping";
13250 }
13251 }
13252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 app.curRawAdj = adj;
13254
Joe Onorato8a9b2202010-02-26 18:56:32 -080013255 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13257 if (adj > app.maxAdj) {
13258 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013259 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013260 schedGroup = Process.THREAD_GROUP_DEFAULT;
13261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013263 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013264 app.keeping = true;
13265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013266
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013267 if (app.hasAboveClient) {
13268 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13269 // then we need to drop its adjustment to be lower than the service's
13270 // in order to honor the request. We want to drop it by one adjustment
13271 // level... but there is special meaning applied to various levels so
13272 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013273 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013274 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013275 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13276 adj = ProcessList.VISIBLE_APP_ADJ;
13277 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13278 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13279 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13280 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013281 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013282 adj++;
13283 }
13284 }
13285
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013286 int importance = app.memImportance;
13287 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13288 app.curAdj = adj;
13289 app.curSchedGroup = schedGroup;
13290 if (!interesting) {
13291 // For this reporting, if there is not something explicitly
13292 // interesting in this process then we will push it to the
13293 // background importance.
13294 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13295 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13296 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13297 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13298 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13299 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13300 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13301 } else if (adj >= ProcessList.SERVICE_ADJ) {
13302 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13303 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13304 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13305 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13306 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13307 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13308 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13309 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13310 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13311 } else {
13312 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13313 }
13314 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013315
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013316 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13317 if (foregroundActivities != app.foregroundActivities) {
13318 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13319 }
13320 if (changes != 0) {
13321 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13322 app.memImportance = importance;
13323 app.foregroundActivities = foregroundActivities;
13324 int i = mPendingProcessChanges.size()-1;
13325 ProcessChangeItem item = null;
13326 while (i >= 0) {
13327 item = mPendingProcessChanges.get(i);
13328 if (item.pid == app.pid) {
13329 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13330 break;
13331 }
13332 i--;
13333 }
13334 if (i < 0) {
13335 // No existing item in pending changes; need a new one.
13336 final int NA = mAvailProcessChanges.size();
13337 if (NA > 0) {
13338 item = mAvailProcessChanges.remove(NA-1);
13339 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13340 } else {
13341 item = new ProcessChangeItem();
13342 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13343 }
13344 item.changes = 0;
13345 item.pid = app.pid;
13346 item.uid = app.info.uid;
13347 if (mPendingProcessChanges.size() == 0) {
13348 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13349 "*** Enqueueing dispatch processes changed!");
13350 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13351 }
13352 mPendingProcessChanges.add(item);
13353 }
13354 item.changes |= changes;
13355 item.importance = importance;
13356 item.foregroundActivities = foregroundActivities;
13357 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13358 + Integer.toHexString(System.identityHashCode(item))
13359 + " " + app.toShortString() + ": changes=" + item.changes
13360 + " importance=" + item.importance
13361 + " foreground=" + item.foregroundActivities
13362 + " type=" + app.adjType + " source=" + app.adjSource
13363 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013364 }
13365
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013366 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367 }
13368
13369 /**
13370 * Ask a given process to GC right now.
13371 */
13372 final void performAppGcLocked(ProcessRecord app) {
13373 try {
13374 app.lastRequestedGc = SystemClock.uptimeMillis();
13375 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013376 if (app.reportLowMemory) {
13377 app.reportLowMemory = false;
13378 app.thread.scheduleLowMemory();
13379 } else {
13380 app.thread.processInBackground();
13381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013382 }
13383 } catch (Exception e) {
13384 // whatever.
13385 }
13386 }
13387
13388 /**
13389 * Returns true if things are idle enough to perform GCs.
13390 */
Josh Bartel7f208742010-02-25 11:01:44 -060013391 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013392 boolean processingBroadcasts = false;
13393 for (BroadcastQueue q : mBroadcastQueues) {
13394 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13395 processingBroadcasts = true;
13396 }
13397 }
13398 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013399 && (mSleeping || (mMainStack.mResumedActivity != null &&
13400 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013401 }
13402
13403 /**
13404 * Perform GCs on all processes that are waiting for it, but only
13405 * if things are idle.
13406 */
13407 final void performAppGcsLocked() {
13408 final int N = mProcessesToGc.size();
13409 if (N <= 0) {
13410 return;
13411 }
Josh Bartel7f208742010-02-25 11:01:44 -060013412 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 while (mProcessesToGc.size() > 0) {
13414 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013415 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013416 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13417 <= SystemClock.uptimeMillis()) {
13418 // To avoid spamming the system, we will GC processes one
13419 // at a time, waiting a few seconds between each.
13420 performAppGcLocked(proc);
13421 scheduleAppGcsLocked();
13422 return;
13423 } else {
13424 // It hasn't been long enough since we last GCed this
13425 // process... put it in the list to wait for its time.
13426 addProcessToGcListLocked(proc);
13427 break;
13428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013429 }
13430 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013431
13432 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013433 }
13434 }
13435
13436 /**
13437 * If all looks good, perform GCs on all processes waiting for them.
13438 */
13439 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013440 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013441 performAppGcsLocked();
13442 return;
13443 }
13444 // Still not idle, wait some more.
13445 scheduleAppGcsLocked();
13446 }
13447
13448 /**
13449 * Schedule the execution of all pending app GCs.
13450 */
13451 final void scheduleAppGcsLocked() {
13452 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013453
13454 if (mProcessesToGc.size() > 0) {
13455 // Schedule a GC for the time to the next process.
13456 ProcessRecord proc = mProcessesToGc.get(0);
13457 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13458
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013459 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013460 long now = SystemClock.uptimeMillis();
13461 if (when < (now+GC_TIMEOUT)) {
13462 when = now + GC_TIMEOUT;
13463 }
13464 mHandler.sendMessageAtTime(msg, when);
13465 }
13466 }
13467
13468 /**
13469 * Add a process to the array of processes waiting to be GCed. Keeps the
13470 * list in sorted order by the last GC time. The process can't already be
13471 * on the list.
13472 */
13473 final void addProcessToGcListLocked(ProcessRecord proc) {
13474 boolean added = false;
13475 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13476 if (mProcessesToGc.get(i).lastRequestedGc <
13477 proc.lastRequestedGc) {
13478 added = true;
13479 mProcessesToGc.add(i+1, proc);
13480 break;
13481 }
13482 }
13483 if (!added) {
13484 mProcessesToGc.add(0, proc);
13485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013486 }
13487
13488 /**
13489 * Set up to ask a process to GC itself. This will either do it
13490 * immediately, or put it on the list of processes to gc the next
13491 * time things are idle.
13492 */
13493 final void scheduleAppGcLocked(ProcessRecord app) {
13494 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013495 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496 return;
13497 }
13498 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013499 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013500 scheduleAppGcsLocked();
13501 }
13502 }
13503
Dianne Hackborn287952c2010-09-22 22:34:31 -070013504 final void checkExcessivePowerUsageLocked(boolean doKills) {
13505 updateCpuStatsNow();
13506
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013507 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013508 boolean doWakeKills = doKills;
13509 boolean doCpuKills = doKills;
13510 if (mLastPowerCheckRealtime == 0) {
13511 doWakeKills = false;
13512 }
13513 if (mLastPowerCheckUptime == 0) {
13514 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013515 }
13516 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013517 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013518 }
13519 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013520 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13521 final long curUptime = SystemClock.uptimeMillis();
13522 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13523 mLastPowerCheckRealtime = curRealtime;
13524 mLastPowerCheckUptime = curUptime;
13525 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13526 doWakeKills = false;
13527 }
13528 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13529 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013530 }
13531 int i = mLruProcesses.size();
13532 while (i > 0) {
13533 i--;
13534 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013535 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013536 long wtime;
13537 synchronized (stats) {
13538 wtime = stats.getProcessWakeTime(app.info.uid,
13539 app.pid, curRealtime);
13540 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013541 long wtimeUsed = wtime - app.lastWakeTime;
13542 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13543 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013544 StringBuilder sb = new StringBuilder(128);
13545 sb.append("Wake for ");
13546 app.toShortString(sb);
13547 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013548 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013549 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013550 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013551 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013552 sb.append((wtimeUsed*100)/realtimeSince);
13553 sb.append("%)");
13554 Slog.i(TAG, sb.toString());
13555 sb.setLength(0);
13556 sb.append("CPU for ");
13557 app.toShortString(sb);
13558 sb.append(": over ");
13559 TimeUtils.formatDuration(uptimeSince, sb);
13560 sb.append(" used ");
13561 TimeUtils.formatDuration(cputimeUsed, sb);
13562 sb.append(" (");
13563 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013564 sb.append("%)");
13565 Slog.i(TAG, sb.toString());
13566 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013567 // If a process has held a wake lock for more
13568 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013569 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013570 if (doWakeKills && realtimeSince > 0
13571 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13572 synchronized (stats) {
13573 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13574 realtimeSince, wtimeUsed);
13575 }
13576 Slog.w(TAG, "Excessive wake lock in " + app.processName
13577 + " (pid " + app.pid + "): held " + wtimeUsed
13578 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013579 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013580 app.processName, app.setAdj, "excessive wake lock");
13581 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013582 } else if (doCpuKills && uptimeSince > 0
13583 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13584 synchronized (stats) {
13585 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13586 uptimeSince, cputimeUsed);
13587 }
13588 Slog.w(TAG, "Excessive CPU in " + app.processName
13589 + " (pid " + app.pid + "): used " + cputimeUsed
13590 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013591 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013592 app.processName, app.setAdj, "excessive cpu");
13593 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013594 } else {
13595 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013596 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013597 }
13598 }
13599 }
13600 }
13601
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013602 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013603 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013605 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013606 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013607
13608 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013609 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013610 }
13611
Dianne Hackborn287952c2010-09-22 22:34:31 -070013612 final boolean wasKeeping = app.keeping;
13613
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013614 boolean success = true;
13615
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013616 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013617
Jeff Brown10e89712011-07-08 18:52:57 -070013618 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013619 if (wasKeeping && !app.keeping) {
13620 // This app is no longer something we want to keep. Note
13621 // its current wake lock time to later know to kill it if
13622 // it is not behaving well.
13623 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13624 synchronized (stats) {
13625 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13626 app.pid, SystemClock.elapsedRealtime());
13627 }
13628 app.lastCpuTime = app.curCpuTime;
13629 }
13630
13631 app.setRawAdj = app.curRawAdj;
13632 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013633
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013634 if (app.curAdj != app.setAdj) {
13635 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013636 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013637 TAG, "Set " + app.pid + " " + app.processName +
13638 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013639 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013640 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013641 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013642 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013643 }
13644 }
13645 if (app.setSchedGroup != app.curSchedGroup) {
13646 app.setSchedGroup = app.curSchedGroup;
13647 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13648 "Setting process group of " + app.processName
13649 + " to " + app.curSchedGroup);
13650 if (app.waitingToKill != null &&
13651 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13652 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013653 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013654 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013655 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013656 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013657 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013658 } else {
13659 if (true) {
13660 long oldId = Binder.clearCallingIdentity();
13661 try {
13662 Process.setProcessGroup(app.pid, app.curSchedGroup);
13663 } catch (Exception e) {
13664 Slog.w(TAG, "Failed setting process group of " + app.pid
13665 + " to " + app.curSchedGroup);
13666 e.printStackTrace();
13667 } finally {
13668 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013669 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013670 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013671 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013672 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013673 app.thread.setSchedulingGroup(app.curSchedGroup);
13674 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013675 }
13676 }
13677 }
13678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013679 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013680 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013681 }
13682
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013683 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013684 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013685 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013686 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013688 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013689 }
13690 }
13691 return resumedActivity;
13692 }
13693
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013694 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013695 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013696 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13697 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013698 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13699 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700
13701 mAdjSeq++;
13702
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013703 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13704 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013705 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13706 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013707 if (nowHidden != wasHidden) {
13708 // Changed to/from hidden state, so apps after it in the LRU
13709 // list may also be changed.
13710 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013711 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013712 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013713 }
13714
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013715 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013716 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013717 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013718 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013719
13720 if (false) {
13721 RuntimeException e = new RuntimeException();
13722 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013723 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013724 }
13725
13726 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013727 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013728
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013729 final int emptyProcessLimit;
13730 final int hiddenProcessLimit;
13731 if (mProcessLimit <= 0) {
13732 emptyProcessLimit = hiddenProcessLimit = 0;
13733 } else if (mProcessLimit == 1) {
13734 emptyProcessLimit = 1;
13735 hiddenProcessLimit = 0;
13736 } else {
13737 emptyProcessLimit = (mProcessLimit*2)/3;
13738 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13739 }
13740
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013741 // Let's determine how many processes we have running vs.
13742 // how many slots we have for background processes; we may want
13743 // to put multiple processes in a slot of there are enough of
13744 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013745 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13746 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013747 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13748 if (numEmptyProcs > hiddenProcessLimit) {
13749 // If there are more empty processes than our limit on hidden
13750 // processes, then use the hidden process limit for the factor.
13751 // This ensures that the really old empty processes get pushed
13752 // down to the bottom, so if we are running low on memory we will
13753 // have a better chance at keeping around more hidden processes
13754 // instead of a gazillion empty processes.
13755 numEmptyProcs = hiddenProcessLimit;
13756 }
13757 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013758 if (emptyFactor < 1) emptyFactor = 1;
13759 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13760 if (hiddenFactor < 1) hiddenFactor = 1;
13761 int stepHidden = 0;
13762 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013763 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013764 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013765 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013766
13767 mNumNonHiddenProcs = 0;
13768 mNumHiddenProcs = 0;
13769
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013770 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013771 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013772 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013773 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013774 int nextHiddenAdj = curHiddenAdj+1;
13775 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13776 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013777 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013778 while (i > 0) {
13779 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013780 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013781 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013782 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013783 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013784 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13785 // This process was assigned as a hidden process... step the
13786 // hidden level.
13787 mNumHiddenProcs++;
13788 if (curHiddenAdj != nextHiddenAdj) {
13789 stepHidden++;
13790 if (stepHidden >= hiddenFactor) {
13791 stepHidden = 0;
13792 curHiddenAdj = nextHiddenAdj;
13793 nextHiddenAdj += 2;
13794 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13795 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13796 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013797 if (curClientHiddenAdj <= curHiddenAdj) {
13798 curClientHiddenAdj = curHiddenAdj + 1;
13799 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13800 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13801 }
13802 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013803 }
13804 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013805 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013806 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013807 Slog.i(TAG, "No longer want " + app.processName
13808 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013809 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013810 app.processName, app.setAdj, "too many background");
13811 app.killedBackground = true;
13812 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013813 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013814 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13815 // This process has a client that has activities. We will have
13816 // given it the current hidden adj; here we will just leave it
13817 // without stepping the hidden adj.
13818 curClientHiddenAdj++;
13819 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13820 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13821 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013822 } else {
13823 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13824 // This process was assigned as an empty process... step the
13825 // empty level.
13826 if (curEmptyAdj != nextEmptyAdj) {
13827 stepEmpty++;
13828 if (stepEmpty >= emptyFactor) {
13829 stepEmpty = 0;
13830 curEmptyAdj = nextEmptyAdj;
13831 nextEmptyAdj += 2;
13832 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13833 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13834 }
13835 }
13836 }
13837 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13838 mNumNonHiddenProcs++;
13839 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013840 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13841 && !app.hasClientActivities) {
13842 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13843 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013844 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013845 + " (pid " + app.pid + "): empty for "
13846 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13847 / 1000) + "s");
13848 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13849 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013850 app.killedBackground = true;
13851 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013852 } else {
13853 numEmpty++;
13854 if (numEmpty > emptyProcessLimit) {
13855 Slog.i(TAG, "No longer want " + app.processName
13856 + " (pid " + app.pid + "): empty #" + numEmpty);
13857 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13858 app.processName, app.setAdj, "too many background");
13859 app.killedBackground = true;
13860 Process.killProcessQuiet(app.pid);
13861 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013862 }
13863 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013864 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013865 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013866 // If this is an isolated process, and there are no
13867 // services running in it, then the process is no longer
13868 // needed. We agressively kill these because we can by
13869 // definition not re-use the same process again, and it is
13870 // good to avoid having whatever code was running in them
13871 // left sitting around after no longer needed.
13872 Slog.i(TAG, "Isolated process " + app.processName
13873 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013874 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013875 app.processName, app.setAdj, "isolated not needed");
13876 app.killedBackground = true;
13877 Process.killProcessQuiet(app.pid);
13878 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013879 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13880 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13881 && !app.killedBackground) {
13882 numTrimming++;
13883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013884 }
13885 }
13886
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013887 mNumServiceProcs = mNewNumServiceProcs;
13888
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013889 // Now determine the memory trimming level of background processes.
13890 // Unfortunately we need to start at the back of the list to do this
13891 // properly. We only do this if the number of background apps we
13892 // are managing to keep around is less than half the maximum we desire;
13893 // if we are keeping a good number around, we'll let them use whatever
13894 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013895 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13896 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013897 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013898 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013899 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013900 int minFactor = 2;
13901 if (mHomeProcess != null) minFactor++;
13902 if (mPreviousProcess != null) minFactor++;
13903 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013904 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013905 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013906 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013907 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013908 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013909 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13910 } else {
13911 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13912 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013913 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013914 for (i=0; i<N; i++) {
13915 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013916 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13917 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013918 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013919 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13920 try {
13921 app.thread.scheduleTrimMemory(curLevel);
13922 } catch (RemoteException e) {
13923 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013924 if (false) {
13925 // For now we won't do this; our memory trimming seems
13926 // to be good enough at this point that destroying
13927 // activities causes more harm than good.
13928 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13929 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013930 // Need to do this on its own message because the stack may not
13931 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013932 // For these apps we will also finish their activities
13933 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013934 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013935 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013936 }
13937 }
13938 app.trimMemoryLevel = curLevel;
13939 step++;
13940 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013941 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013942 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013943 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13944 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013945 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013946 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13947 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013948 break;
13949 }
13950 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013951 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013952 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013953 && app.thread != null) {
13954 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013955 app.thread.scheduleTrimMemory(
13956 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013957 } catch (RemoteException e) {
13958 }
13959 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013960 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013961 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013962 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013963 && app.pendingUiClean) {
13964 // If this application is now in the background and it
13965 // had done UI, then give it the special trim level to
13966 // have it free UI resources.
13967 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13968 if (app.trimMemoryLevel < level && app.thread != null) {
13969 try {
13970 app.thread.scheduleTrimMemory(level);
13971 } catch (RemoteException e) {
13972 }
13973 }
13974 app.pendingUiClean = false;
13975 }
13976 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013977 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013978 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013979 } catch (RemoteException e) {
13980 }
13981 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013982 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013983 }
13984 }
13985 } else {
13986 final int N = mLruProcesses.size();
13987 for (i=0; i<N; i++) {
13988 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013989 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013990 && app.pendingUiClean) {
13991 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13992 && app.thread != null) {
13993 try {
13994 app.thread.scheduleTrimMemory(
13995 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13996 } catch (RemoteException e) {
13997 }
13998 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013999 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014000 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014001 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014002 }
14003 }
14004
14005 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014006 // Need to do this on its own message because the stack may not
14007 // be in a consistent state at this point.
14008 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014010 }
14011
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014012 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014013 synchronized (this) {
14014 int i;
14015
14016 // First remove any unused application processes whose package
14017 // has been removed.
14018 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14019 final ProcessRecord app = mRemovedProcesses.get(i);
14020 if (app.activities.size() == 0
14021 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014022 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014023 TAG, "Exiting empty application process "
14024 + app.processName + " ("
14025 + (app.thread != null ? app.thread.asBinder() : null)
14026 + ")\n");
14027 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014028 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014029 app.processName, app.setAdj, "empty");
14030 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014031 } else {
14032 try {
14033 app.thread.scheduleExit();
14034 } catch (Exception e) {
14035 // Ignore exceptions.
14036 }
14037 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014038 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014039 mRemovedProcesses.remove(i);
14040
14041 if (app.persistent) {
14042 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014043 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014044 }
14045 }
14046 }
14047 }
14048
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014049 // Now update the oom adj for all processes.
14050 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014051 }
14052 }
14053
14054 /** This method sends the specified signal to each of the persistent apps */
14055 public void signalPersistentProcesses(int sig) throws RemoteException {
14056 if (sig != Process.SIGNAL_USR1) {
14057 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14058 }
14059
14060 synchronized (this) {
14061 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14062 != PackageManager.PERMISSION_GRANTED) {
14063 throw new SecurityException("Requires permission "
14064 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14065 }
14066
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014067 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14068 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014069 if (r.thread != null && r.persistent) {
14070 Process.sendSignal(r.pid, sig);
14071 }
14072 }
14073 }
14074 }
14075
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014076 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14077 if (proc == null || proc == mProfileProc) {
14078 proc = mProfileProc;
14079 path = mProfileFile;
14080 profileType = mProfileType;
14081 clearProfilerLocked();
14082 }
14083 if (proc == null) {
14084 return;
14085 }
14086 try {
14087 proc.thread.profilerControl(false, path, null, profileType);
14088 } catch (RemoteException e) {
14089 throw new IllegalStateException("Process disappeared");
14090 }
14091 }
14092
14093 private void clearProfilerLocked() {
14094 if (mProfileFd != null) {
14095 try {
14096 mProfileFd.close();
14097 } catch (IOException e) {
14098 }
14099 }
14100 mProfileApp = null;
14101 mProfileProc = null;
14102 mProfileFile = null;
14103 mProfileType = 0;
14104 mAutoStopProfiler = false;
14105 }
14106
Dianne Hackborn1676c852012-09-10 14:52:30 -070014107 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014108 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014109
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014110 try {
14111 synchronized (this) {
14112 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14113 // its own permission.
14114 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14115 != PackageManager.PERMISSION_GRANTED) {
14116 throw new SecurityException("Requires permission "
14117 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014118 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014119
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014120 if (start && fd == null) {
14121 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014122 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014123
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014124 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014125 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014126 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014127 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014128
14129 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014130 throw new IllegalArgumentException("Unknown process: " + process);
14131 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014132
14133 if (start) {
14134 stopProfilerLocked(null, null, 0);
14135 setProfileApp(proc.info, proc.processName, path, fd, false);
14136 mProfileProc = proc;
14137 mProfileType = profileType;
14138 try {
14139 fd = fd.dup();
14140 } catch (IOException e) {
14141 fd = null;
14142 }
14143 proc.thread.profilerControl(start, path, fd, profileType);
14144 fd = null;
14145 mProfileFd = null;
14146 } else {
14147 stopProfilerLocked(proc, path, profileType);
14148 if (fd != null) {
14149 try {
14150 fd.close();
14151 } catch (IOException e) {
14152 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014153 }
14154 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014155
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014156 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014157 }
14158 } catch (RemoteException e) {
14159 throw new IllegalStateException("Process disappeared");
14160 } finally {
14161 if (fd != null) {
14162 try {
14163 fd.close();
14164 } catch (IOException e) {
14165 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014166 }
14167 }
14168 }
Andy McFadden824c5102010-07-09 16:26:57 -070014169
Dianne Hackborn1676c852012-09-10 14:52:30 -070014170 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014171 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014172 userId, true, true, callName, null);
14173 ProcessRecord proc = null;
14174 try {
14175 int pid = Integer.parseInt(process);
14176 synchronized (mPidsSelfLocked) {
14177 proc = mPidsSelfLocked.get(pid);
14178 }
14179 } catch (NumberFormatException e) {
14180 }
14181
14182 if (proc == null) {
14183 HashMap<String, SparseArray<ProcessRecord>> all
14184 = mProcessNames.getMap();
14185 SparseArray<ProcessRecord> procs = all.get(process);
14186 if (procs != null && procs.size() > 0) {
14187 proc = procs.valueAt(0);
14188 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14189 for (int i=1; i<procs.size(); i++) {
14190 ProcessRecord thisProc = procs.valueAt(i);
14191 if (thisProc.userId == userId) {
14192 proc = thisProc;
14193 break;
14194 }
14195 }
14196 }
14197 }
14198 }
14199
14200 return proc;
14201 }
14202
14203 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014204 String path, ParcelFileDescriptor fd) throws RemoteException {
14205
14206 try {
14207 synchronized (this) {
14208 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14209 // its own permission (same as profileControl).
14210 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14211 != PackageManager.PERMISSION_GRANTED) {
14212 throw new SecurityException("Requires permission "
14213 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14214 }
14215
14216 if (fd == null) {
14217 throw new IllegalArgumentException("null fd");
14218 }
14219
Dianne Hackborn1676c852012-09-10 14:52:30 -070014220 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014221 if (proc == null || proc.thread == null) {
14222 throw new IllegalArgumentException("Unknown process: " + process);
14223 }
14224
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014225 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14226 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014227 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14228 throw new SecurityException("Process not debuggable: " + proc);
14229 }
14230 }
14231
14232 proc.thread.dumpHeap(managed, path, fd);
14233 fd = null;
14234 return true;
14235 }
14236 } catch (RemoteException e) {
14237 throw new IllegalStateException("Process disappeared");
14238 } finally {
14239 if (fd != null) {
14240 try {
14241 fd.close();
14242 } catch (IOException e) {
14243 }
14244 }
14245 }
14246 }
14247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014248 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14249 public void monitor() {
14250 synchronized (this) { }
14251 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014252
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014253 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014254 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14255 ProcessRecord processRecord = mLruProcesses.get(i);
14256 try {
14257 if (processRecord.thread != null) {
14258 processRecord.thread.setCoreSettings(settings);
14259 }
14260 } catch (RemoteException re) {
14261 /* ignore */
14262 }
14263 }
14264 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014265
14266 // Multi-user methods
14267
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014268 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014269 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014270 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14271 != PackageManager.PERMISSION_GRANTED) {
14272 String msg = "Permission Denial: switchUser() from pid="
14273 + Binder.getCallingPid()
14274 + ", uid=" + Binder.getCallingUid()
14275 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14276 Slog.w(TAG, msg);
14277 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014278 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014279
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014280 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014281 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014282 synchronized (this) {
14283 final int oldUserId = mCurrentUserId;
14284 if (oldUserId == userId) {
14285 return true;
14286 }
14287
14288 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14289 if (userInfo == null) {
14290 Slog.w(TAG, "No user info for user #" + userId);
14291 return false;
14292 }
14293
14294 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14295 R.anim.screen_user_enter);
14296
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014297 boolean needStart = false;
14298
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014299 // If the user we are switching to is not currently started, then
14300 // we need to start it now.
14301 if (mStartedUsers.get(userId) == null) {
14302 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014303 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014304 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014305 }
14306
14307 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014308 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014309 final Integer userIdInt = Integer.valueOf(userId);
14310 mUserLru.remove(userIdInt);
14311 mUserLru.add(userIdInt);
14312
Craig Mautnerf1b67412012-09-19 13:18:29 -070014313 mWindowManager.setCurrentUser(userId);
14314
Adam Cohenf7522022012-10-03 20:03:18 -070014315 // Once the internal notion of the active user has switched, we lock the device
14316 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014317 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014318
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014319 final UserStartedState uss = mStartedUsers.get(userId);
14320
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014321 // Make sure user is in the started state. If it is currently
14322 // stopping, we need to knock that off.
14323 if (uss.mState == UserStartedState.STATE_STOPPING) {
14324 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14325 // so we can just fairly silently bring the user back from
14326 // the almost-dead.
14327 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014328 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014329 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014330 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14331 // This means ACTION_SHUTDOWN has been sent, so we will
14332 // need to treat this as a new boot of the user.
14333 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014334 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014335 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014336 }
14337
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014338 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14339 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14340 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14341 oldUserId, userId, uss));
14342 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14343 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014344 if (needStart) {
14345 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14346 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14347 | Intent.FLAG_RECEIVER_FOREGROUND);
14348 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14349 broadcastIntentLocked(null, null, intent,
14350 null, null, 0, null, null, null,
14351 false, false, MY_PID, Process.SYSTEM_UID, userId);
14352 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014353
14354 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14355 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014356 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014357 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014358 broadcastIntentLocked(null, null, intent, null,
14359 new IIntentReceiver.Stub() {
14360 public void performReceive(Intent intent, int resultCode,
14361 String data, Bundle extras, boolean ordered,
14362 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014363 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014364 }
14365 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14366 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014367 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014368 } else {
14369 getUserManagerLocked().makeInitialized(userInfo.id);
14370 }
14371 }
14372
14373 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14374 if (!haveActivities) {
14375 startHomeActivityLocked(userId);
14376 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014377
Jeff Sharkey86597df2012-11-09 15:00:31 -080014378 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014379 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014380 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014381 if (needStart) {
14382 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14383 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14384 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14385 broadcastIntentLocked(null, null, intent,
14386 null, new IIntentReceiver.Stub() {
14387 @Override
14388 public void performReceive(Intent intent, int resultCode, String data,
14389 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14390 throws RemoteException {
14391 }
14392 }, 0, null, null,
14393 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014394 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014395 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014396 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014397 } finally {
14398 Binder.restoreCallingIdentity(ident);
14399 }
Amith Yamasani13593602012-03-22 16:16:17 -070014400
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014401 return true;
14402 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014403
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014404 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14405 long ident = Binder.clearCallingIdentity();
14406 try {
14407 Intent intent;
14408 if (oldUserId >= 0) {
14409 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014410 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14411 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014412 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14413 broadcastIntentLocked(null, null, intent,
14414 null, null, 0, null, null, null,
14415 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14416 }
14417 if (newUserId >= 0) {
14418 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014419 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14420 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014421 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14422 broadcastIntentLocked(null, null, intent,
14423 null, null, 0, null, null, null,
14424 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14425 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014426 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14427 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014428 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14429 broadcastIntentLocked(null, null, intent,
14430 null, null, 0, null, null,
14431 android.Manifest.permission.MANAGE_USERS,
14432 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14433 }
14434 } finally {
14435 Binder.restoreCallingIdentity(ident);
14436 }
14437 }
14438
14439 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14440 final int newUserId) {
14441 final int N = mUserSwitchObservers.beginBroadcast();
14442 if (N > 0) {
14443 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14444 int mCount = 0;
14445 @Override
14446 public void sendResult(Bundle data) throws RemoteException {
14447 synchronized (ActivityManagerService.this) {
14448 if (mCurUserSwitchCallback == this) {
14449 mCount++;
14450 if (mCount == N) {
14451 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14452 }
14453 }
14454 }
14455 }
14456 };
14457 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014458 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014459 mCurUserSwitchCallback = callback;
14460 }
14461 for (int i=0; i<N; i++) {
14462 try {
14463 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14464 newUserId, callback);
14465 } catch (RemoteException e) {
14466 }
14467 }
14468 } else {
14469 synchronized (this) {
14470 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14471 }
14472 }
14473 mUserSwitchObservers.finishBroadcast();
14474 }
14475
14476 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14477 synchronized (this) {
14478 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14479 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14480 }
14481 }
14482
14483 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14484 mCurUserSwitchCallback = null;
14485 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14486 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14487 oldUserId, newUserId, uss));
14488 }
14489
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014490 void userInitialized(UserStartedState uss, int newUserId) {
14491 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014492 }
14493
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014494 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014495 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014496 }
14497
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014498 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14499 boolean clearInitializing, boolean clearSwitching) {
14500 boolean unfrozen = false;
14501 synchronized (this) {
14502 if (clearInitializing) {
14503 uss.initializing = false;
14504 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14505 }
14506 if (clearSwitching) {
14507 uss.switching = false;
14508 }
14509 if (!uss.switching && !uss.initializing) {
14510 mWindowManager.stopFreezingScreen();
14511 unfrozen = true;
14512 }
14513 }
14514 if (unfrozen) {
14515 final int N = mUserSwitchObservers.beginBroadcast();
14516 for (int i=0; i<N; i++) {
14517 try {
14518 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14519 } catch (RemoteException e) {
14520 }
14521 }
14522 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014523 }
14524 }
14525
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014526 void finishUserSwitch(UserStartedState uss) {
14527 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014528 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014529 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14530 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014531 final int userId = uss.mHandle.getIdentifier();
14532 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14533 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14534 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014535 null, null, 0, null, null,
14536 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014537 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014538 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014539 int num = mUserLru.size();
14540 int i = 0;
14541 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14542 Integer oldUserId = mUserLru.get(i);
14543 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14544 if (oldUss == null) {
14545 // Shouldn't happen, but be sane if it does.
14546 mUserLru.remove(i);
14547 num--;
14548 continue;
14549 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014550 if (oldUss.mState == UserStartedState.STATE_STOPPING
14551 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014552 // This user is already stopping, doesn't count.
14553 num--;
14554 i++;
14555 continue;
14556 }
14557 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14558 // Owner and current can't be stopped, but count as running.
14559 i++;
14560 continue;
14561 }
14562 // This is a user to be stopped.
14563 stopUserLocked(oldUserId, null);
14564 num--;
14565 i++;
14566 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014567 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014568 }
14569
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014570 @Override
14571 public int stopUser(final int userId, final IStopUserCallback callback) {
14572 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14573 != PackageManager.PERMISSION_GRANTED) {
14574 String msg = "Permission Denial: switchUser() from pid="
14575 + Binder.getCallingPid()
14576 + ", uid=" + Binder.getCallingUid()
14577 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14578 Slog.w(TAG, msg);
14579 throw new SecurityException(msg);
14580 }
14581 if (userId <= 0) {
14582 throw new IllegalArgumentException("Can't stop primary user " + userId);
14583 }
Amith Yamasani13593602012-03-22 16:16:17 -070014584 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014585 return stopUserLocked(userId, callback);
14586 }
14587 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014588
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014589 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14590 if (mCurrentUserId == userId) {
14591 return ActivityManager.USER_OP_IS_CURRENT;
14592 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014593
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014594 final UserStartedState uss = mStartedUsers.get(userId);
14595 if (uss == null) {
14596 // User is not started, nothing to do... but we do need to
14597 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014598 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014599 mHandler.post(new Runnable() {
14600 @Override
14601 public void run() {
14602 try {
14603 callback.userStopped(userId);
14604 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014605 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014606 }
14607 });
14608 }
14609 return ActivityManager.USER_OP_SUCCESS;
14610 }
14611
14612 if (callback != null) {
14613 uss.mStopCallbacks.add(callback);
14614 }
14615
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014616 if (uss.mState != UserStartedState.STATE_STOPPING
14617 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014618 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014619 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014620
14621 long ident = Binder.clearCallingIdentity();
14622 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014623 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014624 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014625 // stop the user.
14626 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14627 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14628 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14629 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14630 // This is the result receiver for the final shutdown broadcast.
14631 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014632 @Override
14633 public void performReceive(Intent intent, int resultCode, String data,
14634 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14635 finishUserStop(uss);
14636 }
14637 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014638 // This is the result receiver for the initial stopping broadcast.
14639 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14640 @Override
14641 public void performReceive(Intent intent, int resultCode, String data,
14642 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14643 // On to the next.
14644 synchronized (ActivityManagerService.this) {
14645 if (uss.mState != UserStartedState.STATE_STOPPING) {
14646 // Whoops, we are being started back up. Abort, abort!
14647 return;
14648 }
14649 uss.mState = UserStartedState.STATE_SHUTDOWN;
14650 }
14651 broadcastIntentLocked(null, null, shutdownIntent,
14652 null, shutdownReceiver, 0, null, null, null,
14653 true, false, MY_PID, Process.SYSTEM_UID, userId);
14654 }
14655 };
14656 // Kick things off.
14657 broadcastIntentLocked(null, null, stoppingIntent,
14658 null, stoppingReceiver, 0, null, null,
14659 android.Manifest.permission.INTERACT_ACROSS_USERS,
14660 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014661 } finally {
14662 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014663 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014664 }
Amith Yamasani13593602012-03-22 16:16:17 -070014665
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014666 return ActivityManager.USER_OP_SUCCESS;
14667 }
14668
14669 void finishUserStop(UserStartedState uss) {
14670 final int userId = uss.mHandle.getIdentifier();
14671 boolean stopped;
14672 ArrayList<IStopUserCallback> callbacks;
14673 synchronized (this) {
14674 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014675 if (mStartedUsers.get(userId) != uss) {
14676 stopped = false;
14677 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014678 stopped = false;
14679 } else {
14680 stopped = true;
14681 // User can no longer run.
14682 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014683 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014684 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014685
14686 // Clean up all state and processes associated with the user.
14687 // Kill all the processes for the user.
14688 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014689 }
14690 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014691
14692 for (int i=0; i<callbacks.size(); i++) {
14693 try {
14694 if (stopped) callbacks.get(i).userStopped(userId);
14695 else callbacks.get(i).userStopAborted(userId);
14696 } catch (RemoteException e) {
14697 }
14698 }
14699 }
14700
14701 @Override
14702 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014703 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14704 != PackageManager.PERMISSION_GRANTED) && (
14705 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14706 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014707 String msg = "Permission Denial: getCurrentUser() from pid="
14708 + Binder.getCallingPid()
14709 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014710 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014711 Slog.w(TAG, msg);
14712 throw new SecurityException(msg);
14713 }
14714 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014715 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014716 }
Amith Yamasani13593602012-03-22 16:16:17 -070014717 }
14718
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014719 int getCurrentUserIdLocked() {
14720 return mCurrentUserId;
14721 }
14722
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014723 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014724 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014725 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14726 != PackageManager.PERMISSION_GRANTED) {
14727 String msg = "Permission Denial: isUserRunning() from pid="
14728 + Binder.getCallingPid()
14729 + ", uid=" + Binder.getCallingUid()
14730 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14731 Slog.w(TAG, msg);
14732 throw new SecurityException(msg);
14733 }
14734 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014735 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014736 }
14737 }
14738
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014739 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014740 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014741 if (state == null) {
14742 return false;
14743 }
14744 if (orStopped) {
14745 return true;
14746 }
14747 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014748 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014749 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014750
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014751 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014752 public int[] getRunningUserIds() {
14753 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14754 != PackageManager.PERMISSION_GRANTED) {
14755 String msg = "Permission Denial: isUserRunning() from pid="
14756 + Binder.getCallingPid()
14757 + ", uid=" + Binder.getCallingUid()
14758 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14759 Slog.w(TAG, msg);
14760 throw new SecurityException(msg);
14761 }
14762 synchronized (this) {
14763 return mStartedUserArray;
14764 }
14765 }
14766
14767 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014768 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014769 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014770 UserStartedState uss = mStartedUsers.valueAt(i);
14771 // This list does not include stopping users.
14772 if (uss.mState != UserStartedState.STATE_STOPPING
14773 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14774 num++;
14775 }
14776 }
14777 mStartedUserArray = new int[num];
14778 num = 0;
14779 for (int i=0; i<mStartedUsers.size(); i++) {
14780 UserStartedState uss = mStartedUsers.valueAt(i);
14781 if (uss.mState != UserStartedState.STATE_STOPPING
14782 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14783 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14784 num++;
14785 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014786 }
14787 }
14788
14789 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014790 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14791 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14792 != PackageManager.PERMISSION_GRANTED) {
14793 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14794 + Binder.getCallingPid()
14795 + ", uid=" + Binder.getCallingUid()
14796 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14797 Slog.w(TAG, msg);
14798 throw new SecurityException(msg);
14799 }
14800
14801 mUserSwitchObservers.register(observer);
14802 }
14803
14804 @Override
14805 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14806 mUserSwitchObservers.unregister(observer);
14807 }
14808
Dianne Hackborn1676c852012-09-10 14:52:30 -070014809 private boolean userExists(int userId) {
14810 if (userId == 0) {
14811 return true;
14812 }
14813 UserManagerService ums = getUserManagerLocked();
14814 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14815 }
14816
14817 int[] getUsersLocked() {
14818 UserManagerService ums = getUserManagerLocked();
14819 return ums != null ? ums.getUserIds() : new int[] { 0 };
14820 }
14821
14822 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014823 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014824 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14825 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014826 }
14827 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014828 }
14829
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014830 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014831 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014832
14833 throw new SecurityException("Caller uid=" + uid
14834 + " is not privileged to communicate with user=" + userId);
14835 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014836
14837 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014838 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014839 }
14840
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014841 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014842 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014843 ApplicationInfo newInfo = new ApplicationInfo(info);
14844 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014845 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14846 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014847 return newInfo;
14848 }
14849
14850 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014851 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014852 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014853 return aInfo;
14854 }
14855
14856 ActivityInfo info = new ActivityInfo(aInfo);
14857 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14858 return info;
14859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014860}