blob: 7d2d047bc755d8cfa26834a3b97ef0bd8731ffc3 [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;
Adam Cohenf7522022012-10-03 20:03:18 -070024import com.android.internal.widget.LockPatternUtils;
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;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080032import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033
Dianne Hackborndd71fc82009-12-16 19:24:32 -080034import dalvik.system.Zygote;
35
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.app.Activity;
37import android.app.ActivityManager;
38import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070039import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.app.ActivityThread;
41import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070042import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020043import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070045import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.app.IApplicationThread;
47import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070048import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070049import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070051import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.app.IThumbnailReceiver;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070053import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070055import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070056import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080058import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020059import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080060import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080061import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070062import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070064import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.ContentResolver;
66import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020067import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070068import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070069import android.content.IIntentReceiver;
70import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070071import android.content.Intent;
72import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070073import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.content.pm.ActivityInfo;
75import android.content.pm.ApplicationInfo;
76import android.content.pm.ConfigurationInfo;
77import android.content.pm.IPackageDataObserver;
78import android.content.pm.IPackageManager;
79import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080080import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070082import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070083import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070084import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.pm.ProviderInfo;
86import android.content.pm.ResolveInfo;
87import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040088import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.content.res.Configuration;
90import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070091import android.net.Proxy;
92import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.net.Uri;
94import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080095import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080096import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070097import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080098import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -0800100import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.FileUtils;
102import android.os.Handler;
103import android.os.IBinder;
104import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700105import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700106import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.Looper;
108import android.os.Message;
109import android.os.Parcel;
110import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700112import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400114import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700116import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.os.SystemClock;
118import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700119import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700121import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800123import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700124import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700126import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700128import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.view.Gravity;
130import android.view.LayoutInflater;
131import android.view.View;
132import android.view.WindowManager;
133import android.view.WindowManagerPolicy;
134
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700135import java.io.BufferedInputStream;
136import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700137import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.DataInputStream;
139import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.File;
141import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700142import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700144import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200145import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800146import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700148import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.lang.ref.WeakReference;
150import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700151import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700152import java.util.Collections;
153import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.util.HashMap;
155import java.util.HashSet;
156import java.util.Iterator;
157import java.util.List;
158import java.util.Locale;
159import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700160import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700161import java.util.concurrent.atomic.AtomicBoolean;
162import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700164public final class ActivityManagerService extends ActivityManagerNative
165 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700166 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700168 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400170 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final boolean DEBUG_SWITCH = localLOGV || false;
172 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700173 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_PAUSE = localLOGV || false;
175 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
176 static final boolean DEBUG_TRANSITION = localLOGV || false;
177 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800178 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700179 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700181 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_VISBILITY = localLOGV || false;
183 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700184 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700185 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700186 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800187 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700189 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700190 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700191 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700192 static final boolean DEBUG_POWER = localLOGV || false;
193 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700194 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 static final boolean VALIDATE_TOKENS = false;
196 static final boolean SHOW_ACTIVITY_START_TIME = true;
197
198 // Control over CPU and battery monitoring.
199 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
200 static final boolean MONITOR_CPU_USAGE = true;
201 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
202 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
203 static final boolean MONITOR_THREAD_CPU_USAGE = false;
204
Dianne Hackborn1655be42009-05-08 14:29:01 -0700205 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700206 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700207
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800208 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700210 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 // Maximum number of recent tasks that we can remember.
213 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700214
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700215 // Amount of time after a call to stopAppSwitches() during which we will
216 // prevent further untrusted switches from happening.
217 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
219 // How long we wait for a launched process to attach to the activity manager
220 // before we decide it's never going to come up for real.
221 static final int PROC_START_TIMEOUT = 10*1000;
222
Jeff Brown3f9dd282011-07-08 20:02:19 -0700223 // How long we wait for a launched process to attach to the activity manager
224 // before we decide it's never going to come up for real, when the process was
225 // started with a wrapper for instrumentation (such as Valgrind) because it
226 // could take much longer than usual.
227 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // How long to wait after going idle before forcing apps to GC.
230 static final int GC_TIMEOUT = 5*1000;
231
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700232 // The minimum amount of time between successive GC requests for a process.
233 static final int GC_MIN_INTERVAL = 60*1000;
234
Dianne Hackborn287952c2010-09-22 22:34:31 -0700235 // The rate at which we check for apps using excessive power -- 15 mins.
236 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
237
238 // The minimum sample duration we will allow before deciding we have
239 // enough data on wake locks to start killing things.
240 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
241
242 // The minimum sample duration we will allow before deciding we have
243 // enough data on CPU usage to start killing things.
244 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800247 static final int BROADCAST_FG_TIMEOUT = 10*1000;
248 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // How long we wait until we timeout on key dispatching.
251 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 // How long we wait until we timeout on key dispatching during instrumentation.
254 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
255
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700256 // Amount of time we wait for observers to handle a user switch before
257 // giving up on them and unfreezing the screen.
258 static final int USER_SWITCH_TIMEOUT = 2*1000;
259
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700260 // Maximum number of users we allow to be running at a time.
261 static final int MAX_RUNNING_USERS = 3;
262
Dan Egnor42471dd2010-01-07 17:25:22 -0800263 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264
265 static final String[] EMPTY_STRING_ARRAY = new String[0];
266
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700267 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700268
269 private final boolean mHeadless;
270
Joe Onorato54a4a412011-11-02 20:50:08 -0700271 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
272 // default actuion automatically. Important for devices without direct input
273 // devices.
274 private boolean mShowDialogs = true;
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700277 * Description of a request to start a new activity, which has been held
278 * due to app switches being disabled.
279 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700280 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700281 ActivityRecord r;
282 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700283 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700284 }
285
286 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
287 = new ArrayList<PendingActivityLaunch>();
288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800290 BroadcastQueue mFgBroadcastQueue;
291 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800292 // Convenient for easy iteration over the queues. Foreground is first
293 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800294 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800295
296 BroadcastQueue broadcastQueueForIntent(Intent intent) {
297 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
298 if (DEBUG_BACKGROUND_BROADCAST) {
299 Slog.i(TAG, "Broadcast intent " + intent + " on "
300 + (isFg ? "foreground" : "background")
301 + " queue");
302 }
303 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
304 }
305
306 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
307 for (BroadcastQueue queue : mBroadcastQueues) {
308 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
309 if (r != null) {
310 return r;
311 }
312 }
313 return null;
314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315
316 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 * Activity we have told the window manager to have key focus.
318 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700319 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700320 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 * List of intents that were used to start the most recent tasks.
322 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700323 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
325 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700326 * Process management.
327 */
328 final ProcessList mProcessList = new ProcessList();
329
330 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * All of the applications we currently have running organized by name.
332 * The keys are strings of the application package name (as
333 * returned by the package manager), and the keys are ApplicationRecord
334 * objects.
335 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700336 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337
338 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800339 * The currently running isolated processes.
340 */
341 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
342
343 /**
344 * Counter for assigning isolated process uids, to avoid frequently reusing the
345 * same ones.
346 */
347 int mNextIsolatedProcessUid = 0;
348
349 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700350 * The currently running heavy-weight process, if any.
351 */
352 ProcessRecord mHeavyWeightProcess = null;
353
354 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 * The last time that various processes have crashed.
356 */
357 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
358
359 /**
360 * Set of applications that we consider to be bad, and will reject
361 * incoming broadcasts from (which the user has no control over).
362 * Processes are added to this set when they have crashed twice within
363 * a minimum amount of time; they are removed from it when they are
364 * later restarted (hopefully due to some user action). The value is the
365 * time it was added to the list.
366 */
367 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
368
369 /**
370 * All of the processes we currently have running organized by pid.
371 * The keys are the pid running the application.
372 *
373 * <p>NOTE: This object is protected by its own lock, NOT the global
374 * activity manager lock!
375 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700376 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377
378 /**
379 * All of the processes that have been forced to be foreground. The key
380 * is the pid of the caller who requested it (we hold a death
381 * link on it).
382 */
383 abstract class ForegroundToken implements IBinder.DeathRecipient {
384 int pid;
385 IBinder token;
386 }
387 final SparseArray<ForegroundToken> mForegroundProcesses
388 = new SparseArray<ForegroundToken>();
389
390 /**
391 * List of records for processes that someone had tried to start before the
392 * system was ready. We don't start them at that point, but ensure they
393 * are started by the time booting is complete.
394 */
395 final ArrayList<ProcessRecord> mProcessesOnHold
396 = new ArrayList<ProcessRecord>();
397
398 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 * List of persistent applications that are in the process
400 * of being started.
401 */
402 final ArrayList<ProcessRecord> mPersistentStartingProcesses
403 = new ArrayList<ProcessRecord>();
404
405 /**
406 * Processes that are being forcibly torn down.
407 */
408 final ArrayList<ProcessRecord> mRemovedProcesses
409 = new ArrayList<ProcessRecord>();
410
411 /**
412 * List of running applications, sorted by recent usage.
413 * The first entry in the list is the least recently used.
414 * It contains ApplicationRecord objects. This list does NOT include
415 * any persistent application records (since we never want to exit them).
416 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800417 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 = new ArrayList<ProcessRecord>();
419
420 /**
421 * List of processes that should gc as soon as things are idle.
422 */
423 final ArrayList<ProcessRecord> mProcessesToGc
424 = new ArrayList<ProcessRecord>();
425
426 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800427 * This is the process holding what we currently consider to be
428 * the "home" activity.
429 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700430 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800431
432 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700433 * This is the process holding the activity the user last visited that
434 * is in a different process from the one they are currently in.
435 */
436 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800437
438 /**
439 * The time at which the previous process was last visible.
440 */
441 long mPreviousProcessVisibleTime;
442
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700443 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700444 * Which uses have been started, so are allowed to run code.
445 */
446 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
447
448 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700449 * LRU list of history of current users. Most recently current is at the end.
450 */
451 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
452
453 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700454 * Constant array of the users that are currently started.
455 */
456 int[] mStartedUserArray = new int[] { 0 };
457
458 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700459 * Registered observers of the user switching mechanics.
460 */
461 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
462 = new RemoteCallbackList<IUserSwitchObserver>();
463
464 /**
465 * Currently active user switch.
466 */
467 Object mCurUserSwitchCallback;
468
469 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400470 * Packages that the user has asked to have run in screen size
471 * compatibility mode instead of filling the screen.
472 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700473 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400474
475 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 * Set of PendingResultRecord objects that are currently active.
477 */
478 final HashSet mPendingResultRecords = new HashSet();
479
480 /**
481 * Set of IntentSenderRecord objects that are currently active.
482 */
483 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
484 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
485
486 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800487 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700488 * already logged DropBox entries for. Guarded by itself. If
489 * something (rogue user app) forces this over
490 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
491 */
492 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
493 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
494
495 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700496 * Strict Mode background batched logging state.
497 *
498 * The string buffer is guarded by itself, and its lock is also
499 * used to determine if another batched write is already
500 * in-flight.
501 */
502 private final StringBuilder mStrictModeBuffer = new StringBuilder();
503
504 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 * Keeps track of all IIntentReceivers that have been registered for
506 * broadcasts. Hash keys are the receiver IBinder, hash value is
507 * a ReceiverList.
508 */
509 final HashMap mRegisteredReceivers = new HashMap();
510
511 /**
512 * Resolver for broadcast intents to registered receivers.
513 * Holds BroadcastFilter (subclass of IntentFilter).
514 */
515 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
516 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
517 @Override
518 protected boolean allowFilterResult(
519 BroadcastFilter filter, List<BroadcastFilter> dest) {
520 IBinder target = filter.receiverList.receiver.asBinder();
521 for (int i=dest.size()-1; i>=0; i--) {
522 if (dest.get(i).receiverList.receiver.asBinder() == target) {
523 return false;
524 }
525 }
526 return true;
527 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700528
529 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700530 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700531 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
532 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700533 return super.newResult(filter, match, userId);
534 }
535 return null;
536 }
537
538 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700539 protected BroadcastFilter[] newArray(int size) {
540 return new BroadcastFilter[size];
541 }
542
543 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700544 protected String packageForFilter(BroadcastFilter filter) {
545 return filter.packageName;
546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 };
548
549 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700550 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700552 * that action (which should usually be one). The SparseArray is keyed
553 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
554 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700556 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
557 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700559 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560
561 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700562 * Backup/restore process management
563 */
564 String mBackupAppName = null;
565 BackupRecord mBackupTarget = null;
566
567 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 * List of PendingThumbnailsRecord objects of clients who are still
569 * waiting to receive all of the thumbnails for a task.
570 */
571 final ArrayList mPendingThumbnails = new ArrayList();
572
573 /**
574 * List of HistoryRecord objects that have been finished and must
575 * still report back to a pending thumbnail receiver.
576 */
577 final ArrayList mCancelledThumbnails = new ArrayList();
578
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700579 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 /**
582 * List of content providers who have clients waiting for them. The
583 * application is currently being launched and the provider will be
584 * removed from this list once it is published.
585 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700586 final ArrayList<ContentProviderRecord> mLaunchingProviders
587 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588
589 /**
590 * Global set of specific Uri permissions that have been granted.
591 */
592 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
593 = new SparseArray<HashMap<Uri, UriPermission>>();
594
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800595 CoreSettingsObserver mCoreSettingsObserver;
596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 /**
598 * Thread-local storage used to carry caller permissions over through
599 * indirect content-provider access.
600 * @see #ActivityManagerService.openContentUri()
601 */
602 private class Identity {
603 public int pid;
604 public int uid;
605
606 Identity(int _pid, int _uid) {
607 pid = _pid;
608 uid = _uid;
609 }
610 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
613
614 /**
615 * All information we have collected about the runtime performance of
616 * any user id that can impact battery performance.
617 */
618 final BatteryStatsService mBatteryStatsService;
619
620 /**
621 * information about component usage
622 */
623 final UsageStatsService mUsageStatsService;
624
625 /**
626 * Current configuration information. HistoryRecord objects are given
627 * a reference to this object to indicate which configuration they are
628 * currently running in, so this object must be kept immutable.
629 */
630 Configuration mConfiguration = new Configuration();
631
632 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800633 * Current sequencing integer of the configuration, for skipping old
634 * configurations.
635 */
636 int mConfigurationSeq = 0;
637
638 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700639 * Hardware-reported OpenGLES version.
640 */
641 final int GL_ES_VERSION;
642
643 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 * List of initialization arguments to pass to all processes when binding applications to them.
645 * For example, references to the commonly used services.
646 */
647 HashMap<String, IBinder> mAppBindArgs;
648
649 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700650 * Temporary to avoid allocations. Protected by main lock.
651 */
652 final StringBuilder mStringBuilder = new StringBuilder(256);
653
654 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 * Used to control how we initialize the service.
656 */
657 boolean mStartRunning = false;
658 ComponentName mTopComponent;
659 String mTopAction;
660 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700661 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 boolean mSystemReady = false;
663 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700664 boolean mWaitingUpdate = false;
665 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700666 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700667 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668
669 Context mContext;
670
671 int mFactoryTest;
672
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700673 boolean mCheckedForSetup;
674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700676 * The time at which we will allow normal application switches again,
677 * after a call to {@link #stopAppSwitches()}.
678 */
679 long mAppSwitchesAllowedTime;
680
681 /**
682 * This is set to true after the first switch after mAppSwitchesAllowedTime
683 * is set; any switches after that will clear the time.
684 */
685 boolean mDidAppSwitch;
686
687 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700688 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700689 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700690 long mLastPowerCheckRealtime;
691
692 /**
693 * Last time (in uptime) at which we checked for power usage.
694 */
695 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700696
697 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 * Set while we are wanting to sleep, to prevent any
699 * activities from being started/resumed.
700 */
701 boolean mSleeping = false;
702
703 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700704 * State of external calls telling us if the device is asleep.
705 */
706 boolean mWentToSleep = false;
707
708 /**
709 * State of external call telling us if the lock screen is shown.
710 */
711 boolean mLockScreenShown = false;
712
713 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700714 * Set if we are shutting down the system, similar to sleeping.
715 */
716 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717
718 /**
719 * Task identifier that activities are currently being started
720 * in. Incremented each time a new task is created.
721 * todo: Replace this with a TokenSpace class that generates non-repeating
722 * integers that won't wrap.
723 */
724 int mCurTask = 1;
725
726 /**
727 * Current sequence id for oom_adj computation traversal.
728 */
729 int mAdjSeq = 0;
730
731 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700732 * Current sequence id for process LRU updating.
733 */
734 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735
736 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700737 * Keep track of the non-hidden/empty process we last found, to help
738 * determine how to distribute hidden/empty processes next time.
739 */
740 int mNumNonHiddenProcs = 0;
741
742 /**
743 * Keep track of the number of hidden procs, to balance oom adj
744 * distribution between those and empty procs.
745 */
746 int mNumHiddenProcs = 0;
747
748 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700749 * Keep track of the number of service processes we last found, to
750 * determine on the next iteration which should be B services.
751 */
752 int mNumServiceProcs = 0;
753 int mNewNumServiceProcs = 0;
754
755 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 * System monitoring: number of processes that died since the last
757 * N procs were started.
758 */
759 int[] mProcDeaths = new int[20];
760
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700761 /**
762 * This is set if we had to do a delayed dexopt of an app before launching
763 * it, to increasing the ANR timeouts in that case.
764 */
765 boolean mDidDexOpt;
766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 String mDebugApp = null;
768 boolean mWaitForDebugger = false;
769 boolean mDebugTransient = false;
770 String mOrigDebugApp = null;
771 boolean mOrigWaitForDebugger = false;
772 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700773 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700774 String mProfileApp = null;
775 ProcessRecord mProfileProc = null;
776 String mProfileFile;
777 ParcelFileDescriptor mProfileFd;
778 int mProfileType = 0;
779 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800780 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700782 static class ProcessChangeItem {
783 static final int CHANGE_ACTIVITIES = 1<<0;
784 static final int CHANGE_IMPORTANCE= 1<<1;
785 int changes;
786 int uid;
787 int pid;
788 int importance;
789 boolean foregroundActivities;
790 }
791
Jeff Sharkeya4620792011-05-20 15:29:23 -0700792 final RemoteCallbackList<IProcessObserver> mProcessObservers
793 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700794 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
795
796 final ArrayList<ProcessChangeItem> mPendingProcessChanges
797 = new ArrayList<ProcessChangeItem>();
798 final ArrayList<ProcessChangeItem> mAvailProcessChanges
799 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 /**
802 * Callback of last caller to {@link #requestPss}.
803 */
804 Runnable mRequestPssCallback;
805
806 /**
807 * Remaining processes for which we are waiting results from the last
808 * call to {@link #requestPss}.
809 */
810 final ArrayList<ProcessRecord> mRequestPssList
811 = new ArrayList<ProcessRecord>();
812
813 /**
814 * Runtime statistics collection thread. This object's lock is used to
815 * protect all related state.
816 */
817 final Thread mProcessStatsThread;
818
819 /**
820 * Used to collect process stats when showing not responding dialog.
821 * Protected by mProcessStatsThread.
822 */
823 final ProcessStats mProcessStats = new ProcessStats(
824 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700825 final AtomicLong mLastCpuTime = new AtomicLong(0);
826 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 long mLastWriteTime = 0;
829
830 /**
831 * Set to true after the system has finished booting.
832 */
833 boolean mBooted = false;
834
Dianne Hackborn7d608422011-08-07 16:24:18 -0700835 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700836 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837
838 WindowManagerService mWindowManager;
839
840 static ActivityManagerService mSelf;
841 static ActivityThread mSystemThread;
842
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700843 private int mCurrentUserId = 0;
844 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700845 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 private final class AppDeathRecipient implements IBinder.DeathRecipient {
848 final ProcessRecord mApp;
849 final int mPid;
850 final IApplicationThread mAppThread;
851
852 AppDeathRecipient(ProcessRecord app, int pid,
853 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800854 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 TAG, "New death recipient " + this
856 + " for thread " + thread.asBinder());
857 mApp = app;
858 mPid = pid;
859 mAppThread = thread;
860 }
861
862 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800863 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 TAG, "Death received in " + this
865 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 synchronized(ActivityManagerService.this) {
867 appDiedLocked(mApp, mPid, mAppThread);
868 }
869 }
870 }
871
872 static final int SHOW_ERROR_MSG = 1;
873 static final int SHOW_NOT_RESPONDING_MSG = 2;
874 static final int SHOW_FACTORY_ERROR_MSG = 3;
875 static final int UPDATE_CONFIGURATION_MSG = 4;
876 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
877 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 static final int SERVICE_TIMEOUT_MSG = 12;
879 static final int UPDATE_TIME_ZONE = 13;
880 static final int SHOW_UID_ERROR_MSG = 14;
881 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700883 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700884 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800885 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700886 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
887 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700888 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700889 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700890 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700891 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700892 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700893 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700894 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700895 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700896 static final int REPORT_USER_SWITCH_MSG = 34;
897 static final int CONTINUE_USER_SWITCH_MSG = 35;
898 static final int USER_SWITCH_TIMEOUT_MSG = 36;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800900 static final int FIRST_ACTIVITY_STACK_MSG = 100;
901 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
902 static final int FIRST_COMPAT_MODE_MSG = 300;
903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700905 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700906 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907
908 final Handler mHandler = new Handler() {
909 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800910 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 //}
912
913 public void handleMessage(Message msg) {
914 switch (msg.what) {
915 case SHOW_ERROR_MSG: {
916 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700917 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
918 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 synchronized (ActivityManagerService.this) {
920 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700921 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800923 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700924 if (res != null) {
925 res.set(0);
926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 return;
928 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700929 if (!showBackground && UserHandle.getAppId(proc.uid)
930 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
931 && proc.pid != MY_PID) {
932 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
933 if (res != null) {
934 res.set(0);
935 }
936 return;
937 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700938 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700939 Dialog d = new AppErrorDialog(mContext,
940 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 d.show();
942 proc.crashDialog = d;
943 } else {
944 // The device is asleep, so just pretend that the user
945 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700946 if (res != null) {
947 res.set(0);
948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
950 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700951
952 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 } break;
954 case SHOW_NOT_RESPONDING_MSG: {
955 synchronized (ActivityManagerService.this) {
956 HashMap data = (HashMap) msg.obj;
957 ProcessRecord proc = (ProcessRecord)data.get("app");
958 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800959 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 return;
961 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800962
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700963 Intent intent = new Intent("android.intent.action.ANR");
964 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800965 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
966 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700967 }
968 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800969 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700970 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800971
Justin Kohbc52ca22012-03-29 15:11:44 -0700972 if (mShowDialogs) {
973 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -0700974 mContext, proc, (ActivityRecord)data.get("activity"),
975 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -0700976 d.show();
977 proc.anrDialog = d;
978 } else {
979 // Just kill the app if there is no dialog to be shown.
980 killAppAtUsersRequest(proc, null);
981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700983
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700984 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700986 case SHOW_STRICT_MODE_VIOLATION_MSG: {
987 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
988 synchronized (ActivityManagerService.this) {
989 ProcessRecord proc = (ProcessRecord) data.get("app");
990 if (proc == null) {
991 Slog.e(TAG, "App not found when showing strict mode dialog.");
992 break;
993 }
994 if (proc.crashDialog != null) {
995 Slog.e(TAG, "App already has strict mode dialog: " + proc);
996 return;
997 }
998 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700999 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001000 Dialog d = new StrictModeViolationDialog(mContext,
1001 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001002 d.show();
1003 proc.crashDialog = d;
1004 } else {
1005 // The device is asleep, so just pretend that the user
1006 // saw a crash dialog and hit "force quit".
1007 res.set(0);
1008 }
1009 }
1010 ensureBootCompleted();
1011 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 case SHOW_FACTORY_ERROR_MSG: {
1013 Dialog d = new FactoryErrorDialog(
1014 mContext, msg.getData().getCharSequence("msg"));
1015 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001016 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 } break;
1018 case UPDATE_CONFIGURATION_MSG: {
1019 final ContentResolver resolver = mContext.getContentResolver();
1020 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1021 } break;
1022 case GC_BACKGROUND_PROCESSES_MSG: {
1023 synchronized (ActivityManagerService.this) {
1024 performAppGcsIfAppropriateLocked();
1025 }
1026 } break;
1027 case WAIT_FOR_DEBUGGER_MSG: {
1028 synchronized (ActivityManagerService.this) {
1029 ProcessRecord app = (ProcessRecord)msg.obj;
1030 if (msg.arg1 != 0) {
1031 if (!app.waitedForDebugger) {
1032 Dialog d = new AppWaitingForDebuggerDialog(
1033 ActivityManagerService.this,
1034 mContext, app);
1035 app.waitDialog = d;
1036 app.waitedForDebugger = true;
1037 d.show();
1038 }
1039 } else {
1040 if (app.waitDialog != null) {
1041 app.waitDialog.dismiss();
1042 app.waitDialog = null;
1043 }
1044 }
1045 }
1046 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001048 if (mDidDexOpt) {
1049 mDidDexOpt = false;
1050 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1051 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001052 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001053 return;
1054 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001055 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 } break;
1057 case UPDATE_TIME_ZONE: {
1058 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001059 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1060 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 if (r.thread != null) {
1062 try {
1063 r.thread.updateTimeZone();
1064 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001065 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
1067 }
1068 }
1069 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001070 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001071 case CLEAR_DNS_CACHE: {
1072 synchronized (ActivityManagerService.this) {
1073 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1074 ProcessRecord r = mLruProcesses.get(i);
1075 if (r.thread != null) {
1076 try {
1077 r.thread.clearDnsCache();
1078 } catch (RemoteException ex) {
1079 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1080 }
1081 }
1082 }
1083 }
1084 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001085 case UPDATE_HTTP_PROXY: {
1086 ProxyProperties proxy = (ProxyProperties)msg.obj;
1087 String host = "";
1088 String port = "";
1089 String exclList = "";
1090 if (proxy != null) {
1091 host = proxy.getHost();
1092 port = Integer.toString(proxy.getPort());
1093 exclList = proxy.getExclusionList();
1094 }
1095 synchronized (ActivityManagerService.this) {
1096 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1097 ProcessRecord r = mLruProcesses.get(i);
1098 if (r.thread != null) {
1099 try {
1100 r.thread.setHttpProxy(host, port, exclList);
1101 } catch (RemoteException ex) {
1102 Slog.w(TAG, "Failed to update http proxy for: " +
1103 r.info.processName);
1104 }
1105 }
1106 }
1107 }
1108 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001110 String title = "System UIDs Inconsistent";
1111 String text = "UIDs on the system are inconsistent, you need to wipe your"
1112 + " data partition or your device will be unstable.";
1113 Log.e(TAG, title + ": " + text);
1114 if (mShowDialogs) {
1115 // XXX This is a temporary dialog, no need to localize.
1116 AlertDialog d = new BaseErrorDialog(mContext);
1117 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1118 d.setCancelable(false);
1119 d.setTitle(title);
1120 d.setMessage(text);
1121 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1122 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1123 mUidAlert = d;
1124 d.show();
1125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 } break;
1127 case IM_FEELING_LUCKY_MSG: {
1128 if (mUidAlert != null) {
1129 mUidAlert.dismiss();
1130 mUidAlert = null;
1131 }
1132 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001134 if (mDidDexOpt) {
1135 mDidDexOpt = false;
1136 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1137 nmsg.obj = msg.obj;
1138 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1139 return;
1140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 ProcessRecord app = (ProcessRecord)msg.obj;
1142 synchronized (ActivityManagerService.this) {
1143 processStartTimedOutLocked(app);
1144 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001145 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001146 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1147 synchronized (ActivityManagerService.this) {
1148 doPendingActivityLaunchesLocked(true);
1149 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001150 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001151 case KILL_APPLICATION_MSG: {
1152 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001153 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001154 boolean restart = (msg.arg2 == 1);
1155 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001156 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1157 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001158 }
1159 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001160 case FINALIZE_PENDING_INTENT_MSG: {
1161 ((PendingIntentRecord)msg.obj).completeFinalize();
1162 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001163 case POST_HEAVY_NOTIFICATION_MSG: {
1164 INotificationManager inm = NotificationManager.getService();
1165 if (inm == null) {
1166 return;
1167 }
1168
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001169 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001170 ProcessRecord process = root.app;
1171 if (process == null) {
1172 return;
1173 }
1174
1175 try {
1176 Context context = mContext.createPackageContext(process.info.packageName, 0);
1177 String text = mContext.getString(R.string.heavy_weight_notification,
1178 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1179 Notification notification = new Notification();
1180 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1181 notification.when = 0;
1182 notification.flags = Notification.FLAG_ONGOING_EVENT;
1183 notification.tickerText = text;
1184 notification.defaults = 0; // please be quiet
1185 notification.sound = null;
1186 notification.vibrate = null;
1187 notification.setLatestEventInfo(context, text,
1188 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001189 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1190 PendingIntent.FLAG_CANCEL_CURRENT, null,
1191 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001192
1193 try {
1194 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001195 inm.enqueueNotificationWithTag("android", null,
1196 R.string.heavy_weight_notification,
1197 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001198 } catch (RuntimeException e) {
1199 Slog.w(ActivityManagerService.TAG,
1200 "Error showing notification for heavy-weight app", e);
1201 } catch (RemoteException e) {
1202 }
1203 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001204 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001205 }
1206 } break;
1207 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1208 INotificationManager inm = NotificationManager.getService();
1209 if (inm == null) {
1210 return;
1211 }
1212 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001213 inm.cancelNotificationWithTag("android", null,
1214 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001215 } catch (RuntimeException e) {
1216 Slog.w(ActivityManagerService.TAG,
1217 "Error canceling notification for service", e);
1218 } catch (RemoteException e) {
1219 }
1220 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001221 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1222 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001223 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001224 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001225 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1226 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001227 }
1228 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001229 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1230 synchronized (ActivityManagerService.this) {
1231 ActivityRecord ar = (ActivityRecord)msg.obj;
1232 if (mCompatModeDialog != null) {
1233 if (mCompatModeDialog.mAppInfo.packageName.equals(
1234 ar.info.applicationInfo.packageName)) {
1235 return;
1236 }
1237 mCompatModeDialog.dismiss();
1238 mCompatModeDialog = null;
1239 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001240 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001241 if (mCompatModePackages.getPackageAskCompatModeLocked(
1242 ar.packageName)) {
1243 int mode = mCompatModePackages.computeCompatModeLocked(
1244 ar.info.applicationInfo);
1245 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1246 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1247 mCompatModeDialog = new CompatModeDialog(
1248 ActivityManagerService.this, mContext,
1249 ar.info.applicationInfo);
1250 mCompatModeDialog.show();
1251 }
1252 }
1253 }
1254 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001255 break;
1256 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001257 case DISPATCH_PROCESSES_CHANGED: {
1258 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001259 break;
1260 }
1261 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001262 final int pid = msg.arg1;
1263 final int uid = msg.arg2;
1264 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001265 break;
1266 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001267 case REPORT_MEM_USAGE: {
1268 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1269 if (!isDebuggable) {
1270 return;
1271 }
1272 synchronized (ActivityManagerService.this) {
1273 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001274 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1275 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001276 // avoid spamming.
1277 return;
1278 }
1279 mLastMemUsageReportTime = now;
1280 }
1281 Thread thread = new Thread() {
1282 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001283 StringBuilder dropBuilder = new StringBuilder(1024);
1284 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001285 StringWriter oomSw = new StringWriter();
1286 PrintWriter oomPw = new PrintWriter(oomSw);
1287 StringWriter catSw = new StringWriter();
1288 PrintWriter catPw = new PrintWriter(catSw);
1289 String[] emptyArgs = new String[] { };
1290 StringBuilder tag = new StringBuilder(128);
1291 StringBuilder stack = new StringBuilder(128);
1292 tag.append("Low on memory -- ");
1293 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1294 tag, stack);
1295 dropBuilder.append(stack);
1296 dropBuilder.append('\n');
1297 dropBuilder.append('\n');
1298 String oomString = oomSw.toString();
1299 dropBuilder.append(oomString);
1300 dropBuilder.append('\n');
1301 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001302 try {
1303 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1304 "procrank", });
1305 final InputStreamReader converter = new InputStreamReader(
1306 proc.getInputStream());
1307 BufferedReader in = new BufferedReader(converter);
1308 String line;
1309 while (true) {
1310 line = in.readLine();
1311 if (line == null) {
1312 break;
1313 }
1314 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001315 logBuilder.append(line);
1316 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001317 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001318 dropBuilder.append(line);
1319 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001320 }
1321 converter.close();
1322 } catch (IOException e) {
1323 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001324 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001325 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001326 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001327 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001328 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1329 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001330 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001331 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001332 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001333 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001334 addErrorToDropBox("lowmem", null, "system_server", null,
1335 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001336 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001337 synchronized (ActivityManagerService.this) {
1338 long now = SystemClock.uptimeMillis();
1339 if (mLastMemUsageReportTime < now) {
1340 mLastMemUsageReportTime = now;
1341 }
1342 }
1343 }
1344 };
1345 thread.start();
1346 break;
1347 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001348 case REPORT_USER_SWITCH_MSG: {
1349 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1350 break;
1351 }
1352 case CONTINUE_USER_SWITCH_MSG: {
1353 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1354 break;
1355 }
1356 case USER_SWITCH_TIMEOUT_MSG: {
1357 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1358 break;
1359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
1361 }
1362 };
1363
1364 public static void setSystemProcess() {
1365 try {
1366 ActivityManagerService m = mSelf;
1367
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001368 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001370 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001371 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 if (MONITOR_CPU_USAGE) {
1373 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 ServiceManager.addService("permission", new PermissionController(m));
1376
1377 ApplicationInfo info =
1378 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001379 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001380 mSystemThread.installSystemApplicationInfo(info);
1381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 synchronized (mSelf) {
1383 ProcessRecord app = mSelf.newProcessRecordLocked(
1384 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001385 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001387 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001388 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001389 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 synchronized (mSelf.mPidsSelfLocked) {
1391 mSelf.mPidsSelfLocked.put(app.pid, app);
1392 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001393 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
1395 } catch (PackageManager.NameNotFoundException e) {
1396 throw new RuntimeException(
1397 "Unable to find android system package", e);
1398 }
1399 }
1400
1401 public void setWindowManager(WindowManagerService wm) {
1402 mWindowManager = wm;
1403 }
1404
1405 public static final Context main(int factoryTest) {
1406 AThread thr = new AThread();
1407 thr.start();
1408
1409 synchronized (thr) {
1410 while (thr.mService == null) {
1411 try {
1412 thr.wait();
1413 } catch (InterruptedException e) {
1414 }
1415 }
1416 }
1417
1418 ActivityManagerService m = thr.mService;
1419 mSelf = m;
1420 ActivityThread at = ActivityThread.systemMain();
1421 mSystemThread = at;
1422 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001423 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 m.mContext = context;
1425 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001426 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
1428 m.mBatteryStatsService.publish(context);
1429 m.mUsageStatsService.publish(context);
1430
1431 synchronized (thr) {
1432 thr.mReady = true;
1433 thr.notifyAll();
1434 }
1435
1436 m.startRunning(null, null, null, null);
1437
1438 return context;
1439 }
1440
1441 public static ActivityManagerService self() {
1442 return mSelf;
1443 }
1444
1445 static class AThread extends Thread {
1446 ActivityManagerService mService;
1447 boolean mReady = false;
1448
1449 public AThread() {
1450 super("ActivityManager");
1451 }
1452
1453 public void run() {
1454 Looper.prepare();
1455
1456 android.os.Process.setThreadPriority(
1457 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001458 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459
1460 ActivityManagerService m = new ActivityManagerService();
1461
1462 synchronized (this) {
1463 mService = m;
1464 notifyAll();
1465 }
1466
1467 synchronized (this) {
1468 while (!mReady) {
1469 try {
1470 wait();
1471 } catch (InterruptedException e) {
1472 }
1473 }
1474 }
1475
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001476 // For debug builds, log event loop stalls to dropbox for analysis.
1477 if (StrictMode.conditionallyEnableDebugLogging()) {
1478 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1479 }
1480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 Looper.loop();
1482 }
1483 }
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 static class MemBinder extends Binder {
1486 ActivityManagerService mActivityManagerService;
1487 MemBinder(ActivityManagerService activityManagerService) {
1488 mActivityManagerService = activityManagerService;
1489 }
1490
1491 @Override
1492 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001493 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1494 != PackageManager.PERMISSION_GRANTED) {
1495 pw.println("Permission Denial: can't dump meminfo from from pid="
1496 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1497 + " without permission " + android.Manifest.permission.DUMP);
1498 return;
1499 }
1500
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001501 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001502 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
1504 }
1505
Chet Haase9c1e23b2011-03-24 10:51:31 -07001506 static class GraphicsBinder extends Binder {
1507 ActivityManagerService mActivityManagerService;
1508 GraphicsBinder(ActivityManagerService activityManagerService) {
1509 mActivityManagerService = activityManagerService;
1510 }
1511
1512 @Override
1513 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001514 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1515 != PackageManager.PERMISSION_GRANTED) {
1516 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1517 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1518 + " without permission " + android.Manifest.permission.DUMP);
1519 return;
1520 }
1521
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001522 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001523 }
1524 }
1525
Jeff Brown6754ba22011-12-14 20:20:01 -08001526 static class DbBinder extends Binder {
1527 ActivityManagerService mActivityManagerService;
1528 DbBinder(ActivityManagerService activityManagerService) {
1529 mActivityManagerService = activityManagerService;
1530 }
1531
1532 @Override
1533 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1534 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1535 != PackageManager.PERMISSION_GRANTED) {
1536 pw.println("Permission Denial: can't dump dbinfo from from pid="
1537 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1538 + " without permission " + android.Manifest.permission.DUMP);
1539 return;
1540 }
1541
1542 mActivityManagerService.dumpDbInfo(fd, pw, args);
1543 }
1544 }
1545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 static class CpuBinder extends Binder {
1547 ActivityManagerService mActivityManagerService;
1548 CpuBinder(ActivityManagerService activityManagerService) {
1549 mActivityManagerService = activityManagerService;
1550 }
1551
1552 @Override
1553 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001554 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1555 != PackageManager.PERMISSION_GRANTED) {
1556 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1557 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1558 + " without permission " + android.Manifest.permission.DUMP);
1559 return;
1560 }
1561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001563 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1564 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1565 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 }
1567 }
1568 }
1569
1570 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001571 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001572
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001573 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1574 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1575 mBroadcastQueues[0] = mFgBroadcastQueue;
1576 mBroadcastQueues[1] = mBgBroadcastQueue;
1577
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001578 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001579 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 File dataDir = Environment.getDataDirectory();
1582 File systemDir = new File(dataDir, "system");
1583 systemDir.mkdirs();
1584 mBatteryStatsService = new BatteryStatsService(new File(
1585 systemDir, "batterystats.bin").toString());
1586 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001587 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001588 mOnBattery = DEBUG_POWER ? true
1589 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001590 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001592 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001593 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001594 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001596 // User 0 is the first and only user that runs at boot.
1597 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001598 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001599 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001600
Jack Palevichb90d28c2009-07-22 15:35:24 -07001601 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1602 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1603
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001604 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001605 mConfiguration.setLocale(Locale.getDefault());
1606
Dianne Hackborn813075a62011-11-14 17:45:19 -08001607 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 mProcessStats.init();
1609
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001610 mCompatModePackages = new CompatModePackages(this, systemDir);
1611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 // Add ourself to the Watchdog monitors.
1613 Watchdog.getInstance().addMonitor(this);
1614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 mProcessStatsThread = new Thread("ProcessStats") {
1616 public void run() {
1617 while (true) {
1618 try {
1619 try {
1620 synchronized(this) {
1621 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001622 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 // + ", write delay=" + nextWriteDelay);
1626 if (nextWriteDelay < nextCpuDelay) {
1627 nextCpuDelay = nextWriteDelay;
1628 }
1629 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001630 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 this.wait(nextCpuDelay);
1632 }
1633 }
1634 } catch (InterruptedException e) {
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 updateCpuStatsNow();
1637 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 }
1640 }
1641 }
1642 };
1643 mProcessStatsThread.start();
1644 }
1645
1646 @Override
1647 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1648 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001649 if (code == SYSPROPS_TRANSACTION) {
1650 // We need to tell all apps about the system property change.
1651 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1652 synchronized(this) {
1653 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1654 final int NA = apps.size();
1655 for (int ia=0; ia<NA; ia++) {
1656 ProcessRecord app = apps.valueAt(ia);
1657 if (app.thread != null) {
1658 procs.add(app.thread.asBinder());
1659 }
1660 }
1661 }
1662 }
1663
1664 int N = procs.size();
1665 for (int i=0; i<N; i++) {
1666 Parcel data2 = Parcel.obtain();
1667 try {
1668 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1669 } catch (RemoteException e) {
1670 }
1671 data2.recycle();
1672 }
1673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 try {
1675 return super.onTransact(code, data, reply, flags);
1676 } catch (RuntimeException e) {
1677 // The activity manager only throws security exceptions, so let's
1678 // log all others.
1679 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001680 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682 throw e;
1683 }
1684 }
1685
1686 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001687 final long now = SystemClock.uptimeMillis();
1688 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1689 return;
1690 }
1691 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1692 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 mProcessStatsThread.notify();
1694 }
1695 }
1696 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 void updateCpuStatsNow() {
1699 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001700 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 final long now = SystemClock.uptimeMillis();
1702 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001705 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1706 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 haveNewCpuStats = true;
1708 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001709 //Slog.i(TAG, mProcessStats.printCurrentState());
1710 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 // + mProcessStats.getTotalCpuPercent() + "%");
1712
Joe Onorato8a9b2202010-02-26 18:56:32 -08001713 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 if ("true".equals(SystemProperties.get("events.cpu"))) {
1715 int user = mProcessStats.getLastUserTime();
1716 int system = mProcessStats.getLastSystemTime();
1717 int iowait = mProcessStats.getLastIoWaitTime();
1718 int irq = mProcessStats.getLastIrqTime();
1719 int softIrq = mProcessStats.getLastSoftIrqTime();
1720 int idle = mProcessStats.getLastIdleTime();
1721
1722 int total = user + system + iowait + irq + softIrq + idle;
1723 if (total == 0) total = 1;
1724
Doug Zongker2bec3d42009-12-04 12:52:44 -08001725 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 ((user+system+iowait+irq+softIrq) * 100) / total,
1727 (user * 100) / total,
1728 (system * 100) / total,
1729 (iowait * 100) / total,
1730 (irq * 100) / total,
1731 (softIrq * 100) / total);
1732 }
1733 }
1734
Amith Yamasanie43530a2009-08-21 13:11:37 -07001735 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001736 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001737 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 synchronized(mPidsSelfLocked) {
1739 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001740 if (mOnBattery) {
1741 int perc = bstats.startAddingCpuLocked();
1742 int totalUTime = 0;
1743 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001744 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001746 ProcessStats.Stats st = mProcessStats.getStats(i);
1747 if (!st.working) {
1748 continue;
1749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001751 int otherUTime = (st.rel_utime*perc)/100;
1752 int otherSTime = (st.rel_stime*perc)/100;
1753 totalUTime += otherUTime;
1754 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 if (pr != null) {
1756 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001757 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1758 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001759 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001760 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001761 } else {
1762 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001763 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001764 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001765 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1766 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001767 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001771 bstats.finishAddingCpuLocked(perc, totalUTime,
1772 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774 }
1775 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1778 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001779 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781 }
1782 }
1783 }
1784
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001785 @Override
1786 public void batteryNeedsCpuUpdate() {
1787 updateCpuStatsNow();
1788 }
1789
1790 @Override
1791 public void batteryPowerChanged(boolean onBattery) {
1792 // When plugging in, update the CPU stats first before changing
1793 // the plug state.
1794 updateCpuStatsNow();
1795 synchronized (this) {
1796 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001797 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001798 }
1799 }
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 /**
1803 * Initialize the application bind args. These are passed to each
1804 * process when the bindApplication() IPC is sent to the process. They're
1805 * lazily setup to make sure the services are running when they're asked for.
1806 */
1807 private HashMap<String, IBinder> getCommonServicesLocked() {
1808 if (mAppBindArgs == null) {
1809 mAppBindArgs = new HashMap<String, IBinder>();
1810
1811 // Setup the application init args
1812 mAppBindArgs.put("package", ServiceManager.getService("package"));
1813 mAppBindArgs.put("window", ServiceManager.getService("window"));
1814 mAppBindArgs.put(Context.ALARM_SERVICE,
1815 ServiceManager.getService(Context.ALARM_SERVICE));
1816 }
1817 return mAppBindArgs;
1818 }
1819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 if (mFocusedActivity != r) {
1822 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001823 if (r != null) {
1824 mWindowManager.setFocusedApp(r.appToken, true);
1825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001829 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001831 int lrui = mLruProcesses.indexOf(app);
1832 if (lrui >= 0) mLruProcesses.remove(lrui);
1833
1834 int i = mLruProcesses.size()-1;
1835 int skipTop = 0;
1836
Dianne Hackborn906497c2010-05-10 15:57:38 -07001837 app.lruSeq = mLruSeq;
1838
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001839 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001840 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001841 if (app.activities.size() > 0) {
1842 // If this process has activities, we more strongly want to keep
1843 // it around.
1844 app.lruWeight = app.lastActivityTime;
1845 } else if (app.pubProviders.size() > 0) {
1846 // If this process contains content providers, we want to keep
1847 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001848 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001849 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001850 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001851 } else {
1852 // If this process doesn't have activities, we less strongly
1853 // want to keep it around, and generally want to avoid getting
1854 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001855 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001856 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001857 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001858 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001859
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001860 while (i >= 0) {
1861 ProcessRecord p = mLruProcesses.get(i);
1862 // If this app shouldn't be in front of the first N background
1863 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001864 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001865 skipTop--;
1866 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001867 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001868 mLruProcesses.add(i+1, app);
1869 break;
1870 }
1871 i--;
1872 }
1873 if (i < 0) {
1874 mLruProcesses.add(0, app);
1875 }
1876
Dianne Hackborn906497c2010-05-10 15:57:38 -07001877 // If the app is currently using a content provider or service,
1878 // bump those processes as well.
1879 if (app.connections.size() > 0) {
1880 for (ConnectionRecord cr : app.connections) {
1881 if (cr.binding != null && cr.binding.service != null
1882 && cr.binding.service.app != null
1883 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001884 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001885 }
1886 }
1887 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001888 for (int j=app.conProviders.size()-1; j>=0; j--) {
1889 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1890 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001891 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001892 }
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001896 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001897 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001898 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001899 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001900
1901 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1902 if (oomAdj) {
1903 updateOomAdjLocked();
1904 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001905 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001906
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001907 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001909 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001910 // The system gets to run in any process. If there are multiple
1911 // processes with the same uid, just pick the first (this
1912 // should never happen).
1913 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1914 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001915 if (procs == null) return null;
1916 final int N = procs.size();
1917 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001918 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
1921 ProcessRecord proc = mProcessNames.get(processName, uid);
1922 return proc;
1923 }
1924
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001925 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001926 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001927 try {
1928 if (pm.performDexOpt(packageName)) {
1929 mDidDexOpt = true;
1930 }
1931 } catch (RemoteException e) {
1932 }
1933 }
1934
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001935 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 int transit = mWindowManager.getPendingAppTransition();
1937 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1938 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1939 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1940 }
1941
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001942 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001944 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1945 boolean isolated) {
1946 ProcessRecord app;
1947 if (!isolated) {
1948 app = getProcessRecordLocked(processName, info.uid);
1949 } else {
1950 // If this is an isolated process, it can't re-use an existing process.
1951 app = null;
1952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 // We don't have to do anything more if:
1954 // (1) There is an existing application record; and
1955 // (2) The caller doesn't think it is dead, OR there is no thread
1956 // object attached to it so we know it couldn't have crashed; and
1957 // (3) There is a pid assigned to it, so it is either starting or
1958 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001959 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 + " app=" + app + " knownToBeDead=" + knownToBeDead
1961 + " thread=" + (app != null ? app.thread : null)
1962 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001963 if (app != null && app.pid > 0) {
1964 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001965 // We already have the app running, or are waiting for it to
1966 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001967 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001968 // If this is a new package in the process, add the package to the list
1969 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001970 return app;
1971 } else {
1972 // An application record is attached to a previous process,
1973 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001974 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001975 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 String hostingNameStr = hostingName != null
1980 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001981
1982 if (!isolated) {
1983 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1984 // If we are in the background, then check to see if this process
1985 // is bad. If so, we will just silently fail.
1986 if (mBadProcesses.get(info.processName, info.uid) != null) {
1987 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1988 + "/" + info.processName);
1989 return null;
1990 }
1991 } else {
1992 // When the user is explicitly starting a process, then clear its
1993 // crash count so that we won't make it bad until they see at
1994 // least one crash dialog again, and make the process good again
1995 // if it had been bad.
1996 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001997 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001998 mProcessCrashTimes.remove(info.processName, info.uid);
1999 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002000 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2001 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002002 info.processName);
2003 mBadProcesses.remove(info.processName, info.uid);
2004 if (app != null) {
2005 app.bad = false;
2006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008 }
2009 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002012 app = newProcessRecordLocked(null, info, processName, isolated);
2013 if (app == null) {
2014 Slog.w(TAG, "Failed making new process record for "
2015 + processName + "/" + info.uid + " isolated=" + isolated);
2016 return null;
2017 }
2018 mProcessNames.put(processName, app.uid, app);
2019 if (isolated) {
2020 mIsolatedProcesses.put(app.uid, app);
2021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 } else {
2023 // If this is a new package in the process, add the package to the list
2024 app.addPackage(info.packageName);
2025 }
2026
2027 // If the system is not ready yet, then hold off on starting this
2028 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002029 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002030 && !isAllowedWhileBooting(info)
2031 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 if (!mProcessesOnHold.contains(app)) {
2033 mProcessesOnHold.add(app);
2034 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002035 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 return app;
2037 }
2038
2039 startProcessLocked(app, hostingType, hostingNameStr);
2040 return (app.pid != 0) ? app : null;
2041 }
2042
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002043 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2044 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2045 }
2046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 private final void startProcessLocked(ProcessRecord app,
2048 String hostingType, String hostingNameStr) {
2049 if (app.pid > 0 && app.pid != MY_PID) {
2050 synchronized (mPidsSelfLocked) {
2051 mPidsSelfLocked.remove(app.pid);
2052 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2053 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002054 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
2056
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002057 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2058 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 mProcessesOnHold.remove(app);
2060
2061 updateCpuStats();
2062
2063 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2064 mProcDeaths[0] = 0;
2065
2066 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002067 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002070 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002071 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002072 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002073 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002074 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002075 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002076
2077 if (Environment.isExternalStorageEmulated()) {
2078 if (pm.checkPermission(
2079 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2080 app.info.packageName) == PERMISSION_GRANTED) {
2081 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2082 } else {
2083 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2084 }
2085 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002086 } catch (PackageManager.NameNotFoundException e) {
2087 Slog.w(TAG, "Unable to retrieve gids", e);
2088 }
Kenny Roote091f222012-09-11 15:01:26 -07002089
2090 /*
2091 * Add shared application GID so applications can share some
2092 * resources like shared libraries
2093 */
2094 if (permGids == null) {
2095 gids = new int[1];
2096 } else {
2097 gids = new int[permGids.length + 1];
2098 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2099 }
2100 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
2102 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2103 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2104 && mTopComponent != null
2105 && app.processName.equals(mTopComponent.getPackageName())) {
2106 uid = 0;
2107 }
2108 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2109 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2110 uid = 0;
2111 }
2112 }
2113 int debugFlags = 0;
2114 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2115 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002116 // Also turn on CheckJNI for debuggable apps. It's quite
2117 // awkward to turn on otherwise.
2118 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002120 // Run the app in safe mode if its manifest requests so or the
2121 // system is booted in safe mode.
2122 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2123 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002124 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2127 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2128 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002129 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2130 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 if ("1".equals(SystemProperties.get("debug.assert"))) {
2133 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2134 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002135
2136 // Start the process. It will either succeed and return a result containing
2137 // the PID of the new process, or else throw a RuntimeException.
2138 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002139 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002140 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2143 synchronized (bs) {
2144 if (bs.isOnBattery()) {
2145 app.batteryStats.incStartsLocked();
2146 }
2147 }
2148
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002149 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2150 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 app.processName, hostingType,
2152 hostingNameStr != null ? hostingNameStr : "");
2153
2154 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002155 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
2157
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002158 StringBuilder buf = mStringBuilder;
2159 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 buf.append("Start proc ");
2161 buf.append(app.processName);
2162 buf.append(" for ");
2163 buf.append(hostingType);
2164 if (hostingNameStr != null) {
2165 buf.append(" ");
2166 buf.append(hostingNameStr);
2167 }
2168 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002169 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 buf.append(" uid=");
2171 buf.append(uid);
2172 buf.append(" gids={");
2173 if (gids != null) {
2174 for (int gi=0; gi<gids.length; gi++) {
2175 if (gi != 0) buf.append(", ");
2176 buf.append(gids[gi]);
2177
2178 }
2179 }
2180 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002181 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002182 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002183 app.usingWrapper = startResult.usingWrapper;
2184 app.removed = false;
2185 synchronized (mPidsSelfLocked) {
2186 this.mPidsSelfLocked.put(startResult.pid, app);
2187 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2188 msg.obj = app;
2189 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2190 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 }
2192 } catch (RuntimeException e) {
2193 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002194 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002195 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
2197 }
2198
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002199 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 if (resumed) {
2201 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2202 } else {
2203 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2204 }
2205 }
2206
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002207 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002208 if (mHeadless) {
2209 // Added because none of the other calls to ensureBootCompleted seem to fire
2210 // when running headless.
2211 ensureBootCompleted();
2212 return false;
2213 }
2214
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002215 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2216 && mTopAction == null) {
2217 // We are running in factory test mode, but unable to find
2218 // the factory test app, so just sit around displaying the
2219 // error message and don't try to start anything.
2220 return false;
2221 }
2222 Intent intent = new Intent(
2223 mTopAction,
2224 mTopData != null ? Uri.parse(mTopData) : null);
2225 intent.setComponent(mTopComponent);
2226 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2227 intent.addCategory(Intent.CATEGORY_HOME);
2228 }
2229 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002230 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002231 if (aInfo != null) {
2232 intent.setComponent(new ComponentName(
2233 aInfo.applicationInfo.packageName, aInfo.name));
2234 // Don't do this if the home app is currently being
2235 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002236 aInfo = new ActivityInfo(aInfo);
2237 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002238 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2239 aInfo.applicationInfo.uid);
2240 if (app == null || app.instrumentationClass == null) {
2241 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002242 mMainStack.startActivityLocked(null, intent, null, aInfo,
2243 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002244 }
2245 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002246
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002247 return true;
2248 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002249
Amith Yamasani259d5e52012-08-31 15:11:01 -07002250 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2251 ActivityInfo ai = null;
2252 ComponentName comp = intent.getComponent();
2253 try {
2254 if (comp != null) {
2255 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2256 } else {
2257 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2258 intent,
2259 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2260 flags, userId);
2261
2262 if (info != null) {
2263 ai = info.activityInfo;
2264 }
2265 }
2266 } catch (RemoteException e) {
2267 // ignore
2268 }
2269
2270 return ai;
2271 }
2272
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002273 /**
2274 * Starts the "new version setup screen" if appropriate.
2275 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002276 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002277 // Only do this once per boot.
2278 if (mCheckedForSetup) {
2279 return;
2280 }
2281
2282 // We will show this screen if the current one is a different
2283 // version than the last one shown, and we are not running in
2284 // low-level factory test mode.
2285 final ContentResolver resolver = mContext.getContentResolver();
2286 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002287 Settings.Global.getInt(resolver,
2288 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002289 mCheckedForSetup = true;
2290
2291 // See if we should be showing the platform update setup UI.
2292 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2293 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2294 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2295
2296 // We don't allow third party apps to replace this.
2297 ResolveInfo ri = null;
2298 for (int i=0; ris != null && i<ris.size(); i++) {
2299 if ((ris.get(i).activityInfo.applicationInfo.flags
2300 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2301 ri = ris.get(i);
2302 break;
2303 }
2304 }
2305
2306 if (ri != null) {
2307 String vers = ri.activityInfo.metaData != null
2308 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2309 : null;
2310 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2311 vers = ri.activityInfo.applicationInfo.metaData.getString(
2312 Intent.METADATA_SETUP_VERSION);
2313 }
2314 String lastVers = Settings.Secure.getString(
2315 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2316 if (vers != null && !vers.equals(lastVers)) {
2317 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2318 intent.setComponent(new ComponentName(
2319 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002320 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2321 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002322 }
2323 }
2324 }
2325 }
2326
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002327 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002328 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002329 }
2330
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002331 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002332 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002333 throw new SecurityException("Isolated process not allowed to call " + caller);
2334 }
2335 }
2336
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002337 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002338 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002339 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002340 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2341 }
2342 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002343
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002344 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002345 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2346 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002347 synchronized (this) {
2348 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2349 }
2350 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002351
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002352 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002353 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002354 synchronized (this) {
2355 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2356 }
2357 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002358
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002359 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002360 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2361 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002362 synchronized (this) {
2363 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002364 }
2365 }
2366
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002367 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002368 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002369 synchronized (this) {
2370 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2371 }
2372 }
2373
2374 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002375 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2376 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002377 synchronized (this) {
2378 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2379 }
2380 }
2381
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002382 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002383 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002384 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002387 private void dispatchProcessesChanged() {
2388 int N;
2389 synchronized (this) {
2390 N = mPendingProcessChanges.size();
2391 if (mActiveProcessChanges.length < N) {
2392 mActiveProcessChanges = new ProcessChangeItem[N];
2393 }
2394 mPendingProcessChanges.toArray(mActiveProcessChanges);
2395 mAvailProcessChanges.addAll(mPendingProcessChanges);
2396 mPendingProcessChanges.clear();
2397 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2398 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002399 int i = mProcessObservers.beginBroadcast();
2400 while (i > 0) {
2401 i--;
2402 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2403 if (observer != null) {
2404 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002405 for (int j=0; j<N; j++) {
2406 ProcessChangeItem item = mActiveProcessChanges[j];
2407 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2408 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2409 + item.pid + " uid=" + item.uid + ": "
2410 + item.foregroundActivities);
2411 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2412 item.foregroundActivities);
2413 }
2414 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2415 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2416 + item.pid + " uid=" + item.uid + ": " + item.importance);
2417 observer.onImportanceChanged(item.pid, item.uid,
2418 item.importance);
2419 }
2420 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002421 } catch (RemoteException e) {
2422 }
2423 }
2424 }
2425 mProcessObservers.finishBroadcast();
2426 }
2427
2428 private void dispatchProcessDied(int pid, int uid) {
2429 int i = mProcessObservers.beginBroadcast();
2430 while (i > 0) {
2431 i--;
2432 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2433 if (observer != null) {
2434 try {
2435 observer.onProcessDied(pid, uid);
2436 } catch (RemoteException e) {
2437 }
2438 }
2439 }
2440 mProcessObservers.finishBroadcast();
2441 }
2442
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002443 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002444 final int N = mPendingActivityLaunches.size();
2445 if (N <= 0) {
2446 return;
2447 }
2448 for (int i=0; i<N; i++) {
2449 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002450 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002451 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002452 }
2453 mPendingActivityLaunches.clear();
2454 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002455
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002456 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002457 Intent intent, String resolvedType, IBinder resultTo,
2458 String resultWho, int requestCode, int startFlags,
2459 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002460 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002461 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002462 }
2463
2464 public final int startActivityAsUser(IApplicationThread caller,
2465 Intent intent, String resolvedType, IBinder resultTo,
2466 String resultWho, int requestCode, int startFlags,
2467 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002468 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002469 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002470 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002471 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002472 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2473 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002474 }
2475
2476 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 Intent intent, String resolvedType, IBinder resultTo,
2478 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002479 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002480 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002481 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002482 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002483 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002484 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002485 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002486 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002487 return res;
2488 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002489
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002490 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002491 Intent intent, String resolvedType, IBinder resultTo,
2492 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002493 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002494 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002495 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002496 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002497 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002498 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002499 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002500 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002501 }
2502
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002503 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002504 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002505 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002506 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002507 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002508 // Refuse possible leaked file descriptors
2509 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2510 throw new IllegalArgumentException("File descriptors passed in Intent");
2511 }
2512
2513 IIntentSender sender = intent.getTarget();
2514 if (!(sender instanceof PendingIntentRecord)) {
2515 throw new IllegalArgumentException("Bad PendingIntent object");
2516 }
2517
2518 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002519
2520 synchronized (this) {
2521 // If this is coming from the currently resumed activity, it is
2522 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002523 if (mMainStack.mResumedActivity != null
2524 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002525 Binder.getCallingUid()) {
2526 mAppSwitchesAllowedTime = 0;
2527 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002528 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002529 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2530 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002531 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002535 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 // Refuse possible leaked file descriptors
2537 if (intent != null && intent.hasFileDescriptors() == true) {
2538 throw new IllegalArgumentException("File descriptors passed in Intent");
2539 }
2540
2541 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002542 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2543 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002544 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 return false;
2546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 if (r.app == null || r.app.thread == null) {
2548 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002549 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 return false;
2551 }
2552 intent = new Intent(intent);
2553 // The caller is not allowed to change the data.
2554 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2555 // And we are resetting to find the next component...
2556 intent.setComponent(null);
2557
2558 ActivityInfo aInfo = null;
2559 try {
2560 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002561 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002563 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002564 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565
2566 // Look for the original activity in the list...
2567 final int N = resolves != null ? resolves.size() : 0;
2568 for (int i=0; i<N; i++) {
2569 ResolveInfo rInfo = resolves.get(i);
2570 if (rInfo.activityInfo.packageName.equals(r.packageName)
2571 && rInfo.activityInfo.name.equals(r.info.name)) {
2572 // We found the current one... the next matching is
2573 // after it.
2574 i++;
2575 if (i<N) {
2576 aInfo = resolves.get(i).activityInfo;
2577 }
2578 break;
2579 }
2580 }
2581 } catch (RemoteException e) {
2582 }
2583
2584 if (aInfo == null) {
2585 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002586 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 return false;
2588 }
2589
2590 intent.setComponent(new ComponentName(
2591 aInfo.applicationInfo.packageName, aInfo.name));
2592 intent.setFlags(intent.getFlags()&~(
2593 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2594 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2595 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2596 Intent.FLAG_ACTIVITY_NEW_TASK));
2597
2598 // Okay now we need to start the new activity, replacing the
2599 // currently running activity. This is a little tricky because
2600 // we want to start the new one as if the current one is finished,
2601 // but not finish the current one first so that there is no flicker.
2602 // And thus...
2603 final boolean wasFinishing = r.finishing;
2604 r.finishing = true;
2605
2606 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002607 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 final String resultWho = r.resultWho;
2609 final int requestCode = r.requestCode;
2610 r.resultTo = null;
2611 if (resultTo != null) {
2612 resultTo.removeResultsLocked(r, resultWho, requestCode);
2613 }
2614
2615 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002616 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002617 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2618 resultWho, requestCode, -1, r.launchedFromUid, 0,
2619 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 Binder.restoreCallingIdentity(origId);
2621
2622 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002623 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 return false;
2625 }
2626 return true;
2627 }
2628 }
2629
Dianne Hackborn41203752012-08-31 14:05:51 -07002630 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002632 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2633
Dianne Hackborn139748f2012-09-24 11:36:57 -07002634 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002635 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636
Amith Yamasani742a6712011-05-04 14:49:28 -07002637 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002638 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002639 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002640 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002641 }
2642
2643 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002644 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2645 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002646 enforceNotIsolatedCaller("startActivities");
Amith Yamasani95293862012-09-24 18:14:47 -07002647 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002648 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002649 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002650 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002651 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002652 }
2653
Dianne Hackborn41203752012-08-31 14:05:51 -07002654 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002655 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002656 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002657
Dianne Hackborn139748f2012-09-24 11:36:57 -07002658 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002659 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002660 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002661 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002662 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002665 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002667 // Quick case: check if the top-most recent task is the same.
2668 if (N > 0 && mRecentTasks.get(0) == task) {
2669 return;
2670 }
2671 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 for (int i=0; i<N; i++) {
2673 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002674 if (task.userId == tr.userId
2675 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2676 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 mRecentTasks.remove(i);
2678 i--;
2679 N--;
2680 if (task.intent == null) {
2681 // If the new recent task we are adding is not fully
2682 // specified, then replace it with the existing recent task.
2683 task = tr;
2684 }
2685 }
2686 }
2687 if (N >= MAX_RECENT_TASKS) {
2688 mRecentTasks.remove(N-1);
2689 }
2690 mRecentTasks.add(0, task);
2691 }
2692
2693 public void setRequestedOrientation(IBinder token,
2694 int requestedOrientation) {
2695 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002696 ActivityRecord r = mMainStack.isInStackLocked(token);
2697 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 return;
2699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002701 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002703 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002704 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 if (config != null) {
2706 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002707 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 }
2710 }
2711 Binder.restoreCallingIdentity(origId);
2712 }
2713 }
2714
2715 public int getRequestedOrientation(IBinder token) {
2716 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002717 ActivityRecord r = mMainStack.isInStackLocked(token);
2718 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2720 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002721 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 }
2723 }
2724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 /**
2726 * This is the internal entry point for handling Activity.finish().
2727 *
2728 * @param token The Binder token referencing the Activity we want to finish.
2729 * @param resultCode Result code, if any, from this Activity.
2730 * @param resultData Result data (Intent), if any, from this Activity.
2731 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002732 * @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 -08002733 */
2734 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2735 // Refuse possible leaked file descriptors
2736 if (resultData != null && resultData.hasFileDescriptors() == true) {
2737 throw new IllegalArgumentException("File descriptors passed in Intent");
2738 }
2739
2740 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002741 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002743 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 if (next != null) {
2745 // ask watcher if this is allowed
2746 boolean resumeOK = true;
2747 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002748 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002750 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 }
2752
2753 if (!resumeOK) {
2754 return false;
2755 }
2756 }
2757 }
2758 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002759 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002760 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 Binder.restoreCallingIdentity(origId);
2762 return res;
2763 }
2764 }
2765
Dianne Hackborn860755f2010-06-03 18:47:52 -07002766 public final void finishHeavyWeightApp() {
2767 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2768 != PackageManager.PERMISSION_GRANTED) {
2769 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2770 + Binder.getCallingPid()
2771 + ", uid=" + Binder.getCallingUid()
2772 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2773 Slog.w(TAG, msg);
2774 throw new SecurityException(msg);
2775 }
2776
2777 synchronized(this) {
2778 if (mHeavyWeightProcess == null) {
2779 return;
2780 }
2781
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002782 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002783 mHeavyWeightProcess.activities);
2784 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002785 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002786 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002787 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002788 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002789 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002790 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002791 }
2792 }
2793 }
2794
Dianne Hackborn41203752012-08-31 14:05:51 -07002795 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2796 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002797 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002798 }
2799 }
2800
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002801 public void crashApplication(int uid, int initialPid, String packageName,
2802 String message) {
2803 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2804 != PackageManager.PERMISSION_GRANTED) {
2805 String msg = "Permission Denial: crashApplication() from pid="
2806 + Binder.getCallingPid()
2807 + ", uid=" + Binder.getCallingUid()
2808 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2809 Slog.w(TAG, msg);
2810 throw new SecurityException(msg);
2811 }
2812
2813 synchronized(this) {
2814 ProcessRecord proc = null;
2815
2816 // Figure out which process to kill. We don't trust that initialPid
2817 // still has any relation to current pids, so must scan through the
2818 // list.
2819 synchronized (mPidsSelfLocked) {
2820 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2821 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002822 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002823 continue;
2824 }
2825 if (p.pid == initialPid) {
2826 proc = p;
2827 break;
2828 }
2829 for (String str : p.pkgList) {
2830 if (str.equals(packageName)) {
2831 proc = p;
2832 }
2833 }
2834 }
2835 }
2836
2837 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002838 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002839 + " initialPid=" + initialPid
2840 + " packageName=" + packageName);
2841 return;
2842 }
2843
2844 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002845 if (proc.pid == Process.myPid()) {
2846 Log.w(TAG, "crashApplication: trying to crash self!");
2847 return;
2848 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002849 long ident = Binder.clearCallingIdentity();
2850 try {
2851 proc.thread.scheduleCrash(message);
2852 } catch (RemoteException e) {
2853 }
2854 Binder.restoreCallingIdentity(ident);
2855 }
2856 }
2857 }
2858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 public final void finishSubActivity(IBinder token, String resultWho,
2860 int requestCode) {
2861 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002863 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 Binder.restoreCallingIdentity(origId);
2865 }
2866 }
2867
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002868 public boolean finishActivityAffinity(IBinder token) {
2869 synchronized(this) {
2870 final long origId = Binder.clearCallingIdentity();
2871 boolean res = mMainStack.finishActivityAffinityLocked(token);
2872 Binder.restoreCallingIdentity(origId);
2873 return res;
2874 }
2875 }
2876
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002877 public boolean willActivityBeVisible(IBinder token) {
2878 synchronized(this) {
2879 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002880 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2881 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002882 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002883 return true;
2884 }
2885 if (r.fullscreen && !r.finishing) {
2886 return false;
2887 }
2888 }
2889 return true;
2890 }
2891 }
2892
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002893 public void overridePendingTransition(IBinder token, String packageName,
2894 int enterAnim, int exitAnim) {
2895 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002896 ActivityRecord self = mMainStack.isInStackLocked(token);
2897 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002898 return;
2899 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002900
2901 final long origId = Binder.clearCallingIdentity();
2902
2903 if (self.state == ActivityState.RESUMED
2904 || self.state == ActivityState.PAUSING) {
2905 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002906 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002907 }
2908
2909 Binder.restoreCallingIdentity(origId);
2910 }
2911 }
2912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 * Main function for removing an existing process from the activity manager
2915 * as a result of that process going away. Clears out all connections
2916 * to the process.
2917 */
2918 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002919 boolean restarting, boolean allowRestart) {
2920 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002922 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
2924
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002925 if (mProfileProc == app) {
2926 clearProfilerLocked();
2927 }
2928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002930 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002931 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2932 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002933 mMainStack.mPausingActivity = null;
2934 }
2935 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2936 mMainStack.mLastPausedActivity = null;
2937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938
2939 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002940 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941
2942 app.activities.clear();
2943
2944 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002945 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 + " running instrumentation " + app.instrumentationClass);
2947 Bundle info = new Bundle();
2948 info.putString("shortMsg", "Process crashed.");
2949 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2950 }
2951
2952 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002953 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 // If there was nothing to resume, and we are not already
2955 // restarting this process, but there is a visible activity that
2956 // is hosted by the process... then make sure all visible
2957 // activities are running, taking care of restarting this
2958 // process.
2959 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002960 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 }
2962 }
2963 }
2964 }
2965
2966 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2967 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002969 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2970 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2972 return i;
2973 }
2974 }
2975 return -1;
2976 }
2977
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002978 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 IApplicationThread thread) {
2980 if (thread == null) {
2981 return null;
2982 }
2983
2984 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002985 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
2987
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002988 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 IApplicationThread thread) {
2990
2991 mProcDeaths[0]++;
2992
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002993 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2994 synchronized (stats) {
2995 stats.noteProcessDiedLocked(app.info.uid, pid);
2996 }
2997
Magnus Edlund7bb25812010-02-24 15:45:06 +01002998 // Clean up already done if the process has been re-started.
2999 if (app.pid == pid && app.thread != null &&
3000 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003001 if (!app.killedBackground) {
3002 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3003 + ") has died.");
3004 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003005 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003006 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 TAG, "Dying app: " + app + ", pid: " + pid
3008 + ", thread: " + thread.asBinder());
3009 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003010 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011
3012 if (doLowMem) {
3013 // If there are no longer any background processes running,
3014 // and the app that died was not running instrumentation,
3015 // then tell everyone we are now low on memory.
3016 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003017 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3018 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003019 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 haveBg = true;
3021 break;
3022 }
3023 }
3024
3025 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003026 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003027 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003028 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3029 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003030 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003031 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3032 // The low memory report is overriding any current
3033 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003034 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003035 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003036 rec.lastRequestedGc = 0;
3037 } else {
3038 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003040 rec.reportLowMemory = true;
3041 rec.lastLowMemory = now;
3042 mProcessesToGc.remove(rec);
3043 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 }
3045 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003046 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003047 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 }
3049 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003050 } else if (app.pid != pid) {
3051 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003052 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003053 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003054 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003055 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003056 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 + thread.asBinder());
3058 }
3059 }
3060
Dan Egnor42471dd2010-01-07 17:25:22 -08003061 /**
3062 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003063 * @param clearTraces causes the dump file to be erased prior to the new
3064 * traces being written, if true; when false, the new traces will be
3065 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003066 * @param firstPids of dalvik VM processes to dump stack traces for first
3067 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003068 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003069 * @return file containing stack traces, or null if no dump file is configured
3070 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003071 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003072 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003073 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3074 if (tracesPath == null || tracesPath.length() == 0) {
3075 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003077
3078 File tracesFile = new File(tracesPath);
3079 try {
3080 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003081 if (!tracesDir.exists()) {
3082 tracesFile.mkdirs();
3083 if (!SELinux.restorecon(tracesDir)) {
3084 return null;
3085 }
3086 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003087 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3088
Christopher Tate6ee412d2010-05-28 12:01:56 -07003089 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003090 tracesFile.createNewFile();
3091 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3092 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003093 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003094 return null;
3095 }
3096
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003097 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003098 return tracesFile;
3099 }
3100
3101 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003102 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003103 // Use a FileObserver to detect when traces finish writing.
3104 // The order of traces is considered important to maintain for legibility.
3105 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3106 public synchronized void onEvent(int event, String path) { notify(); }
3107 };
3108
3109 try {
3110 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003111
3112 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003113 if (firstPids != null) {
3114 try {
3115 int num = firstPids.size();
3116 for (int i = 0; i < num; i++) {
3117 synchronized (observer) {
3118 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3119 observer.wait(200); // Wait for write-close, give up after 200msec
3120 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003121 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003122 } catch (InterruptedException e) {
3123 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003124 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003125 }
3126
3127 // Next measure CPU usage.
3128 if (processStats != null) {
3129 processStats.init();
3130 System.gc();
3131 processStats.update();
3132 try {
3133 synchronized (processStats) {
3134 processStats.wait(500); // measure over 1/2 second.
3135 }
3136 } catch (InterruptedException e) {
3137 }
3138 processStats.update();
3139
3140 // We'll take the stack crawls of just the top apps using CPU.
3141 final int N = processStats.countWorkingStats();
3142 int numProcs = 0;
3143 for (int i=0; i<N && numProcs<5; i++) {
3144 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3145 if (lastPids.indexOfKey(stats.pid) >= 0) {
3146 numProcs++;
3147 try {
3148 synchronized (observer) {
3149 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3150 observer.wait(200); // Wait for write-close, give up after 200msec
3151 }
3152 } catch (InterruptedException e) {
3153 Log.wtf(TAG, e);
3154 }
3155
3156 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003157 }
3158 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003159
Dan Egnor42471dd2010-01-07 17:25:22 -08003160 } finally {
3161 observer.stopWatching();
3162 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003163
3164 if (nativeProcs != null) {
3165 int[] pids = Process.getPidsForCommands(nativeProcs);
3166 if (pids != null) {
3167 for (int pid : pids) {
3168 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3169 }
3170 }
3171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 }
3173
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003174 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003175 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003176 return;
3177 }
3178 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3179 if (tracesPath == null || tracesPath.length() == 0) {
3180 return;
3181 }
3182
3183 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3184 StrictMode.allowThreadDiskWrites();
3185 try {
3186 final File tracesFile = new File(tracesPath);
3187 final File tracesDir = tracesFile.getParentFile();
3188 final File tracesTmp = new File(tracesDir, "__tmp__");
3189 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003190 if (!tracesDir.exists()) {
3191 tracesFile.mkdirs();
3192 if (!SELinux.restorecon(tracesDir.getPath())) {
3193 return;
3194 }
3195 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003196 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3197
3198 if (tracesFile.exists()) {
3199 tracesTmp.delete();
3200 tracesFile.renameTo(tracesTmp);
3201 }
3202 StringBuilder sb = new StringBuilder();
3203 Time tobj = new Time();
3204 tobj.set(System.currentTimeMillis());
3205 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3206 sb.append(": ");
3207 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3208 sb.append(" since ");
3209 sb.append(msg);
3210 FileOutputStream fos = new FileOutputStream(tracesFile);
3211 fos.write(sb.toString().getBytes());
3212 if (app == null) {
3213 fos.write("\n*** No application process!".getBytes());
3214 }
3215 fos.close();
3216 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3217 } catch (IOException e) {
3218 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3219 return;
3220 }
3221
3222 if (app != null) {
3223 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3224 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003225 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003226 }
3227
3228 File lastTracesFile = null;
3229 File curTracesFile = null;
3230 for (int i=9; i>=0; i--) {
3231 String name = String.format("slow%02d.txt", i);
3232 curTracesFile = new File(tracesDir, name);
3233 if (curTracesFile.exists()) {
3234 if (lastTracesFile != null) {
3235 curTracesFile.renameTo(lastTracesFile);
3236 } else {
3237 curTracesFile.delete();
3238 }
3239 }
3240 lastTracesFile = curTracesFile;
3241 }
3242 tracesFile.renameTo(curTracesFile);
3243 if (tracesTmp.exists()) {
3244 tracesTmp.renameTo(tracesFile);
3245 }
3246 } finally {
3247 StrictMode.setThreadPolicy(oldPolicy);
3248 }
3249 }
3250
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003251 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003252 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003253 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3254 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3255
Dianne Hackborn287952c2010-09-22 22:34:31 -07003256 if (mController != null) {
3257 try {
3258 // 0 == continue, -1 = kill process immediately
3259 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3260 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3261 } catch (RemoteException e) {
3262 mController = null;
3263 }
3264 }
3265
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003266 long anrTime = SystemClock.uptimeMillis();
3267 if (MONITOR_CPU_USAGE) {
3268 updateCpuStatsNow();
3269 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003270
3271 synchronized (this) {
3272 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3273 if (mShuttingDown) {
3274 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3275 return;
3276 } else if (app.notResponding) {
3277 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3278 return;
3279 } else if (app.crashing) {
3280 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3281 return;
3282 }
3283
3284 // In case we come through here for the same app before completing
3285 // this one, mark as anring now so we will bail out.
3286 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003287
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003288 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003289 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3290 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003291
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003292 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003293 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003294
3295 int parentPid = app.pid;
3296 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003297 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003298
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003299 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003300
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003301 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3302 ProcessRecord r = mLruProcesses.get(i);
3303 if (r != null && r.thread != null) {
3304 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003305 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3306 if (r.persistent) {
3307 firstPids.add(pid);
3308 } else {
3309 lastPids.put(pid, Boolean.TRUE);
3310 }
3311 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 }
3314 }
3315
Dan Egnor42471dd2010-01-07 17:25:22 -08003316 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003317 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003318 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003319 info.append("ANR in ").append(app.processName);
3320 if (activity != null && activity.shortComponentName != null) {
3321 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003322 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003323 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003325 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003327 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003328 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330
Dianne Hackborn287952c2010-09-22 22:34:31 -07003331 final ProcessStats processStats = new ProcessStats(true);
3332
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003333 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003334
Dan Egnor42471dd2010-01-07 17:25:22 -08003335 String cpuInfo = null;
3336 if (MONITOR_CPU_USAGE) {
3337 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003338 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003339 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003340 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003341 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003342 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 }
3344
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003345 info.append(processStats.printCurrentState(anrTime));
3346
Joe Onorato8a9b2202010-02-26 18:56:32 -08003347 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003348 if (tracesFile == null) {
3349 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3350 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3351 }
3352
Jeff Sharkeya353d262011-10-28 11:12:06 -07003353 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3354 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003355
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003356 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003358 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3359 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003361 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3362 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
3364 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003365 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 }
3367 }
3368
Dan Egnor42471dd2010-01-07 17:25:22 -08003369 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3370 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3371 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003372
3373 synchronized (this) {
3374 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003375 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003376 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003377 app.processName, app.setAdj, "background ANR");
3378 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003379 return;
3380 }
3381
3382 // Set the app's notResponding state, and look up the errorReportReceiver
3383 makeAppNotRespondingLocked(app,
3384 activity != null ? activity.shortComponentName : null,
3385 annotation != null ? "ANR " + annotation : "ANR",
3386 info.toString());
3387
3388 // Bring up the infamous App Not Responding dialog
3389 Message msg = Message.obtain();
3390 HashMap map = new HashMap();
3391 msg.what = SHOW_NOT_RESPONDING_MSG;
3392 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003393 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003394 map.put("app", app);
3395 if (activity != null) {
3396 map.put("activity", activity);
3397 }
3398
3399 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 }
3402
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003403 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3404 if (!mLaunchWarningShown) {
3405 mLaunchWarningShown = true;
3406 mHandler.post(new Runnable() {
3407 @Override
3408 public void run() {
3409 synchronized (ActivityManagerService.this) {
3410 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3411 d.show();
3412 mHandler.postDelayed(new Runnable() {
3413 @Override
3414 public void run() {
3415 synchronized (ActivityManagerService.this) {
3416 d.dismiss();
3417 mLaunchWarningShown = false;
3418 }
3419 }
3420 }, 4000);
3421 }
3422 }
3423 });
3424 }
3425 }
3426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003428 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003429 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 int uid = Binder.getCallingUid();
3431 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003432 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003433 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 long callingId = Binder.clearCallingIdentity();
3435 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003436 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 int pkgUid = -1;
3438 synchronized(this) {
3439 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003440 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 } catch (RemoteException e) {
3442 }
3443 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003444 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 return false;
3446 }
3447 if (uid == pkgUid || checkComponentPermission(
3448 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003449 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003451 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 } else {
3453 throw new SecurityException(pid+" does not have permission:"+
3454 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3455 "for process:"+packageName);
3456 }
3457 }
3458
3459 try {
3460 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003461 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3463 Uri.fromParts("package", packageName, null));
3464 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003465 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003466 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 } catch (RemoteException e) {
3468 }
3469 } finally {
3470 Binder.restoreCallingIdentity(callingId);
3471 }
3472 return true;
3473 }
3474
Dianne Hackborn1676c852012-09-10 14:52:30 -07003475 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003476 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3477 != PackageManager.PERMISSION_GRANTED &&
3478 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3479 != PackageManager.PERMISSION_GRANTED) {
3480 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 + Binder.getCallingPid()
3482 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003483 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003484 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 throw new SecurityException(msg);
3486 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003487
Dianne Hackborn139748f2012-09-24 11:36:57 -07003488 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003489 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 long callingId = Binder.clearCallingIdentity();
3491 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003492 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003494 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003496 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 } catch (RemoteException e) {
3498 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003499 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003500 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 return;
3502 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003503 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003504 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3505 }
3506 } finally {
3507 Binder.restoreCallingIdentity(callingId);
3508 }
3509 }
3510
3511 public void killAllBackgroundProcesses() {
3512 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3513 != PackageManager.PERMISSION_GRANTED) {
3514 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3515 + Binder.getCallingPid()
3516 + ", uid=" + Binder.getCallingUid()
3517 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3518 Slog.w(TAG, msg);
3519 throw new SecurityException(msg);
3520 }
3521
3522 long callingId = Binder.clearCallingIdentity();
3523 try {
3524 synchronized(this) {
3525 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3526 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3527 final int NA = apps.size();
3528 for (int ia=0; ia<NA; ia++) {
3529 ProcessRecord app = apps.valueAt(ia);
3530 if (app.persistent) {
3531 // we don't kill persistent processes
3532 continue;
3533 }
3534 if (app.removed) {
3535 procs.add(app);
3536 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3537 app.removed = true;
3538 procs.add(app);
3539 }
3540 }
3541 }
3542
3543 int N = procs.size();
3544 for (int i=0; i<N; i++) {
3545 removeProcessLocked(procs.get(i), false, true, "kill all background");
3546 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003547 }
3548 } finally {
3549 Binder.restoreCallingIdentity(callingId);
3550 }
3551 }
3552
Dianne Hackborn1676c852012-09-10 14:52:30 -07003553 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003554 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3555 != PackageManager.PERMISSION_GRANTED) {
3556 String msg = "Permission Denial: forceStopPackage() from pid="
3557 + Binder.getCallingPid()
3558 + ", uid=" + Binder.getCallingUid()
3559 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003560 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003561 throw new SecurityException(msg);
3562 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003563 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003564 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003565 long callingId = Binder.clearCallingIdentity();
3566 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003567 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003568 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003569 int[] users = userId == UserHandle.USER_ALL
3570 ? getUsersLocked() : new int[] { userId };
3571 for (int user : users) {
3572 int pkgUid = -1;
3573 try {
3574 pkgUid = pm.getPackageUid(packageName, user);
3575 } catch (RemoteException e) {
3576 }
3577 if (pkgUid == -1) {
3578 Slog.w(TAG, "Invalid packageName: " + packageName);
3579 continue;
3580 }
3581 try {
3582 pm.setPackageStoppedState(packageName, true, user);
3583 } catch (RemoteException e) {
3584 } catch (IllegalArgumentException e) {
3585 Slog.w(TAG, "Failed trying to unstop package "
3586 + packageName + ": " + e);
3587 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003588 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003589 forceStopPackageLocked(packageName, pkgUid);
3590 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 }
3593 } finally {
3594 Binder.restoreCallingIdentity(callingId);
3595 }
3596 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003597
3598 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003599 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003600 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003601 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003602 if (pkg == null) {
3603 return;
3604 }
3605 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003606 if (appid < 0) {
3607 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003608 return;
3609 }
3610 int callerUid = Binder.getCallingUid();
3611 // Only the system server can kill an application
3612 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003613 // Post an aysnc message to kill the application
3614 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003615 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003616 msg.arg2 = 0;
3617 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003618 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003619 } else {
3620 throw new SecurityException(callerUid + " cannot kill pkg: " +
3621 pkg);
3622 }
3623 }
3624
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003625 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003626 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003627
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003628 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003629 final int uid = Binder.getCallingUid();
3630 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003631 try {
3632 synchronized (this) {
3633 // Only allow this from foreground processes, so that background
3634 // applications can't abuse it to prevent system UI from being shown.
3635 if (uid >= Process.FIRST_APPLICATION_UID) {
3636 ProcessRecord proc;
3637 synchronized (mPidsSelfLocked) {
3638 proc = mPidsSelfLocked.get(pid);
3639 }
3640 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3641 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3642 + " from background process " + proc);
3643 return;
3644 }
3645 }
3646 closeSystemDialogsLocked(reason);
3647 }
3648 } finally {
3649 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003650 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003651 }
3652
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003653 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003654 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003655 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3656 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003657 if (reason != null) {
3658 intent.putExtra("reason", reason);
3659 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003660 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003661
Dianne Hackborne302a162012-05-15 14:58:32 -07003662 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3663 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003664 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003665 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003666 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003667 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003668 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003669
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003670 broadcastIntentLocked(null, null, intent, null,
3671 null, 0, null, null, null, false, false, -1,
3672 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003673 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003674
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003675 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003676 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003677 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003678 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3679 for (int i=pids.length-1; i>=0; i--) {
3680 infos[i] = new Debug.MemoryInfo();
3681 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003682 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003683 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003684 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003685
Dianne Hackbornb437e092011-08-05 17:50:29 -07003686 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003687 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003688 long[] pss = new long[pids.length];
3689 for (int i=pids.length-1; i>=0; i--) {
3690 pss[i] = Debug.getPss(pids[i]);
3691 }
3692 return pss;
3693 }
3694
Christopher Tate5e1ab332009-09-01 20:32:49 -07003695 public void killApplicationProcess(String processName, int uid) {
3696 if (processName == null) {
3697 return;
3698 }
3699
3700 int callerUid = Binder.getCallingUid();
3701 // Only the system server can kill an application
3702 if (callerUid == Process.SYSTEM_UID) {
3703 synchronized (this) {
3704 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003705 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003706 try {
3707 app.thread.scheduleSuicide();
3708 } catch (RemoteException e) {
3709 // If the other end already died, then our work here is done.
3710 }
3711 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003712 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003713 + processName + " / " + uid);
3714 }
3715 }
3716 } else {
3717 throw new SecurityException(callerUid + " cannot kill app process: " +
3718 processName);
3719 }
3720 }
3721
Dianne Hackborn03abb812010-01-04 18:43:19 -08003722 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003723 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3724 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3726 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003727 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003728 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3729 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003732 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 broadcastIntentLocked(null, null, intent,
3734 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003735 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003736 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003738
3739 private void forceStopUserLocked(int userId) {
3740 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3741 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003742 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3743 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003744 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3745 broadcastIntentLocked(null, null, intent,
3746 null, null, 0, null, null, null,
3747 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003748 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003749 }
3750
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003751 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003752 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3753 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003754 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755
Dianne Hackborn03abb812010-01-04 18:43:19 -08003756 // Remove all processes this package may have touched: all with the
3757 // same UID (except for the system or root user), and all whose name
3758 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003759 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003760 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3761 final int NA = apps.size();
3762 for (int ia=0; ia<NA; ia++) {
3763 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003764 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003765 // we don't kill persistent processes
3766 continue;
3767 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003768 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003769 if (doit) {
3770 procs.add(app);
3771 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003772 continue;
3773 }
3774
3775 // Skip process if it doesn't meet our oom adj requirement.
3776 if (app.setAdj < minOomAdj) {
3777 continue;
3778 }
3779
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003780 // If no package is specified, we call all processes under the
3781 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003782 if (packageName == null) {
3783 if (app.userId != userId) {
3784 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003785 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003786 // Package has been specified, we want to hit all processes
3787 // that match it. We need to qualify this by the processes
3788 // that are running under the specified app and user ID.
3789 } else {
3790 if (UserHandle.getAppId(app.uid) != appId) {
3791 continue;
3792 }
3793 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3794 continue;
3795 }
3796 if (!app.pkgList.contains(packageName)) {
3797 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003798 }
3799 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003800
3801 // Process has passed all conditions, kill it!
3802 if (!doit) {
3803 return true;
3804 }
3805 app.removed = true;
3806 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003807 }
3808 }
3809
3810 int N = procs.size();
3811 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003812 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003813 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003814 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003815 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003816
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003817 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003818 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003819 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003820 int i;
3821 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003823 if (userId == UserHandle.USER_ALL && name == null) {
3824 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3825 }
3826
3827 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003829 appId = UserHandle.getAppId(
3830 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 } catch (RemoteException e) {
3832 }
3833 }
3834
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003835 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003836 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003837 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3838 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003839 } else {
3840 Slog.i(TAG, "Force stopping user " + userId);
3841 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003842
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003843 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3844 while (badApps.hasNext()) {
3845 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003846 for (i=ba.size()-1; i>=0; i--) {
3847 boolean remove = false;
3848 final int entUid = ba.keyAt(i);
3849 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003850 if (userId == UserHandle.USER_ALL) {
3851 if (UserHandle.getAppId(entUid) == appId) {
3852 remove = true;
3853 }
3854 } else {
3855 if (entUid == UserHandle.getUid(userId, appId)) {
3856 remove = true;
3857 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003858 }
3859 } else if (UserHandle.getUserId(entUid) == userId) {
3860 remove = true;
3861 }
3862 if (remove) {
3863 ba.removeAt(i);
3864 }
3865 }
3866 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003867 badApps.remove();
3868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 }
3870 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003871
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003872 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3873 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003874 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003876 TaskRecord lastTask = null;
3877 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003878 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003879 final boolean samePackage = r.packageName.equals(name)
3880 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003881 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003882 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003883 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003884 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003885 if (r.finishing) {
3886 // If this activity is just finishing, then it is not
3887 // interesting as far as something to stop.
3888 continue;
3889 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003890 return true;
3891 }
3892 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003893 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003894 if (samePackage) {
3895 if (r.app != null) {
3896 r.app.removed = true;
3897 }
3898 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003900 lastTask = r.task;
3901 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003902 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003903 i--;
3904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 }
3906 }
3907
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003908 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3909 if (!doit) {
3910 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003912 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003914
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003915 if (name == null) {
3916 // Remove all sticky broadcasts from this user.
3917 mStickyBroadcasts.remove(userId);
3918 }
3919
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003920 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003921 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3922 userId, providers)) {
3923 if (!doit) {
3924 return true;
3925 }
3926 didSomething = true;
3927 }
3928 N = providers.size();
3929 for (i=0; i<N; i++) {
3930 removeDyingProviderLocked(null, providers.get(i), true);
3931 }
3932
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003933 if (name == null) {
3934 // Remove pending intents. For now we only do this when force
3935 // stopping users, because we have some problems when doing this
3936 // for packages -- app widgets are not currently cleaned up for
3937 // such packages, so they can be left with bad pending intents.
3938 if (mIntentSenderRecords.size() > 0) {
3939 Iterator<WeakReference<PendingIntentRecord>> it
3940 = mIntentSenderRecords.values().iterator();
3941 while (it.hasNext()) {
3942 WeakReference<PendingIntentRecord> wpir = it.next();
3943 if (wpir == null) {
3944 it.remove();
3945 continue;
3946 }
3947 PendingIntentRecord pir = wpir.get();
3948 if (pir == null) {
3949 it.remove();
3950 continue;
3951 }
3952 if (name == null) {
3953 // Stopping user, remove all objects for the user.
3954 if (pir.key.userId != userId) {
3955 // Not the same user, skip it.
3956 continue;
3957 }
3958 } else {
3959 if (UserHandle.getAppId(pir.uid) != appId) {
3960 // Different app id, skip it.
3961 continue;
3962 }
3963 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3964 // Different user, skip it.
3965 continue;
3966 }
3967 if (!pir.key.packageName.equals(name)) {
3968 // Different package, skip it.
3969 continue;
3970 }
3971 }
3972 if (!doit) {
3973 return true;
3974 }
3975 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003976 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003977 pir.canceled = true;
3978 if (pir.key.activity != null) {
3979 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003980 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003981 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003982 }
3983 }
3984
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003985 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003986 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003987 AttributeCache ac = AttributeCache.instance();
3988 if (ac != null) {
3989 ac.removePackage(name);
3990 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003991 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003992 if (mBooted) {
3993 mMainStack.resumeTopActivityLocked(null);
3994 mMainStack.scheduleIdleLocked();
3995 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003996 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003997
3998 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
4000
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004001 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004002 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004004 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004005 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004006 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 + "/" + uid + ")");
4008
4009 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004010 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004011 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004012 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4013 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004014 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 boolean needRestart = false;
4017 if (app.pid > 0 && app.pid != MY_PID) {
4018 int pid = app.pid;
4019 synchronized (mPidsSelfLocked) {
4020 mPidsSelfLocked.remove(pid);
4021 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4022 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004023 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004024 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004025 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004026 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004028 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004030 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 } else {
4032 needRestart = true;
4033 }
4034 }
4035 } else {
4036 mRemovedProcesses.add(app);
4037 }
4038
4039 return needRestart;
4040 }
4041
4042 private final void processStartTimedOutLocked(ProcessRecord app) {
4043 final int pid = app.pid;
4044 boolean gone = false;
4045 synchronized (mPidsSelfLocked) {
4046 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4047 if (knownApp != null && knownApp.thread == null) {
4048 mPidsSelfLocked.remove(pid);
4049 gone = true;
4050 }
4051 }
4052
4053 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004054 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004055 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4056 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004057 mProcessNames.remove(app.processName, app.uid);
4058 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004059 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004060 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4061 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004062 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004063 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004064 // Take care of any launching providers waiting for this process.
4065 checkAppInLaunchingProvidersLocked(app, true);
4066 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004067 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004068 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004069 app.processName, app.setAdj, "start timeout");
4070 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004071 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004072 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004073 try {
4074 IBackupManager bm = IBackupManager.Stub.asInterface(
4075 ServiceManager.getService(Context.BACKUP_SERVICE));
4076 bm.agentDisconnected(app.info.packageName);
4077 } catch (RemoteException e) {
4078 // Can't happen; the backup manager is local
4079 }
4080 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004081 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004082 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004083 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004086 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 }
4088 }
4089
4090 private final boolean attachApplicationLocked(IApplicationThread thread,
4091 int pid) {
4092
4093 // Find the application record that is being attached... either via
4094 // the pid if we are running in multiple processes, or just pull the
4095 // next app record if we are emulating process with anonymous threads.
4096 ProcessRecord app;
4097 if (pid != MY_PID && pid >= 0) {
4098 synchronized (mPidsSelfLocked) {
4099 app = mPidsSelfLocked.get(pid);
4100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 } else {
4102 app = null;
4103 }
4104
4105 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004106 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004108 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004110 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 } else {
4112 try {
4113 thread.scheduleExit();
4114 } catch (Exception e) {
4115 // Ignore exceptions.
4116 }
4117 }
4118 return false;
4119 }
4120
4121 // If this application record is still attached to a previous
4122 // process, clean it up now.
4123 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004124 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 }
4126
4127 // Tell the process all about itself.
4128
Joe Onorato8a9b2202010-02-26 18:56:32 -08004129 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 TAG, "Binding process pid " + pid + " to record " + app);
4131
4132 String processName = app.processName;
4133 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004134 AppDeathRecipient adr = new AppDeathRecipient(
4135 app, pid, thread);
4136 thread.asBinder().linkToDeath(adr, 0);
4137 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 } catch (RemoteException e) {
4139 app.resetPackageList();
4140 startProcessLocked(app, "link fail", processName);
4141 return false;
4142 }
4143
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004144 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145
4146 app.thread = thread;
4147 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004148 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4149 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 app.forcingToForeground = null;
4151 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004152 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 app.debugging = false;
4154
4155 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4156
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004157 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004158 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004160 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004161 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004162 }
4163
Joe Onorato8a9b2202010-02-26 18:56:32 -08004164 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 TAG, "New app record " + app
4166 + " thread=" + thread.asBinder() + " pid=" + pid);
4167 try {
4168 int testMode = IApplicationThread.DEBUG_OFF;
4169 if (mDebugApp != null && mDebugApp.equals(processName)) {
4170 testMode = mWaitForDebugger
4171 ? IApplicationThread.DEBUG_WAIT
4172 : IApplicationThread.DEBUG_ON;
4173 app.debugging = true;
4174 if (mDebugTransient) {
4175 mDebugApp = mOrigDebugApp;
4176 mWaitForDebugger = mOrigWaitForDebugger;
4177 }
4178 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004179 String profileFile = app.instrumentationProfileFile;
4180 ParcelFileDescriptor profileFd = null;
4181 boolean profileAutoStop = false;
4182 if (mProfileApp != null && mProfileApp.equals(processName)) {
4183 mProfileProc = app;
4184 profileFile = mProfileFile;
4185 profileFd = mProfileFd;
4186 profileAutoStop = mAutoStopProfiler;
4187 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004188 boolean enableOpenGlTrace = false;
4189 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4190 enableOpenGlTrace = true;
4191 mOpenGlTraceApp = null;
4192 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004193
Christopher Tate181fafa2009-05-14 11:12:14 -07004194 // If the app is being launched for restore or full backup, set it up specially
4195 boolean isRestrictedBackupMode = false;
4196 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4197 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004198 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004199 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4200 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004201
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004202 ensurePackageDexOpt(app.instrumentationInfo != null
4203 ? app.instrumentationInfo.packageName
4204 : app.info.packageName);
4205 if (app.instrumentationClass != null) {
4206 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004207 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004208 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004209 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004210 ApplicationInfo appInfo = app.instrumentationInfo != null
4211 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004212 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004213 if (profileFd != null) {
4214 profileFd = profileFd.dup();
4215 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004216 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004217 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004218 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4219 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004220 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004221 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004222 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004223 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 } catch (Exception e) {
4225 // todo: Yikes! What should we do? For now we will try to
4226 // start another process, but that could easily get us in
4227 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004228 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229
4230 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004231 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 startProcessLocked(app, "bind fail", processName);
4233 return false;
4234 }
4235
4236 // Remove this record from the list of starting applications.
4237 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004238 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4239 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 mProcessesOnHold.remove(app);
4241
4242 boolean badApp = false;
4243 boolean didSomething = false;
4244
4245 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004246 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004247 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004248 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 && processName.equals(hr.processName)) {
4250 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004251 if (mHeadless) {
4252 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4253 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 didSomething = true;
4255 }
4256 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004257 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 + hr.intent.getComponent().flattenToShortString(), e);
4259 badApp = true;
4260 }
4261 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004262 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263 }
4264 }
4265
4266 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004267 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004269 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 badApp = true;
4272 }
4273 }
4274
Christopher Tatef46723b2012-01-26 14:19:24 -08004275 // Check if a next-broadcast receiver is in this process...
4276 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004278 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004280 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 }
4283 }
4284
Christopher Tate181fafa2009-05-14 11:12:14 -07004285 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004286 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004287 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004288 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004289 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004290 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4291 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4292 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004293 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004294 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004295 e.printStackTrace();
4296 }
4297 }
4298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 if (badApp) {
4300 // todo: Also need to kill application to deal with all
4301 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004302 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 return false;
4304 }
4305
4306 if (!didSomething) {
4307 updateOomAdjLocked();
4308 }
4309
4310 return true;
4311 }
4312
4313 public final void attachApplication(IApplicationThread thread) {
4314 synchronized (this) {
4315 int callingPid = Binder.getCallingPid();
4316 final long origId = Binder.clearCallingIdentity();
4317 attachApplicationLocked(thread, callingPid);
4318 Binder.restoreCallingIdentity(origId);
4319 }
4320 }
4321
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004322 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004324 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4325 if (stopProfiling) {
4326 synchronized (this) {
4327 if (mProfileProc == r.app) {
4328 if (mProfileFd != null) {
4329 try {
4330 mProfileFd.close();
4331 } catch (IOException e) {
4332 }
4333 clearProfilerLocked();
4334 }
4335 }
4336 }
4337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 Binder.restoreCallingIdentity(origId);
4339 }
4340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004342 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004343 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004345
4346 synchronized (this) {
4347 updateEventDispatchingLocked();
4348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 }
4350
Dianne Hackborn661cd522011-08-22 00:26:20 -07004351 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004352 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004353 mWindowManager.showBootMessage(msg, always);
4354 }
4355
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004356 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004357 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004358 final long token = Binder.clearCallingIdentity();
4359 try {
4360 synchronized (this) {
4361 if (mLockScreenShown) {
4362 mLockScreenShown = false;
4363 comeOutOfSleepIfNeededLocked();
4364 }
4365 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004366 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004367 } finally {
4368 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004369 }
4370 }
4371
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004372 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004373 IntentFilter pkgFilter = new IntentFilter();
4374 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4375 pkgFilter.addDataScheme("package");
4376 mContext.registerReceiver(new BroadcastReceiver() {
4377 @Override
4378 public void onReceive(Context context, Intent intent) {
4379 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4380 if (pkgs != null) {
4381 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004382 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004383 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4384 setResultCode(Activity.RESULT_OK);
4385 return;
4386 }
4387 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004388 }
4389 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004390 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004391 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004392
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004393 synchronized (this) {
4394 // Ensure that any processes we had put on hold are now started
4395 // up.
4396 final int NP = mProcessesOnHold.size();
4397 if (NP > 0) {
4398 ArrayList<ProcessRecord> procs =
4399 new ArrayList<ProcessRecord>(mProcessesOnHold);
4400 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004401 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4402 + procs.get(ip));
4403 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004404 }
4405 }
4406
4407 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004408 // Start looking for apps that are abusing wake locks.
4409 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004410 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004411 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004412 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004413 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004414 for (int i=0; i<mStartedUsers.size(); i++) {
4415 UserStartedState uss = mStartedUsers.valueAt(i);
4416 if (uss.mState == UserStartedState.STATE_BOOTING) {
4417 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004418 final int userId = mStartedUsers.keyAt(i);
4419 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4420 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4421 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004422 null, null, 0, null, null,
4423 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004424 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004425 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004426 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004427 }
4428 }
4429 }
4430
4431 final void ensureBootCompleted() {
4432 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004433 boolean enableScreen;
4434 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004435 booting = mBooting;
4436 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004437 enableScreen = !mBooted;
4438 mBooted = true;
4439 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004440
4441 if (booting) {
4442 finishBooting();
4443 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004444
4445 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004446 enableScreenAfterBoot();
4447 }
4448 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004449
4450 public final void activityResumed(IBinder token) {
4451 final long origId = Binder.clearCallingIdentity();
4452 mMainStack.activityResumed(token);
4453 Binder.restoreCallingIdentity(origId);
4454 }
4455
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004456 public final void activityPaused(IBinder token) {
4457 final long origId = Binder.clearCallingIdentity();
4458 mMainStack.activityPaused(token, false);
4459 Binder.restoreCallingIdentity(origId);
4460 }
4461
4462 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4463 CharSequence description) {
4464 if (localLOGV) Slog.v(
4465 TAG, "Activity stopped: token=" + token);
4466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 // Refuse possible leaked file descriptors
4468 if (icicle != null && icicle.hasFileDescriptors()) {
4469 throw new IllegalArgumentException("File descriptors passed in Bundle");
4470 }
4471
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004472 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473
4474 final long origId = Binder.clearCallingIdentity();
4475
4476 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004477 r = mMainStack.isInStackLocked(token);
4478 if (r != null) {
4479 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 }
4481 }
4482
4483 if (r != null) {
4484 sendPendingThumbnail(r, null, null, null, false);
4485 }
4486
4487 trimApplications();
4488
4489 Binder.restoreCallingIdentity(origId);
4490 }
4491
4492 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004493 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004494 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 }
4496
4497 public String getCallingPackage(IBinder token) {
4498 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004499 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004500 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 }
4502 }
4503
4504 public ComponentName getCallingActivity(IBinder token) {
4505 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004506 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 return r != null ? r.intent.getComponent() : null;
4508 }
4509 }
4510
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004511 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004512 ActivityRecord r = mMainStack.isInStackLocked(token);
4513 if (r == null) {
4514 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004516 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518
4519 public ComponentName getActivityClassForToken(IBinder token) {
4520 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004521 ActivityRecord r = mMainStack.isInStackLocked(token);
4522 if (r == null) {
4523 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004525 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 }
4527 }
4528
4529 public String getPackageForToken(IBinder token) {
4530 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004531 ActivityRecord r = mMainStack.isInStackLocked(token);
4532 if (r == null) {
4533 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004535 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 }
4537 }
4538
4539 public IIntentSender getIntentSender(int type,
4540 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004541 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004542 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004543 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004545 if (intents != null) {
4546 if (intents.length < 1) {
4547 throw new IllegalArgumentException("Intents array length must be >= 1");
4548 }
4549 for (int i=0; i<intents.length; i++) {
4550 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004551 if (intent != null) {
4552 if (intent.hasFileDescriptors()) {
4553 throw new IllegalArgumentException("File descriptors passed in Intent");
4554 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004555 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004556 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4557 throw new IllegalArgumentException(
4558 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4559 }
4560 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004561 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004562 }
4563 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004564 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004565 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004566 }
4567 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004568 if (options != null) {
4569 if (options.hasFileDescriptors()) {
4570 throw new IllegalArgumentException("File descriptors passed in options");
4571 }
4572 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 synchronized(this) {
4575 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004576 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004577 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004578 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004579 "getIntentSender", null);
4580 if (origUserId == UserHandle.USER_CURRENT) {
4581 // We don't want to evaluate this until the pending intent is
4582 // actually executed. However, we do want to always do the
4583 // security checking for it above.
4584 userId = UserHandle.USER_CURRENT;
4585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004587 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004588 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004589 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4590 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 String msg = "Permission Denial: getIntentSender() from pid="
4592 + Binder.getCallingPid()
4593 + ", uid=" + Binder.getCallingUid()
4594 + ", (need uid=" + uid + ")"
4595 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004596 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 throw new SecurityException(msg);
4598 }
4599 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004600
4601 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004602 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 } catch (RemoteException e) {
4605 throw new SecurityException(e);
4606 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004607 }
4608 }
4609
Dianne Hackborn41203752012-08-31 14:05:51 -07004610 IIntentSender getIntentSenderLocked(int type, String packageName,
4611 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004612 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4613 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004614 if (DEBUG_MU)
4615 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004616 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004617 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004618 activity = mMainStack.isInStackLocked(token);
4619 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004620 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004622 if (activity.finishing) {
4623 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004625 }
4626
4627 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4628 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4629 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4630 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4631 |PendingIntent.FLAG_UPDATE_CURRENT);
4632
4633 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4634 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004635 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004636 WeakReference<PendingIntentRecord> ref;
4637 ref = mIntentSenderRecords.get(key);
4638 PendingIntentRecord rec = ref != null ? ref.get() : null;
4639 if (rec != null) {
4640 if (!cancelCurrent) {
4641 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004642 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004643 rec.key.requestIntent.replaceExtras(intents != null ?
4644 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004645 }
4646 if (intents != null) {
4647 intents[intents.length-1] = rec.key.requestIntent;
4648 rec.key.allIntents = intents;
4649 rec.key.allResolvedTypes = resolvedTypes;
4650 } else {
4651 rec.key.allIntents = null;
4652 rec.key.allResolvedTypes = null;
4653 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 return rec;
4656 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004657 rec.canceled = true;
4658 mIntentSenderRecords.remove(key);
4659 }
4660 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 return rec;
4662 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004663 rec = new PendingIntentRecord(this, key, callingUid);
4664 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004665 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004666 if (activity.pendingResults == null) {
4667 activity.pendingResults
4668 = new HashSet<WeakReference<PendingIntentRecord>>();
4669 }
4670 activity.pendingResults.add(rec.ref);
4671 }
4672 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 }
4674
4675 public void cancelIntentSender(IIntentSender sender) {
4676 if (!(sender instanceof PendingIntentRecord)) {
4677 return;
4678 }
4679 synchronized(this) {
4680 PendingIntentRecord rec = (PendingIntentRecord)sender;
4681 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004682 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004683 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4684 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 String msg = "Permission Denial: cancelIntentSender() from pid="
4686 + Binder.getCallingPid()
4687 + ", uid=" + Binder.getCallingUid()
4688 + " is not allowed to cancel packges "
4689 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004690 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 throw new SecurityException(msg);
4692 }
4693 } catch (RemoteException e) {
4694 throw new SecurityException(e);
4695 }
4696 cancelIntentSenderLocked(rec, true);
4697 }
4698 }
4699
4700 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4701 rec.canceled = true;
4702 mIntentSenderRecords.remove(rec.key);
4703 if (cleanActivity && rec.key.activity != null) {
4704 rec.key.activity.pendingResults.remove(rec.ref);
4705 }
4706 }
4707
4708 public String getPackageForIntentSender(IIntentSender pendingResult) {
4709 if (!(pendingResult instanceof PendingIntentRecord)) {
4710 return null;
4711 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004712 try {
4713 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4714 return res.key.packageName;
4715 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 }
4717 return null;
4718 }
4719
Christopher Tatec4a07d12012-04-06 14:19:13 -07004720 public int getUidForIntentSender(IIntentSender sender) {
4721 if (sender instanceof PendingIntentRecord) {
4722 try {
4723 PendingIntentRecord res = (PendingIntentRecord)sender;
4724 return res.uid;
4725 } catch (ClassCastException e) {
4726 }
4727 }
4728 return -1;
4729 }
4730
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004731 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4732 if (!(pendingResult instanceof PendingIntentRecord)) {
4733 return false;
4734 }
4735 try {
4736 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4737 if (res.key.allIntents == null) {
4738 return false;
4739 }
4740 for (int i=0; i<res.key.allIntents.length; i++) {
4741 Intent intent = res.key.allIntents[i];
4742 if (intent.getPackage() != null && intent.getComponent() != null) {
4743 return false;
4744 }
4745 }
4746 return true;
4747 } catch (ClassCastException e) {
4748 }
4749 return false;
4750 }
4751
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004752 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4753 if (!(pendingResult instanceof PendingIntentRecord)) {
4754 return false;
4755 }
4756 try {
4757 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4758 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4759 return true;
4760 }
4761 return false;
4762 } catch (ClassCastException e) {
4763 }
4764 return false;
4765 }
4766
Dianne Hackborn81038902012-11-26 17:04:09 -08004767 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4768 if (!(pendingResult instanceof PendingIntentRecord)) {
4769 return null;
4770 }
4771 try {
4772 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4773 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4774 } catch (ClassCastException e) {
4775 }
4776 return null;
4777 }
4778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 public void setProcessLimit(int max) {
4780 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4781 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004782 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004783 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004784 mProcessLimitOverride = max;
4785 }
4786 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 }
4788
4789 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004790 synchronized (this) {
4791 return mProcessLimitOverride;
4792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
4794
4795 void foregroundTokenDied(ForegroundToken token) {
4796 synchronized (ActivityManagerService.this) {
4797 synchronized (mPidsSelfLocked) {
4798 ForegroundToken cur
4799 = mForegroundProcesses.get(token.pid);
4800 if (cur != token) {
4801 return;
4802 }
4803 mForegroundProcesses.remove(token.pid);
4804 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4805 if (pr == null) {
4806 return;
4807 }
4808 pr.forcingToForeground = null;
4809 pr.foregroundServices = false;
4810 }
4811 updateOomAdjLocked();
4812 }
4813 }
4814
4815 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4816 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4817 "setProcessForeground()");
4818 synchronized(this) {
4819 boolean changed = false;
4820
4821 synchronized (mPidsSelfLocked) {
4822 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004823 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004824 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004825 return;
4826 }
4827 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4828 if (oldToken != null) {
4829 oldToken.token.unlinkToDeath(oldToken, 0);
4830 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004831 if (pr != null) {
4832 pr.forcingToForeground = null;
4833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004834 changed = true;
4835 }
4836 if (isForeground && token != null) {
4837 ForegroundToken newToken = new ForegroundToken() {
4838 public void binderDied() {
4839 foregroundTokenDied(this);
4840 }
4841 };
4842 newToken.pid = pid;
4843 newToken.token = token;
4844 try {
4845 token.linkToDeath(newToken, 0);
4846 mForegroundProcesses.put(pid, newToken);
4847 pr.forcingToForeground = token;
4848 changed = true;
4849 } catch (RemoteException e) {
4850 // If the process died while doing this, we will later
4851 // do the cleanup with the process death link.
4852 }
4853 }
4854 }
4855
4856 if (changed) {
4857 updateOomAdjLocked();
4858 }
4859 }
4860 }
4861
4862 // =========================================================
4863 // PERMISSIONS
4864 // =========================================================
4865
4866 static class PermissionController extends IPermissionController.Stub {
4867 ActivityManagerService mActivityManagerService;
4868 PermissionController(ActivityManagerService activityManagerService) {
4869 mActivityManagerService = activityManagerService;
4870 }
4871
4872 public boolean checkPermission(String permission, int pid, int uid) {
4873 return mActivityManagerService.checkPermission(permission, pid,
4874 uid) == PackageManager.PERMISSION_GRANTED;
4875 }
4876 }
4877
4878 /**
4879 * This can be called with or without the global lock held.
4880 */
4881 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004882 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 // We might be performing an operation on behalf of an indirect binder
4884 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4885 // client identity accordingly before proceeding.
4886 Identity tlsIdentity = sCallerIdentity.get();
4887 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004888 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4890 uid = tlsIdentity.uid;
4891 pid = tlsIdentity.pid;
4892 }
4893
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004894 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 return PackageManager.PERMISSION_GRANTED;
4896 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004897
4898 return ActivityManager.checkComponentPermission(permission, uid,
4899 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 }
4901
4902 /**
4903 * As the only public entry point for permissions checking, this method
4904 * can enforce the semantic that requesting a check on a null global
4905 * permission is automatically denied. (Internally a null permission
4906 * string is used when calling {@link #checkComponentPermission} in cases
4907 * when only uid-based security is needed.)
4908 *
4909 * This can be called with or without the global lock held.
4910 */
4911 public int checkPermission(String permission, int pid, int uid) {
4912 if (permission == null) {
4913 return PackageManager.PERMISSION_DENIED;
4914 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004915 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 }
4917
4918 /**
4919 * Binder IPC calls go through the public entry point.
4920 * This can be called with or without the global lock held.
4921 */
4922 int checkCallingPermission(String permission) {
4923 return checkPermission(permission,
4924 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004925 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 }
4927
4928 /**
4929 * This can be called with or without the global lock held.
4930 */
4931 void enforceCallingPermission(String permission, String func) {
4932 if (checkCallingPermission(permission)
4933 == PackageManager.PERMISSION_GRANTED) {
4934 return;
4935 }
4936
4937 String msg = "Permission Denial: " + func + " from pid="
4938 + Binder.getCallingPid()
4939 + ", uid=" + Binder.getCallingUid()
4940 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004941 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 throw new SecurityException(msg);
4943 }
4944
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004945 /**
4946 * Determine if UID is holding permissions required to access {@link Uri} in
4947 * the given {@link ProviderInfo}. Final permission checking is always done
4948 * in {@link ContentProvider}.
4949 */
4950 private final boolean checkHoldingPermissionsLocked(
4951 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004952 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4953 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004954
4955 if (pi.applicationInfo.uid == uid) {
4956 return true;
4957 } else if (!pi.exported) {
4958 return false;
4959 }
4960
4961 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4962 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004964 // check if target holds top-level <provider> permissions
4965 if (!readMet && pi.readPermission != null
4966 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4967 readMet = true;
4968 }
4969 if (!writeMet && pi.writePermission != null
4970 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4971 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004973
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004974 // track if unprotected read/write is allowed; any denied
4975 // <path-permission> below removes this ability
4976 boolean allowDefaultRead = pi.readPermission == null;
4977 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004978
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004979 // check if target holds any <path-permission> that match uri
4980 final PathPermission[] pps = pi.pathPermissions;
4981 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004982 final String path = uri.getPath();
4983 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004984 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004985 i--;
4986 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004987 if (pp.match(path)) {
4988 if (!readMet) {
4989 final String pprperm = pp.getReadPermission();
4990 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4991 + pprperm + " for " + pp.getPath()
4992 + ": match=" + pp.match(path)
4993 + " check=" + pm.checkUidPermission(pprperm, uid));
4994 if (pprperm != null) {
4995 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4996 readMet = true;
4997 } else {
4998 allowDefaultRead = false;
4999 }
5000 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005001 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005002 if (!writeMet) {
5003 final String ppwperm = pp.getWritePermission();
5004 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5005 + ppwperm + " for " + pp.getPath()
5006 + ": match=" + pp.match(path)
5007 + " check=" + pm.checkUidPermission(ppwperm, uid));
5008 if (ppwperm != null) {
5009 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5010 writeMet = true;
5011 } else {
5012 allowDefaultWrite = false;
5013 }
5014 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005015 }
5016 }
5017 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005018 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005019
5020 // grant unprotected <provider> read/write, if not blocked by
5021 // <path-permission> above
5022 if (allowDefaultRead) readMet = true;
5023 if (allowDefaultWrite) writeMet = true;
5024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 } catch (RemoteException e) {
5026 return false;
5027 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005028
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005029 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 }
5031
5032 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5033 int modeFlags) {
5034 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005035 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005036 return true;
5037 }
5038 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5039 if (perms == null) return false;
5040 UriPermission perm = perms.get(uri);
5041 if (perm == null) return false;
5042 return (modeFlags&perm.modeFlags) == modeFlags;
5043 }
5044
5045 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005046 enforceNotIsolatedCaller("checkUriPermission");
5047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048 // Another redirected-binder-call permissions check as in
5049 // {@link checkComponentPermission}.
5050 Identity tlsIdentity = sCallerIdentity.get();
5051 if (tlsIdentity != null) {
5052 uid = tlsIdentity.uid;
5053 pid = tlsIdentity.pid;
5054 }
5055
5056 // Our own process gets to do everything.
5057 if (pid == MY_PID) {
5058 return PackageManager.PERMISSION_GRANTED;
5059 }
5060 synchronized(this) {
5061 return checkUriPermissionLocked(uri, uid, modeFlags)
5062 ? PackageManager.PERMISSION_GRANTED
5063 : PackageManager.PERMISSION_DENIED;
5064 }
5065 }
5066
Dianne Hackborn39792d22010-08-19 18:01:52 -07005067 /**
5068 * Check if the targetPkg can be granted permission to access uri by
5069 * the callingUid using the given modeFlags. Throws a security exception
5070 * if callingUid is not allowed to do this. Returns the uid of the target
5071 * if the URI permission grant should be performed; returns -1 if it is not
5072 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005073 * If you already know the uid of the target, you can supply it in
5074 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005075 */
5076 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005077 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5079 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5080 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005081 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 }
5083
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005084 if (targetPkg != null) {
5085 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5086 "Checking grant " + targetPkg + " permission to " + uri);
5087 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005088
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005089 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090
5091 // If this is not a content: uri, we can't do anything with it.
5092 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005093 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005094 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005095 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 }
5097
5098 String name = uri.getAuthority();
5099 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005100 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005101 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 if (cpr != null) {
5103 pi = cpr.info;
5104 } else {
5105 try {
5106 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005107 PackageManager.GET_URI_PERMISSION_PATTERNS,
5108 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 } catch (RemoteException ex) {
5110 }
5111 }
5112 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005113 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005114 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 }
5116
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005117 int targetUid = lastTargetUid;
5118 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005119 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005120 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005121 if (targetUid < 0) {
5122 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5123 "Can't grant URI permission no uid for: " + targetPkg);
5124 return -1;
5125 }
5126 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005127 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 }
5130
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005131 if (targetUid >= 0) {
5132 // First... does the target actually need this permission?
5133 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5134 // No need to grant the target this permission.
5135 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5136 "Target " + targetPkg + " already has full permission to " + uri);
5137 return -1;
5138 }
5139 } else {
5140 // First... there is no target package, so can anyone access it?
5141 boolean allowed = pi.exported;
5142 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5143 if (pi.readPermission != null) {
5144 allowed = false;
5145 }
5146 }
5147 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5148 if (pi.writePermission != null) {
5149 allowed = false;
5150 }
5151 }
5152 if (allowed) {
5153 return -1;
5154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 }
5156
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005157 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 if (!pi.grantUriPermissions) {
5159 throw new SecurityException("Provider " + pi.packageName
5160 + "/" + pi.name
5161 + " does not allow granting of Uri permissions (uri "
5162 + uri + ")");
5163 }
5164 if (pi.uriPermissionPatterns != null) {
5165 final int N = pi.uriPermissionPatterns.length;
5166 boolean allowed = false;
5167 for (int i=0; i<N; i++) {
5168 if (pi.uriPermissionPatterns[i] != null
5169 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5170 allowed = true;
5171 break;
5172 }
5173 }
5174 if (!allowed) {
5175 throw new SecurityException("Provider " + pi.packageName
5176 + "/" + pi.name
5177 + " does not allow granting of permission to path of Uri "
5178 + uri);
5179 }
5180 }
5181
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005182 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005184 if (callingUid != Process.myUid()) {
5185 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5186 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5187 throw new SecurityException("Uid " + callingUid
5188 + " does not have permission to uri " + uri);
5189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005190 }
5191 }
5192
Dianne Hackborn39792d22010-08-19 18:01:52 -07005193 return targetUid;
5194 }
5195
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005196 public int checkGrantUriPermission(int callingUid, String targetPkg,
5197 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005198 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005199 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005200 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005201 }
5202 }
5203
Dianne Hackborn39792d22010-08-19 18:01:52 -07005204 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5205 Uri uri, int modeFlags, UriPermissionOwner owner) {
5206 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5207 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5208 if (modeFlags == 0) {
5209 return;
5210 }
5211
5212 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 // to the uri, and the target doesn't. Let's now give this to
5214 // the target.
5215
Joe Onorato8a9b2202010-02-26 18:56:32 -08005216 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005217 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 HashMap<Uri, UriPermission> targetUris
5220 = mGrantedUriPermissions.get(targetUid);
5221 if (targetUris == null) {
5222 targetUris = new HashMap<Uri, UriPermission>();
5223 mGrantedUriPermissions.put(targetUid, targetUris);
5224 }
5225
5226 UriPermission perm = targetUris.get(uri);
5227 if (perm == null) {
5228 perm = new UriPermission(targetUid, uri);
5229 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005233 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005235 } else {
5236 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5237 perm.readOwners.add(owner);
5238 owner.addReadPermission(perm);
5239 }
5240 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5241 perm.writeOwners.add(owner);
5242 owner.addWritePermission(perm);
5243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 }
5245 }
5246
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005247 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5248 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005249 if (targetPkg == null) {
5250 throw new NullPointerException("targetPkg");
5251 }
5252
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005253 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005254 if (targetUid < 0) {
5255 return;
5256 }
5257
5258 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5259 }
5260
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005261 static class NeededUriGrants extends ArrayList<Uri> {
5262 final String targetPkg;
5263 final int targetUid;
5264 final int flags;
5265
5266 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5267 targetPkg = _targetPkg;
5268 targetUid = _targetUid;
5269 flags = _flags;
5270 }
5271 }
5272
Dianne Hackborn39792d22010-08-19 18:01:52 -07005273 /**
5274 * Like checkGrantUriPermissionLocked, but takes an Intent.
5275 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005276 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5277 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005278 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005279 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5280 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005281 + " from " + intent + "; flags=0x"
5282 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5283
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005284 if (targetPkg == null) {
5285 throw new NullPointerException("targetPkg");
5286 }
5287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005289 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 }
5291 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005292 ClipData clip = intent.getClipData();
5293 if (data == null && clip == null) {
5294 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005295 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005296 if (data != null) {
5297 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5298 mode, needed != null ? needed.targetUid : -1);
5299 if (target > 0) {
5300 if (needed == null) {
5301 needed = new NeededUriGrants(targetPkg, target, mode);
5302 }
5303 needed.add(data);
5304 }
5305 }
5306 if (clip != null) {
5307 for (int i=0; i<clip.getItemCount(); i++) {
5308 Uri uri = clip.getItemAt(i).getUri();
5309 if (uri != null) {
5310 int target = -1;
5311 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5312 mode, needed != null ? needed.targetUid : -1);
5313 if (target > 0) {
5314 if (needed == null) {
5315 needed = new NeededUriGrants(targetPkg, target, mode);
5316 }
5317 needed.add(uri);
5318 }
5319 } else {
5320 Intent clipIntent = clip.getItemAt(i).getIntent();
5321 if (clipIntent != null) {
5322 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5323 callingUid, targetPkg, clipIntent, mode, needed);
5324 if (newNeeded != null) {
5325 needed = newNeeded;
5326 }
5327 }
5328 }
5329 }
5330 }
5331
5332 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005333 }
5334
5335 /**
5336 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5337 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005338 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5339 UriPermissionOwner owner) {
5340 if (needed != null) {
5341 for (int i=0; i<needed.size(); i++) {
5342 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5343 needed.get(i), needed.flags, owner);
5344 }
5345 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005346 }
5347
5348 void grantUriPermissionFromIntentLocked(int callingUid,
5349 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005350 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005351 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005352 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 return;
5354 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005355
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005356 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 }
5358
5359 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5360 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005361 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 synchronized(this) {
5363 final ProcessRecord r = getRecordForAppLocked(caller);
5364 if (r == null) {
5365 throw new SecurityException("Unable to find app for caller "
5366 + caller
5367 + " when granting permission to uri " + uri);
5368 }
5369 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005370 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 }
5372 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005373 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 }
5375
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005376 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 null);
5378 }
5379 }
5380
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005381 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5383 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5384 HashMap<Uri, UriPermission> perms
5385 = mGrantedUriPermissions.get(perm.uid);
5386 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005387 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005388 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 perms.remove(perm.uri);
5390 if (perms.size() == 0) {
5391 mGrantedUriPermissions.remove(perm.uid);
5392 }
5393 }
5394 }
5395 }
5396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5398 int modeFlags) {
5399 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5400 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5401 if (modeFlags == 0) {
5402 return;
5403 }
5404
Joe Onorato8a9b2202010-02-26 18:56:32 -08005405 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005406 "Revoking all granted permissions to " + uri);
5407
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005408 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409
5410 final String authority = uri.getAuthority();
5411 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005412 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005413 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 if (cpr != null) {
5415 pi = cpr.info;
5416 } else {
5417 try {
5418 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005419 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 } catch (RemoteException ex) {
5421 }
5422 }
5423 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005424 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 return;
5426 }
5427
5428 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005429 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 // Right now, if you are not the original owner of the permission,
5431 // you are not allowed to revoke it.
5432 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5433 throw new SecurityException("Uid " + callingUid
5434 + " does not have permission to uri " + uri);
5435 //}
5436 }
5437
5438 // Go through all of the permissions and remove any that match.
5439 final List<String> SEGMENTS = uri.getPathSegments();
5440 if (SEGMENTS != null) {
5441 final int NS = SEGMENTS.size();
5442 int N = mGrantedUriPermissions.size();
5443 for (int i=0; i<N; i++) {
5444 HashMap<Uri, UriPermission> perms
5445 = mGrantedUriPermissions.valueAt(i);
5446 Iterator<UriPermission> it = perms.values().iterator();
5447 toploop:
5448 while (it.hasNext()) {
5449 UriPermission perm = it.next();
5450 Uri targetUri = perm.uri;
5451 if (!authority.equals(targetUri.getAuthority())) {
5452 continue;
5453 }
5454 List<String> targetSegments = targetUri.getPathSegments();
5455 if (targetSegments == null) {
5456 continue;
5457 }
5458 if (targetSegments.size() < NS) {
5459 continue;
5460 }
5461 for (int j=0; j<NS; j++) {
5462 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5463 continue toploop;
5464 }
5465 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005466 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005467 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 perm.clearModes(modeFlags);
5469 if (perm.modeFlags == 0) {
5470 it.remove();
5471 }
5472 }
5473 if (perms.size() == 0) {
5474 mGrantedUriPermissions.remove(
5475 mGrantedUriPermissions.keyAt(i));
5476 N--;
5477 i--;
5478 }
5479 }
5480 }
5481 }
5482
5483 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5484 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005485 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 synchronized(this) {
5487 final ProcessRecord r = getRecordForAppLocked(caller);
5488 if (r == null) {
5489 throw new SecurityException("Unable to find app for caller "
5490 + caller
5491 + " when revoking permission to uri " + uri);
5492 }
5493 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005494 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 return;
5496 }
5497
5498 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5499 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5500 if (modeFlags == 0) {
5501 return;
5502 }
5503
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005504 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505
5506 final String authority = uri.getAuthority();
5507 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005508 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 if (cpr != null) {
5510 pi = cpr.info;
5511 } else {
5512 try {
5513 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005514 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 } catch (RemoteException ex) {
5516 }
5517 }
5518 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005519 Slog.w(TAG, "No content provider found for permission revoke: "
5520 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 return;
5522 }
5523
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005524 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 }
5526 }
5527
Dianne Hackborn7e269642010-08-25 19:50:20 -07005528 @Override
5529 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005530 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005531 synchronized(this) {
5532 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5533 return owner.getExternalTokenLocked();
5534 }
5535 }
5536
5537 @Override
5538 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5539 Uri uri, int modeFlags) {
5540 synchronized(this) {
5541 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5542 if (owner == null) {
5543 throw new IllegalArgumentException("Unknown owner: " + token);
5544 }
5545 if (fromUid != Binder.getCallingUid()) {
5546 if (Binder.getCallingUid() != Process.myUid()) {
5547 // Only system code can grant URI permissions on behalf
5548 // of other users.
5549 throw new SecurityException("nice try");
5550 }
5551 }
5552 if (targetPkg == null) {
5553 throw new IllegalArgumentException("null target");
5554 }
5555 if (uri == null) {
5556 throw new IllegalArgumentException("null uri");
5557 }
5558
5559 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5560 }
5561 }
5562
5563 @Override
5564 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5565 synchronized(this) {
5566 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5567 if (owner == null) {
5568 throw new IllegalArgumentException("Unknown owner: " + token);
5569 }
5570
5571 if (uri == null) {
5572 owner.removeUriPermissionsLocked(mode);
5573 } else {
5574 owner.removeUriPermissionLocked(uri, mode);
5575 }
5576 }
5577 }
5578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5580 synchronized (this) {
5581 ProcessRecord app =
5582 who != null ? getRecordForAppLocked(who) : null;
5583 if (app == null) return;
5584
5585 Message msg = Message.obtain();
5586 msg.what = WAIT_FOR_DEBUGGER_MSG;
5587 msg.obj = app;
5588 msg.arg1 = waiting ? 1 : 0;
5589 mHandler.sendMessage(msg);
5590 }
5591 }
5592
5593 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005594 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5595 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005597 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005598 outInfo.threshold = homeAppMem;
5599 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5600 outInfo.hiddenAppThreshold = hiddenAppMem;
5601 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005602 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005603 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5604 ProcessList.VISIBLE_APP_ADJ);
5605 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5606 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 }
5608
5609 // =========================================================
5610 // TASK MANAGEMENT
5611 // =========================================================
5612
5613 public List getTasks(int maxNum, int flags,
5614 IThumbnailReceiver receiver) {
5615 ArrayList list = new ArrayList();
5616
5617 PendingThumbnailsRecord pending = null;
5618 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005619 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620
5621 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005622 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5624 + ", receiver=" + receiver);
5625
5626 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5627 != PackageManager.PERMISSION_GRANTED) {
5628 if (receiver != null) {
5629 // If the caller wants to wait for pending thumbnails,
5630 // it ain't gonna get them.
5631 try {
5632 receiver.finished();
5633 } catch (RemoteException ex) {
5634 }
5635 }
5636 String msg = "Permission Denial: getTasks() from pid="
5637 + Binder.getCallingPid()
5638 + ", uid=" + Binder.getCallingUid()
5639 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005640 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 throw new SecurityException(msg);
5642 }
5643
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005644 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005645 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005646 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005647 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 TaskRecord curTask = null;
5649 int numActivities = 0;
5650 int numRunning = 0;
5651 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005652 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005654 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655
5656 // Initialize state for next task if needed.
5657 if (top == null ||
5658 (top.state == ActivityState.INITIALIZING
5659 && top.task == r.task)) {
5660 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 curTask = r.task;
5662 numActivities = numRunning = 0;
5663 }
5664
5665 // Add 'r' into the current task.
5666 numActivities++;
5667 if (r.app != null && r.app.thread != null) {
5668 numRunning++;
5669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670
Joe Onorato8a9b2202010-02-26 18:56:32 -08005671 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 TAG, r.intent.getComponent().flattenToShortString()
5673 + ": task=" + r.task);
5674
5675 // If the next one is a different task, generate a new
5676 // TaskInfo entry for what we have.
5677 if (next == null || next.task != curTask) {
5678 ActivityManager.RunningTaskInfo ci
5679 = new ActivityManager.RunningTaskInfo();
5680 ci.id = curTask.taskId;
5681 ci.baseActivity = r.intent.getComponent();
5682 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005683 if (top.thumbHolder != null) {
5684 ci.description = top.thumbHolder.lastDescription;
5685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 ci.numActivities = numActivities;
5687 ci.numRunning = numRunning;
5688 //System.out.println(
5689 // "#" + maxNum + ": " + " descr=" + ci.description);
5690 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005691 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 TAG, "State=" + top.state + "Idle=" + top.idle
5693 + " app=" + top.app
5694 + " thr=" + (top.app != null ? top.app.thread : null));
5695 if (top.state == ActivityState.RESUMED
5696 || top.state == ActivityState.PAUSING) {
5697 if (top.idle && top.app != null
5698 && top.app.thread != null) {
5699 topRecord = top;
5700 topThumbnail = top.app.thread;
5701 } else {
5702 top.thumbnailNeeded = true;
5703 }
5704 }
5705 if (pending == null) {
5706 pending = new PendingThumbnailsRecord(receiver);
5707 }
5708 pending.pendingRecords.add(top);
5709 }
5710 list.add(ci);
5711 maxNum--;
5712 top = null;
5713 }
5714 }
5715
5716 if (pending != null) {
5717 mPendingThumbnails.add(pending);
5718 }
5719 }
5720
Joe Onorato8a9b2202010-02-26 18:56:32 -08005721 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722
5723 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005724 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005726 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005728 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005729 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 }
5731 }
5732
5733 if (pending == null && receiver != null) {
5734 // In this case all thumbnails were available and the client
5735 // is being asked to be told when the remaining ones come in...
5736 // which is unusually, since the top-most currently running
5737 // activity should never have a canned thumbnail! Oh well.
5738 try {
5739 receiver.finished();
5740 } catch (RemoteException ex) {
5741 }
5742 }
5743
5744 return list;
5745 }
5746
5747 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005748 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005749 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5750 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 synchronized (this) {
5753 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5754 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005755 final boolean detailed = checkCallingPermission(
5756 android.Manifest.permission.GET_DETAILED_TASKS)
5757 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005759 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 final int N = mRecentTasks.size();
5762 ArrayList<ActivityManager.RecentTaskInfo> res
5763 = new ArrayList<ActivityManager.RecentTaskInfo>(
5764 maxNum < N ? maxNum : N);
5765 for (int i=0; i<N && maxNum > 0; i++) {
5766 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005767 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005768 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005769 // Return the entry if desired by the caller. We always return
5770 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005771 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005772 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5773 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005774
Dianne Hackborn905577f2011-09-07 18:31:28 -07005775 if (i == 0
5776 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 || (tr.intent == null)
5778 || ((tr.intent.getFlags()
5779 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5780 ActivityManager.RecentTaskInfo rti
5781 = new ActivityManager.RecentTaskInfo();
5782 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005783 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 rti.baseIntent = new Intent(
5785 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005786 if (!detailed) {
5787 rti.baseIntent.replaceExtras((Bundle)null);
5788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005790 rti.description = tr.lastDescription;
5791
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005792 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5793 // Check whether this activity is currently available.
5794 try {
5795 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005796 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005797 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005798 continue;
5799 }
5800 } else if (rti.baseIntent != null) {
5801 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005802 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005803 continue;
5804 }
5805 }
5806 } catch (RemoteException e) {
5807 // Will never happen.
5808 }
5809 }
5810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 res.add(rti);
5812 maxNum--;
5813 }
5814 }
5815 return res;
5816 }
5817 }
5818
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005819 private TaskRecord taskForIdLocked(int id) {
5820 final int N = mRecentTasks.size();
5821 for (int i=0; i<N; i++) {
5822 TaskRecord tr = mRecentTasks.get(i);
5823 if (tr.taskId == id) {
5824 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005825 }
5826 }
5827 return null;
5828 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005829
5830 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5831 synchronized (this) {
5832 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5833 "getTaskThumbnails()");
5834 TaskRecord tr = taskForIdLocked(id);
5835 if (tr != null) {
5836 return mMainStack.getTaskThumbnailsLocked(tr);
5837 }
5838 }
5839 return null;
5840 }
5841
Dianne Hackborn15491c62012-09-19 10:59:14 -07005842 public Bitmap getTaskTopThumbnail(int id) {
5843 synchronized (this) {
5844 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5845 "getTaskTopThumbnail()");
5846 TaskRecord tr = taskForIdLocked(id);
5847 if (tr != null) {
5848 return mMainStack.getTaskTopThumbnailLocked(tr);
5849 }
5850 }
5851 return null;
5852 }
5853
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005854 public boolean removeSubTask(int taskId, int subTaskIndex) {
5855 synchronized (this) {
5856 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5857 "removeSubTask()");
5858 long ident = Binder.clearCallingIdentity();
5859 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005860 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5861 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005862 } finally {
5863 Binder.restoreCallingIdentity(ident);
5864 }
5865 }
5866 }
5867
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005868 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5869 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005870 Intent baseIntent = new Intent(
5871 tr.intent != null ? tr.intent : tr.affinityIntent);
5872 ComponentName component = baseIntent.getComponent();
5873 if (component == null) {
5874 Slog.w(TAG, "Now component for base intent of task: " + tr);
5875 return;
5876 }
5877
5878 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005879 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005880
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005881 if (killProcesses) {
5882 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005883 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005884 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005885 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5886 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5887 for (int i=0; i<uids.size(); i++) {
5888 ProcessRecord proc = uids.valueAt(i);
5889 if (proc.userId != tr.userId) {
5890 continue;
5891 }
5892 if (!proc.pkgList.contains(pkg)) {
5893 continue;
5894 }
5895 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005896 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005897 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005898
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005899 // Kill the running processes.
5900 for (int i=0; i<procs.size(); i++) {
5901 ProcessRecord pr = procs.get(i);
5902 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5903 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005904 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005905 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005906 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005907 Process.killProcessQuiet(pr.pid);
5908 } else {
5909 pr.waitingToKill = "remove task";
5910 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005911 }
5912 }
5913 }
5914
5915 public boolean removeTask(int taskId, int flags) {
5916 synchronized (this) {
5917 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5918 "removeTask()");
5919 long ident = Binder.clearCallingIdentity();
5920 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005921 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5922 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005923 if (r != null) {
5924 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005925 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005926 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005927 } else {
5928 TaskRecord tr = null;
5929 int i=0;
5930 while (i < mRecentTasks.size()) {
5931 TaskRecord t = mRecentTasks.get(i);
5932 if (t.taskId == taskId) {
5933 tr = t;
5934 break;
5935 }
5936 i++;
5937 }
5938 if (tr != null) {
5939 if (tr.numActivities <= 0) {
5940 // Caller is just removing a recent task that is
5941 // not actively running. That is easy!
5942 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005943 cleanUpRemovedTaskLocked(tr, flags);
5944 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005945 } else {
5946 Slog.w(TAG, "removeTask: task " + taskId
5947 + " does not have activities to remove, "
5948 + " but numActivities=" + tr.numActivities
5949 + ": " + tr);
5950 }
5951 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005952 }
5953 } finally {
5954 Binder.restoreCallingIdentity(ident);
5955 }
5956 }
5957 return false;
5958 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5961 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005962 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 TaskRecord jt = startTask;
5964
5965 // First look backwards
5966 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005967 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 if (r.task != jt) {
5969 jt = r.task;
5970 if (affinity.equals(jt.affinity)) {
5971 return j;
5972 }
5973 }
5974 }
5975
5976 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005977 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 jt = startTask;
5979 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005980 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 if (r.task != jt) {
5982 if (affinity.equals(jt.affinity)) {
5983 return j;
5984 }
5985 jt = r.task;
5986 }
5987 }
5988
5989 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005990 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 return N-1;
5992 }
5993
5994 return -1;
5995 }
5996
5997 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005998 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006000 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6002 "moveTaskToFront()");
6003
6004 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006005 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6006 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006007 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006008 return;
6009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 final long origId = Binder.clearCallingIdentity();
6011 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006012 TaskRecord tr = taskForIdLocked(task);
6013 if (tr != null) {
6014 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6015 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006017 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6018 // Caller wants the home activity moved with it. To accomplish this,
6019 // we'll just move the home task to the top first.
6020 mMainStack.moveHomeToFrontLocked();
6021 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006022 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006023 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006025 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6026 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006028 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6029 mMainStack.mUserLeaving = true;
6030 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006031 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6032 // Caller wants the home activity moved with it. To accomplish this,
6033 // we'll just move the home task to the top first.
6034 mMainStack.moveHomeToFrontLocked();
6035 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006036 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 return;
6038 }
6039 }
6040 } finally {
6041 Binder.restoreCallingIdentity(origId);
6042 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006043 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 }
6045 }
6046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 public void moveTaskToBack(int task) {
6048 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6049 "moveTaskToBack()");
6050
6051 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006052 if (mMainStack.mResumedActivity != null
6053 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006054 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6055 Binder.getCallingUid(), "Task to back")) {
6056 return;
6057 }
6058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006060 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 Binder.restoreCallingIdentity(origId);
6062 }
6063 }
6064
6065 /**
6066 * Moves an activity, and all of the other activities within the same task, to the bottom
6067 * of the history stack. The activity's order within the task is unchanged.
6068 *
6069 * @param token A reference to the activity we wish to move
6070 * @param nonRoot If false then this only works if the activity is the root
6071 * of a task; if true it will work for any activity in a task.
6072 * @return Returns true if the move completed, false if not.
6073 */
6074 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006075 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 synchronized(this) {
6077 final long origId = Binder.clearCallingIdentity();
6078 int taskId = getTaskForActivityLocked(token, !nonRoot);
6079 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006080 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 }
6082 Binder.restoreCallingIdentity(origId);
6083 }
6084 return false;
6085 }
6086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 public void moveTaskBackwards(int task) {
6088 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6089 "moveTaskBackwards()");
6090
6091 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006092 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6093 Binder.getCallingUid(), "Task backwards")) {
6094 return;
6095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 final long origId = Binder.clearCallingIdentity();
6097 moveTaskBackwardsLocked(task);
6098 Binder.restoreCallingIdentity(origId);
6099 }
6100 }
6101
6102 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006103 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 }
6105
6106 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6107 synchronized(this) {
6108 return getTaskForActivityLocked(token, onlyRoot);
6109 }
6110 }
6111
6112 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006113 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 TaskRecord lastTask = null;
6115 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006116 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006117 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 if (!onlyRoot || lastTask != r.task) {
6119 return r.task.taskId;
6120 }
6121 return -1;
6122 }
6123 lastTask = r.task;
6124 }
6125
6126 return -1;
6127 }
6128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 // =========================================================
6130 // THUMBNAILS
6131 // =========================================================
6132
6133 public void reportThumbnail(IBinder token,
6134 Bitmap thumbnail, CharSequence description) {
6135 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6136 final long origId = Binder.clearCallingIdentity();
6137 sendPendingThumbnail(null, token, thumbnail, description, true);
6138 Binder.restoreCallingIdentity(origId);
6139 }
6140
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006141 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 Bitmap thumbnail, CharSequence description, boolean always) {
6143 TaskRecord task = null;
6144 ArrayList receivers = null;
6145
6146 //System.out.println("Send pending thumbnail: " + r);
6147
6148 synchronized(this) {
6149 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006150 r = mMainStack.isInStackLocked(token);
6151 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 return;
6153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006155 if (thumbnail == null && r.thumbHolder != null) {
6156 thumbnail = r.thumbHolder.lastThumbnail;
6157 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 }
6159 if (thumbnail == null && !always) {
6160 // If there is no thumbnail, and this entry is not actually
6161 // going away, then abort for now and pick up the next
6162 // thumbnail we get.
6163 return;
6164 }
6165 task = r.task;
6166
6167 int N = mPendingThumbnails.size();
6168 int i=0;
6169 while (i<N) {
6170 PendingThumbnailsRecord pr =
6171 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6172 //System.out.println("Looking in " + pr.pendingRecords);
6173 if (pr.pendingRecords.remove(r)) {
6174 if (receivers == null) {
6175 receivers = new ArrayList();
6176 }
6177 receivers.add(pr);
6178 if (pr.pendingRecords.size() == 0) {
6179 pr.finished = true;
6180 mPendingThumbnails.remove(i);
6181 N--;
6182 continue;
6183 }
6184 }
6185 i++;
6186 }
6187 }
6188
6189 if (receivers != null) {
6190 final int N = receivers.size();
6191 for (int i=0; i<N; i++) {
6192 try {
6193 PendingThumbnailsRecord pr =
6194 (PendingThumbnailsRecord)receivers.get(i);
6195 pr.receiver.newThumbnail(
6196 task != null ? task.taskId : -1, thumbnail, description);
6197 if (pr.finished) {
6198 pr.receiver.finished();
6199 }
6200 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006201 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 }
6203 }
6204 }
6205 }
6206
6207 // =========================================================
6208 // CONTENT PROVIDERS
6209 // =========================================================
6210
Jeff Brown10e89712011-07-08 18:52:57 -07006211 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6212 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006214 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006215 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006216 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 } catch (RemoteException ex) {
6218 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006219 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006220 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6221 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006223 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 for (int i=0; i<N; i++) {
6225 ProviderInfo cpi =
6226 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006227 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6228 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006229 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006230 // This is a singleton provider, but a user besides the
6231 // default user is asking to initialize a process it runs
6232 // in... well, no, it doesn't actually run in this process,
6233 // it runs in the process of the default user. Get rid of it.
6234 providers.remove(i);
6235 N--;
6236 continue;
6237 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006238
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006239 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006240 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006242 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006243 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006245 if (DEBUG_MU)
6246 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 app.pubProviders.put(cpi.name, cpr);
6248 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006249 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 }
6251 }
6252 return providers;
6253 }
6254
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006255 /**
6256 * Check if {@link ProcessRecord} has a possible chance at accessing the
6257 * given {@link ProviderInfo}. Final permission checking is always done
6258 * in {@link ContentProvider}.
6259 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006261 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006263 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006265 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006266 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 return null;
6268 }
6269 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006270 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 == PackageManager.PERMISSION_GRANTED) {
6272 return null;
6273 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006274
6275 PathPermission[] pps = cpi.pathPermissions;
6276 if (pps != null) {
6277 int i = pps.length;
6278 while (i > 0) {
6279 i--;
6280 PathPermission pp = pps[i];
6281 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006282 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006283 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006284 return null;
6285 }
6286 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006287 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006288 == PackageManager.PERMISSION_GRANTED) {
6289 return null;
6290 }
6291 }
6292 }
6293
Dianne Hackbornb424b632010-08-18 15:59:05 -07006294 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6295 if (perms != null) {
6296 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6297 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6298 return null;
6299 }
6300 }
6301 }
6302
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006303 String msg;
6304 if (!cpi.exported) {
6305 msg = "Permission Denial: opening provider " + cpi.name
6306 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6307 + ", uid=" + callingUid + ") that is not exported from uid "
6308 + cpi.applicationInfo.uid;
6309 } else {
6310 msg = "Permission Denial: opening provider " + cpi.name
6311 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6312 + ", uid=" + callingUid + ") requires "
6313 + cpi.readPermission + " or " + cpi.writePermission;
6314 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006315 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 return msg;
6317 }
6318
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006319 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6320 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006321 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006322 for (int i=0; i<r.conProviders.size(); i++) {
6323 ContentProviderConnection conn = r.conProviders.get(i);
6324 if (conn.provider == cpr) {
6325 if (DEBUG_PROVIDER) Slog.v(TAG,
6326 "Adding provider requested by "
6327 + r.processName + " from process "
6328 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6329 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6330 if (stable) {
6331 conn.stableCount++;
6332 conn.numStableIncs++;
6333 } else {
6334 conn.unstableCount++;
6335 conn.numUnstableIncs++;
6336 }
6337 return conn;
6338 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006339 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006340 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6341 if (stable) {
6342 conn.stableCount = 1;
6343 conn.numStableIncs = 1;
6344 } else {
6345 conn.unstableCount = 1;
6346 conn.numUnstableIncs = 1;
6347 }
6348 cpr.connections.add(conn);
6349 r.conProviders.add(conn);
6350 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006351 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006352 cpr.addExternalProcessHandleLocked(externalProcessToken);
6353 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006354 }
6355
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006356 boolean decProviderCountLocked(ContentProviderConnection conn,
6357 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6358 if (conn != null) {
6359 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006360 if (DEBUG_PROVIDER) Slog.v(TAG,
6361 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006362 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006363 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006364 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6365 if (stable) {
6366 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006367 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006368 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006369 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006370 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6371 cpr.connections.remove(conn);
6372 conn.client.conProviders.remove(conn);
6373 return true;
6374 }
6375 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006376 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006377 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006378 return false;
6379 }
6380
Amith Yamasani742a6712011-05-04 14:49:28 -07006381 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006382 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006384 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 ProviderInfo cpi = null;
6386
6387 synchronized(this) {
6388 ProcessRecord r = null;
6389 if (caller != null) {
6390 r = getRecordForAppLocked(caller);
6391 if (r == null) {
6392 throw new SecurityException(
6393 "Unable to find app for caller " + caller
6394 + " (pid=" + Binder.getCallingPid()
6395 + ") when getting content provider " + name);
6396 }
6397 }
6398
6399 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006400 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006401 boolean providerRunning = cpr != null;
6402 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006404 String msg;
6405 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6406 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 }
6408
6409 if (r != null && cpr.canRunHere(r)) {
6410 // This provider has been published or is in the process
6411 // of being published... but it is also allowed to run
6412 // in the caller's process, so don't make a connection
6413 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006414 ContentProviderHolder holder = cpr.newHolder(null);
6415 // don't give caller the provider object, it needs
6416 // to make its own.
6417 holder.provider = null;
6418 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 }
6420
6421 final long origId = Binder.clearCallingIdentity();
6422
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006423 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006425 conn = incProviderCountLocked(r, cpr, token, stable);
6426 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006427 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006428 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006429 // make sure to count it as being accessed and thus
6430 // back up on the LRU list. This is good because
6431 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006432 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006433 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006434 }
6435
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006436 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006437 if (false) {
6438 if (cpr.name.flattenToShortString().equals(
6439 "com.android.providers.calendar/.CalendarProvider2")) {
6440 Slog.v(TAG, "****************** KILLING "
6441 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006442 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006443 }
6444 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006445 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006446 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6447 // NOTE: there is still a race here where a signal could be
6448 // pending on the process even though we managed to update its
6449 // adj level. Not sure what to do about this, but at least
6450 // the race is now smaller.
6451 if (!success) {
6452 // Uh oh... it looks like the provider's process
6453 // has been killed on us. We need to wait for a new
6454 // process to be started, and make sure its death
6455 // doesn't kill our process.
6456 Slog.i(TAG,
6457 "Existing provider " + cpr.name.flattenToShortString()
6458 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006459 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006460 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006461 if (!lastRef) {
6462 // This wasn't the last ref our process had on
6463 // the provider... we have now been killed, bail.
6464 return null;
6465 }
6466 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006467 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 }
6470
6471 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006474 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006475 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006477 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006478 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006479 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 } catch (RemoteException ex) {
6481 }
6482 if (cpi == null) {
6483 return null;
6484 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006485 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6486 cpi.name, cpi.flags);
6487 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006488 userId = 0;
6489 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006490 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006491
Dianne Hackbornb424b632010-08-18 15:59:05 -07006492 String msg;
6493 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6494 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006497 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006498 && !cpi.processName.equals("system")) {
6499 // If this content provider does not run in the system
6500 // process, and the system is not yet ready to run other
6501 // processes, then fail fast instead of hanging.
6502 throw new IllegalArgumentException(
6503 "Attempt to launch content provider before system ready");
6504 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006505
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006506 // Make sure that the user who owns this provider is started. If not,
6507 // we don't want to allow it to run.
6508 if (mStartedUsers.get(userId) == null) {
6509 Slog.w(TAG, "Unable to launch app "
6510 + cpi.applicationInfo.packageName + "/"
6511 + cpi.applicationInfo.uid + " for provider "
6512 + name + ": user " + userId + " is stopped");
6513 return null;
6514 }
6515
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006516 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006517 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 final boolean firstClass = cpr == null;
6519 if (firstClass) {
6520 try {
6521 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006522 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 getApplicationInfo(
6524 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006525 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006527 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 + cpi.name);
6529 return null;
6530 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006531 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006532 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 } catch (RemoteException ex) {
6534 // pm is in same process, this will never happen.
6535 }
6536 }
6537
6538 if (r != null && cpr.canRunHere(r)) {
6539 // If this is a multiprocess provider, then just return its
6540 // info and allow the caller to instantiate it. Only do
6541 // this if the provider is the same user as the caller's
6542 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006543 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 }
6545
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006546 if (DEBUG_PROVIDER) {
6547 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006548 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006549 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 }
6551
6552 // This is single process, and our app is now connecting to it.
6553 // See if we are already in the process of launching this
6554 // provider.
6555 final int N = mLaunchingProviders.size();
6556 int i;
6557 for (i=0; i<N; i++) {
6558 if (mLaunchingProviders.get(i) == cpr) {
6559 break;
6560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 }
6562
6563 // If the provider is not already being launched, then get it
6564 // started.
6565 if (i >= N) {
6566 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006567
6568 try {
6569 // Content provider is now in use, its package can't be stopped.
6570 try {
6571 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006572 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006573 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006574 } catch (IllegalArgumentException e) {
6575 Slog.w(TAG, "Failed trying to unstop package "
6576 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006577 }
6578
6579 ProcessRecord proc = startProcessLocked(cpi.processName,
6580 cpr.appInfo, false, 0, "content provider",
6581 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006582 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006583 if (proc == null) {
6584 Slog.w(TAG, "Unable to launch app "
6585 + cpi.applicationInfo.packageName + "/"
6586 + cpi.applicationInfo.uid + " for provider "
6587 + name + ": process is bad");
6588 return null;
6589 }
6590 cpr.launchingApp = proc;
6591 mLaunchingProviders.add(cpr);
6592 } finally {
6593 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 }
6596
6597 // Make sure the provider is published (the same provider class
6598 // may be published under multiple names).
6599 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006600 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006602
Amith Yamasani742a6712011-05-04 14:49:28 -07006603 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006604 conn = incProviderCountLocked(r, cpr, token, stable);
6605 if (conn != null) {
6606 conn.waiting = true;
6607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 }
6609 }
6610
6611 // Wait for the provider to be published...
6612 synchronized (cpr) {
6613 while (cpr.provider == null) {
6614 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006615 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 + cpi.applicationInfo.packageName + "/"
6617 + cpi.applicationInfo.uid + " for provider "
6618 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006619 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006620 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 cpi.applicationInfo.packageName,
6622 cpi.applicationInfo.uid, name);
6623 return null;
6624 }
6625 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006626 if (DEBUG_MU) {
6627 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6628 + cpr.launchingApp);
6629 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006630 if (conn != null) {
6631 conn.waiting = true;
6632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 cpr.wait();
6634 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006635 } finally {
6636 if (conn != null) {
6637 conn.waiting = false;
6638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 }
6640 }
6641 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006642 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 }
6644
6645 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006646 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006647 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 if (caller == null) {
6649 String msg = "null IApplicationThread when getting content provider "
6650 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006651 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 throw new SecurityException(msg);
6653 }
6654
Dianne Hackborn139748f2012-09-24 11:36:57 -07006655 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006656 false, true, "getContentProvider", null);
6657 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 }
6659
Jeff Sharkey6d515712012-09-20 16:06:08 -07006660 public ContentProviderHolder getContentProviderExternal(
6661 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006662 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6663 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006664 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006665 false, true, "getContentProvider", null);
6666 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006667 }
6668
Dianne Hackborn41203752012-08-31 14:05:51 -07006669 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6670 IBinder token, int userId) {
6671 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 }
6673
6674 /**
6675 * Drop a content provider from a ProcessRecord's bookkeeping
6676 * @param cpr
6677 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006678 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006679 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006681 ContentProviderConnection conn;
6682 try {
6683 conn = (ContentProviderConnection)connection;
6684 } catch (ClassCastException e) {
6685 String msg ="removeContentProvider: " + connection
6686 + " not a ContentProviderConnection";
6687 Slog.w(TAG, msg);
6688 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006690 if (conn == null) {
6691 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006693 if (decProviderCountLocked(conn, null, null, stable)) {
6694 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 }
6697 }
6698
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006699 public void removeContentProviderExternal(String name, IBinder token) {
6700 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6701 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006702 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006703 }
6704
Dianne Hackborn41203752012-08-31 14:05:51 -07006705 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006707 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 if(cpr == null) {
6709 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006710 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 return;
6712 }
6713
6714 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006715 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006716 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006717 if (localCpr.hasExternalProcessHandles()) {
6718 if (localCpr.removeExternalProcessHandleLocked(token)) {
6719 updateOomAdjLocked();
6720 } else {
6721 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6722 + " with no external reference for token: "
6723 + token + ".");
6724 }
6725 } else {
6726 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6727 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 }
6730 }
6731
6732 public final void publishContentProviders(IApplicationThread caller,
6733 List<ContentProviderHolder> providers) {
6734 if (providers == null) {
6735 return;
6736 }
6737
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006738 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006739 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006741 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006742 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 if (r == null) {
6744 throw new SecurityException(
6745 "Unable to find app for caller " + caller
6746 + " (pid=" + Binder.getCallingPid()
6747 + ") when publishing content providers");
6748 }
6749
6750 final long origId = Binder.clearCallingIdentity();
6751
6752 final int N = providers.size();
6753 for (int i=0; i<N; i++) {
6754 ContentProviderHolder src = providers.get(i);
6755 if (src == null || src.info == null || src.provider == null) {
6756 continue;
6757 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006758 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006759 if (DEBUG_MU)
6760 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006762 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006763 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 String names[] = dst.info.authority.split(";");
6765 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006766 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 }
6768
6769 int NL = mLaunchingProviders.size();
6770 int j;
6771 for (j=0; j<NL; j++) {
6772 if (mLaunchingProviders.get(j) == dst) {
6773 mLaunchingProviders.remove(j);
6774 j--;
6775 NL--;
6776 }
6777 }
6778 synchronized (dst) {
6779 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006780 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 dst.notifyAll();
6782 }
6783 updateOomAdjLocked(r);
6784 }
6785 }
6786
6787 Binder.restoreCallingIdentity(origId);
6788 }
6789 }
6790
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006791 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6792 ContentProviderConnection conn;
6793 try {
6794 conn = (ContentProviderConnection)connection;
6795 } catch (ClassCastException e) {
6796 String msg ="refContentProvider: " + connection
6797 + " not a ContentProviderConnection";
6798 Slog.w(TAG, msg);
6799 throw new IllegalArgumentException(msg);
6800 }
6801 if (conn == null) {
6802 throw new NullPointerException("connection is null");
6803 }
6804
6805 synchronized (this) {
6806 if (stable > 0) {
6807 conn.numStableIncs += stable;
6808 }
6809 stable = conn.stableCount + stable;
6810 if (stable < 0) {
6811 throw new IllegalStateException("stableCount < 0: " + stable);
6812 }
6813
6814 if (unstable > 0) {
6815 conn.numUnstableIncs += unstable;
6816 }
6817 unstable = conn.unstableCount + unstable;
6818 if (unstable < 0) {
6819 throw new IllegalStateException("unstableCount < 0: " + unstable);
6820 }
6821
6822 if ((stable+unstable) <= 0) {
6823 throw new IllegalStateException("ref counts can't go to zero here: stable="
6824 + stable + " unstable=" + unstable);
6825 }
6826 conn.stableCount = stable;
6827 conn.unstableCount = unstable;
6828 return !conn.dead;
6829 }
6830 }
6831
6832 public void unstableProviderDied(IBinder connection) {
6833 ContentProviderConnection conn;
6834 try {
6835 conn = (ContentProviderConnection)connection;
6836 } catch (ClassCastException e) {
6837 String msg ="refContentProvider: " + connection
6838 + " not a ContentProviderConnection";
6839 Slog.w(TAG, msg);
6840 throw new IllegalArgumentException(msg);
6841 }
6842 if (conn == null) {
6843 throw new NullPointerException("connection is null");
6844 }
6845
6846 // Safely retrieve the content provider associated with the connection.
6847 IContentProvider provider;
6848 synchronized (this) {
6849 provider = conn.provider.provider;
6850 }
6851
6852 if (provider == null) {
6853 // Um, yeah, we're way ahead of you.
6854 return;
6855 }
6856
6857 // Make sure the caller is being honest with us.
6858 if (provider.asBinder().pingBinder()) {
6859 // Er, no, still looks good to us.
6860 synchronized (this) {
6861 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6862 + " says " + conn + " died, but we don't agree");
6863 return;
6864 }
6865 }
6866
6867 // Well look at that! It's dead!
6868 synchronized (this) {
6869 if (conn.provider.provider != provider) {
6870 // But something changed... good enough.
6871 return;
6872 }
6873
6874 ProcessRecord proc = conn.provider.proc;
6875 if (proc == null || proc.thread == null) {
6876 // Seems like the process is already cleaned up.
6877 return;
6878 }
6879
6880 // As far as we're concerned, this is just like receiving a
6881 // death notification... just a bit prematurely.
6882 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6883 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006884 final long ident = Binder.clearCallingIdentity();
6885 try {
6886 appDiedLocked(proc, proc.pid, proc.thread);
6887 } finally {
6888 Binder.restoreCallingIdentity(ident);
6889 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006890 }
6891 }
6892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006893 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006894 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006895 synchronized (mSelf) {
6896 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6897 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006898 if (providers != null) {
6899 for (int i=providers.size()-1; i>=0; i--) {
6900 ProviderInfo pi = (ProviderInfo)providers.get(i);
6901 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6902 Slog.w(TAG, "Not installing system proc provider " + pi.name
6903 + ": not system .apk");
6904 providers.remove(i);
6905 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006906 }
6907 }
6908 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006909 if (providers != null) {
6910 mSystemThread.installSystemProviders(providers);
6911 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006912
6913 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006914
6915 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 }
6917
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006918 /**
6919 * Allows app to retrieve the MIME type of a URI without having permission
6920 * to access its content provider.
6921 *
6922 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6923 *
6924 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6925 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6926 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006927 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006928 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006929 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006930 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006931 final String name = uri.getAuthority();
6932 final long ident = Binder.clearCallingIdentity();
6933 ContentProviderHolder holder = null;
6934
6935 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006936 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006937 if (holder != null) {
6938 return holder.provider.getType(uri);
6939 }
6940 } catch (RemoteException e) {
6941 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6942 return null;
6943 } finally {
6944 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006945 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006946 }
6947 Binder.restoreCallingIdentity(ident);
6948 }
6949
6950 return null;
6951 }
6952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006953 // =========================================================
6954 // GLOBAL MANAGEMENT
6955 // =========================================================
6956
6957 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006958 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006959 String proc = customProcess != null ? customProcess : info.processName;
6960 BatteryStatsImpl.Uid.Proc ps = null;
6961 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006962 int uid = info.uid;
6963 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006964 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006965 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6966 uid = 0;
6967 while (true) {
6968 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6969 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6970 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6971 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006972 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006973 mNextIsolatedProcessUid++;
6974 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6975 // No process for this uid, use it.
6976 break;
6977 }
6978 stepsLeft--;
6979 if (stepsLeft <= 0) {
6980 return null;
6981 }
6982 }
6983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006984 synchronized (stats) {
6985 ps = stats.getProcessStatsLocked(info.uid, proc);
6986 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006987 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 }
6989
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006990 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6991 ProcessRecord app;
6992 if (!isolated) {
6993 app = getProcessRecordLocked(info.processName, info.uid);
6994 } else {
6995 app = null;
6996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997
6998 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006999 app = newProcessRecordLocked(null, info, null, isolated);
7000 mProcessNames.put(info.processName, app.uid, app);
7001 if (isolated) {
7002 mIsolatedProcesses.put(app.uid, app);
7003 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007004 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 }
7006
Dianne Hackborne7f97212011-02-24 14:40:20 -08007007 // This package really, really can not be stopped.
7008 try {
7009 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007010 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007011 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007012 } catch (IllegalArgumentException e) {
7013 Slog.w(TAG, "Failed trying to unstop package "
7014 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007015 }
7016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7018 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7019 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007020 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 }
7022 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7023 mPersistentStartingProcesses.add(app);
7024 startProcessLocked(app, "added application", app.processName);
7025 }
7026
7027 return app;
7028 }
7029
7030 public void unhandledBack() {
7031 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7032 "unhandledBack()");
7033
7034 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007035 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007036 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 TAG, "Performing unhandledBack(): stack size = " + count);
7038 if (count > 1) {
7039 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007040 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007041 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 Binder.restoreCallingIdentity(origId);
7043 }
7044 }
7045 }
7046
7047 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007048 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007049 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007051 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 ParcelFileDescriptor pfd = null;
7053 if (cph != null) {
7054 // We record the binder invoker's uid in thread-local storage before
7055 // going to the content provider to open the file. Later, in the code
7056 // that handles all permissions checks, we look for this uid and use
7057 // that rather than the Activity Manager's own uid. The effect is that
7058 // we do the check against the caller's permissions even though it looks
7059 // to the content provider like the Activity Manager itself is making
7060 // the request.
7061 sCallerIdentity.set(new Identity(
7062 Binder.getCallingPid(), Binder.getCallingUid()));
7063 try {
7064 pfd = cph.provider.openFile(uri, "r");
7065 } catch (FileNotFoundException e) {
7066 // do nothing; pfd will be returned null
7067 } finally {
7068 // Ensure that whatever happens, we clean up the identity state
7069 sCallerIdentity.remove();
7070 }
7071
7072 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007073 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007075 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 }
7077 return pfd;
7078 }
7079
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007080 // Actually is sleeping or shutting down or whatever else in the future
7081 // is an inactive state.
7082 public boolean isSleeping() {
7083 return mSleeping || mShuttingDown;
7084 }
7085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007087 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7088 != PackageManager.PERMISSION_GRANTED) {
7089 throw new SecurityException("Requires permission "
7090 + android.Manifest.permission.DEVICE_POWER);
7091 }
7092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007094 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007095 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007097 if (!mSleeping) {
7098 mSleeping = true;
7099 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007100
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007101 // Initialize the wake times of all processes.
7102 checkExcessivePowerUsageLocked(false);
7103 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7104 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7105 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 }
7108 }
7109
Dianne Hackborn55280a92009-05-07 15:53:46 -07007110 public boolean shutdown(int timeout) {
7111 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7112 != PackageManager.PERMISSION_GRANTED) {
7113 throw new SecurityException("Requires permission "
7114 + android.Manifest.permission.SHUTDOWN);
7115 }
7116
7117 boolean timedout = false;
7118
7119 synchronized(this) {
7120 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007121 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007122
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007123 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007124 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007125 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007126 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007127 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007128 long delay = endTime - System.currentTimeMillis();
7129 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007130 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007131 timedout = true;
7132 break;
7133 }
7134 try {
7135 this.wait();
7136 } catch (InterruptedException e) {
7137 }
7138 }
7139 }
7140 }
7141
7142 mUsageStatsService.shutdown();
7143 mBatteryStatsService.shutdown();
7144
7145 return timedout;
7146 }
7147
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007148 public final void activitySlept(IBinder token) {
7149 if (localLOGV) Slog.v(
7150 TAG, "Activity slept: token=" + token);
7151
7152 ActivityRecord r = null;
7153
7154 final long origId = Binder.clearCallingIdentity();
7155
7156 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007157 r = mMainStack.isInStackLocked(token);
7158 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007159 mMainStack.activitySleptLocked(r);
7160 }
7161 }
7162
7163 Binder.restoreCallingIdentity(origId);
7164 }
7165
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007166 private void comeOutOfSleepIfNeededLocked() {
7167 if (!mWentToSleep && !mLockScreenShown) {
7168 if (mSleeping) {
7169 mSleeping = false;
7170 mMainStack.awakeFromSleepingLocked();
7171 mMainStack.resumeTopActivityLocked(null);
7172 }
7173 }
7174 }
7175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007177 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7178 != PackageManager.PERMISSION_GRANTED) {
7179 throw new SecurityException("Requires permission "
7180 + android.Manifest.permission.DEVICE_POWER);
7181 }
7182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007184 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007185 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007186 comeOutOfSleepIfNeededLocked();
7187 }
7188 }
7189
Jeff Brownc042ee22012-05-08 13:03:42 -07007190 private void updateEventDispatchingLocked() {
7191 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7192 }
7193
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007194 public void setLockScreenShown(boolean shown) {
7195 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7196 != PackageManager.PERMISSION_GRANTED) {
7197 throw new SecurityException("Requires permission "
7198 + android.Manifest.permission.DEVICE_POWER);
7199 }
7200
7201 synchronized(this) {
7202 mLockScreenShown = shown;
7203 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 }
7205 }
7206
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007207 public void stopAppSwitches() {
7208 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7209 != PackageManager.PERMISSION_GRANTED) {
7210 throw new SecurityException("Requires permission "
7211 + android.Manifest.permission.STOP_APP_SWITCHES);
7212 }
7213
7214 synchronized(this) {
7215 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7216 + APP_SWITCH_DELAY_TIME;
7217 mDidAppSwitch = false;
7218 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7219 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7220 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7221 }
7222 }
7223
7224 public void resumeAppSwitches() {
7225 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7226 != PackageManager.PERMISSION_GRANTED) {
7227 throw new SecurityException("Requires permission "
7228 + android.Manifest.permission.STOP_APP_SWITCHES);
7229 }
7230
7231 synchronized(this) {
7232 // Note that we don't execute any pending app switches... we will
7233 // let those wait until either the timeout, or the next start
7234 // activity request.
7235 mAppSwitchesAllowedTime = 0;
7236 }
7237 }
7238
7239 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7240 String name) {
7241 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7242 return true;
7243 }
7244
7245 final int perm = checkComponentPermission(
7246 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007247 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007248 if (perm == PackageManager.PERMISSION_GRANTED) {
7249 return true;
7250 }
7251
Joe Onorato8a9b2202010-02-26 18:56:32 -08007252 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007253 return false;
7254 }
7255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007256 public void setDebugApp(String packageName, boolean waitForDebugger,
7257 boolean persistent) {
7258 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7259 "setDebugApp()");
7260
7261 // Note that this is not really thread safe if there are multiple
7262 // callers into it at the same time, but that's not a situation we
7263 // care about.
7264 if (persistent) {
7265 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007266 Settings.Global.putString(
7267 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007269 Settings.Global.putInt(
7270 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007271 waitForDebugger ? 1 : 0);
7272 }
7273
7274 synchronized (this) {
7275 if (!persistent) {
7276 mOrigDebugApp = mDebugApp;
7277 mOrigWaitForDebugger = mWaitForDebugger;
7278 }
7279 mDebugApp = packageName;
7280 mWaitForDebugger = waitForDebugger;
7281 mDebugTransient = !persistent;
7282 if (packageName != null) {
7283 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007284 forceStopPackageLocked(packageName, -1, false, false, true, true,
7285 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 Binder.restoreCallingIdentity(origId);
7287 }
7288 }
7289 }
7290
Siva Velusamy92a8b222012-03-09 16:24:04 -08007291 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7292 synchronized (this) {
7293 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7294 if (!isDebuggable) {
7295 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7296 throw new SecurityException("Process not debuggable: " + app.packageName);
7297 }
7298 }
7299
7300 mOpenGlTraceApp = processName;
7301 }
7302 }
7303
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007304 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7305 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7306 synchronized (this) {
7307 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7308 if (!isDebuggable) {
7309 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7310 throw new SecurityException("Process not debuggable: " + app.packageName);
7311 }
7312 }
7313 mProfileApp = processName;
7314 mProfileFile = profileFile;
7315 if (mProfileFd != null) {
7316 try {
7317 mProfileFd.close();
7318 } catch (IOException e) {
7319 }
7320 mProfileFd = null;
7321 }
7322 mProfileFd = profileFd;
7323 mProfileType = 0;
7324 mAutoStopProfiler = autoStopProfiler;
7325 }
7326 }
7327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007328 public void setAlwaysFinish(boolean enabled) {
7329 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7330 "setAlwaysFinish()");
7331
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007332 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007334 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335
7336 synchronized (this) {
7337 mAlwaysFinishActivities = enabled;
7338 }
7339 }
7340
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007341 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007343 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007345 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 }
7347 }
7348
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007349 public boolean isUserAMonkey() {
7350 // For now the fact that there is a controller implies
7351 // we have a monkey.
7352 synchronized (this) {
7353 return mController != null;
7354 }
7355 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007356
7357 public void requestBugReport() {
7358 // No permission check because this can't do anything harmful --
7359 // it will just eventually cause the user to be presented with
7360 // a UI to select where the bug report goes.
7361 SystemProperties.set("ctl.start", "bugreport");
7362 }
7363
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007364 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7365 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7366 != PackageManager.PERMISSION_GRANTED) {
7367 throw new SecurityException("Requires permission "
7368 + android.Manifest.permission.FILTER_EVENTS);
7369 }
7370
7371 ProcessRecord proc;
7372
7373 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7374 synchronized (this) {
7375 synchronized (mPidsSelfLocked) {
7376 proc = mPidsSelfLocked.get(pid);
7377 }
7378 if (proc != null) {
7379 if (proc.debugging) {
7380 return -1;
7381 }
7382
7383 if (mDidDexOpt) {
7384 // Give more time since we were dexopting.
7385 mDidDexOpt = false;
7386 return -1;
7387 }
7388
7389 if (proc.instrumentationClass != null) {
7390 Bundle info = new Bundle();
7391 info.putString("shortMsg", "keyDispatchingTimedOut");
7392 info.putString("longMsg", "Timed out while dispatching key event");
7393 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7394 proc = null;
7395 }
7396 }
7397 }
7398
7399 if (proc != null) {
7400 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7401 if (proc.instrumentationClass != null || proc.usingWrapper) {
7402 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7403 }
7404 }
7405
7406 return KEY_DISPATCHING_TIMEOUT;
7407 }
7408
Jeff Sharkeya4620792011-05-20 15:29:23 -07007409 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007410 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7411 "registerProcessObserver()");
7412 synchronized (this) {
7413 mProcessObservers.register(observer);
7414 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007415 }
7416
7417 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007418 synchronized (this) {
7419 mProcessObservers.unregister(observer);
7420 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007421 }
7422
Daniel Sandler69a48172010-06-23 16:29:36 -04007423 public void setImmersive(IBinder token, boolean immersive) {
7424 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007425 ActivityRecord r = mMainStack.isInStackLocked(token);
7426 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007427 throw new IllegalArgumentException();
7428 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007429 r.immersive = immersive;
7430 }
7431 }
7432
7433 public boolean isImmersive(IBinder token) {
7434 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007435 ActivityRecord r = mMainStack.isInStackLocked(token);
7436 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007437 throw new IllegalArgumentException();
7438 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007439 return r.immersive;
7440 }
7441 }
7442
7443 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007444 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007445 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007446 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007447 return (r != null) ? r.immersive : false;
7448 }
7449 }
7450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 public final void enterSafeMode() {
7452 synchronized(this) {
7453 // It only makes sense to do this before the system is ready
7454 // and started launching other packages.
7455 if (!mSystemReady) {
7456 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007457 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 } catch (RemoteException e) {
7459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 }
7461 }
7462 }
7463
Jeff Brownb09abc12011-01-13 21:08:27 -08007464 public final void showSafeModeOverlay() {
7465 View v = LayoutInflater.from(mContext).inflate(
7466 com.android.internal.R.layout.safe_mode, null);
7467 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7468 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7469 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7470 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007471 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007472 lp.format = v.getBackground().getOpacity();
7473 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7474 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007475 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007476 ((WindowManager)mContext.getSystemService(
7477 Context.WINDOW_SERVICE)).addView(v, lp);
7478 }
7479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 public void noteWakeupAlarm(IIntentSender sender) {
7481 if (!(sender instanceof PendingIntentRecord)) {
7482 return;
7483 }
7484 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7485 synchronized (stats) {
7486 if (mBatteryStatsService.isOnBattery()) {
7487 mBatteryStatsService.enforceCallingPermission();
7488 PendingIntentRecord rec = (PendingIntentRecord)sender;
7489 int MY_UID = Binder.getCallingUid();
7490 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7491 BatteryStatsImpl.Uid.Pkg pkg =
7492 stats.getPackageStatsLocked(uid, rec.key.packageName);
7493 pkg.incWakeupsLocked();
7494 }
7495 }
7496 }
7497
Dianne Hackborn64825172011-03-02 21:32:58 -08007498 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007500 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007502 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 // XXX Note: don't acquire main activity lock here, because the window
7504 // manager calls in with its locks held.
7505
7506 boolean killed = false;
7507 synchronized (mPidsSelfLocked) {
7508 int[] types = new int[pids.length];
7509 int worstType = 0;
7510 for (int i=0; i<pids.length; i++) {
7511 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7512 if (proc != null) {
7513 int type = proc.setAdj;
7514 types[i] = type;
7515 if (type > worstType) {
7516 worstType = type;
7517 }
7518 }
7519 }
7520
Dianne Hackborn64825172011-03-02 21:32:58 -08007521 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007523 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7524 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007525 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007527
7528 // If this is not a secure call, don't let it kill processes that
7529 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007530 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7531 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007532 }
7533
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007534 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535 for (int i=0; i<pids.length; i++) {
7536 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7537 if (proc == null) {
7538 continue;
7539 }
7540 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007541 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007542 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007543 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007544 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007546 proc.killedBackground = true;
7547 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 }
7549 }
7550 }
7551 return killed;
7552 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007553
7554 @Override
7555 public boolean killProcessesBelowForeground(String reason) {
7556 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7557 throw new SecurityException("killProcessesBelowForeground() only available to system");
7558 }
7559
7560 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7561 }
7562
7563 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7564 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7565 throw new SecurityException("killProcessesBelowAdj() only available to system");
7566 }
7567
7568 boolean killed = false;
7569 synchronized (mPidsSelfLocked) {
7570 final int size = mPidsSelfLocked.size();
7571 for (int i = 0; i < size; i++) {
7572 final int pid = mPidsSelfLocked.keyAt(i);
7573 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7574 if (proc == null) continue;
7575
7576 final int adj = proc.setAdj;
7577 if (adj > belowAdj && !proc.killedBackground) {
7578 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007579 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7580 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007581 killed = true;
7582 proc.killedBackground = true;
7583 Process.killProcessQuiet(pid);
7584 }
7585 }
7586 }
7587 return killed;
7588 }
7589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 public final void startRunning(String pkg, String cls, String action,
7591 String data) {
7592 synchronized(this) {
7593 if (mStartRunning) {
7594 return;
7595 }
7596 mStartRunning = true;
7597 mTopComponent = pkg != null && cls != null
7598 ? new ComponentName(pkg, cls) : null;
7599 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7600 mTopData = data;
7601 if (!mSystemReady) {
7602 return;
7603 }
7604 }
7605
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007606 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 }
7608
7609 private void retrieveSettings() {
7610 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007611 String debugApp = Settings.Global.getString(
7612 resolver, Settings.Global.DEBUG_APP);
7613 boolean waitForDebugger = Settings.Global.getInt(
7614 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7615 boolean alwaysFinishActivities = Settings.Global.getInt(
7616 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617
7618 Configuration configuration = new Configuration();
7619 Settings.System.getConfiguration(resolver, configuration);
7620
7621 synchronized (this) {
7622 mDebugApp = mOrigDebugApp = debugApp;
7623 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7624 mAlwaysFinishActivities = alwaysFinishActivities;
7625 // This happens before any activities are started, so we can
7626 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007627 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007628 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 }
7630 }
7631
7632 public boolean testIsSystemReady() {
7633 // no need to synchronize(this) just to read & return the value
7634 return mSystemReady;
7635 }
7636
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007637 private static File getCalledPreBootReceiversFile() {
7638 File dataDir = Environment.getDataDirectory();
7639 File systemDir = new File(dataDir, "system");
7640 File fname = new File(systemDir, "called_pre_boots.dat");
7641 return fname;
7642 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007643
7644 static final int LAST_DONE_VERSION = 10000;
7645
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007646 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7647 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7648 File file = getCalledPreBootReceiversFile();
7649 FileInputStream fis = null;
7650 try {
7651 fis = new FileInputStream(file);
7652 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007653 int fvers = dis.readInt();
7654 if (fvers == LAST_DONE_VERSION) {
7655 String vers = dis.readUTF();
7656 String codename = dis.readUTF();
7657 String build = dis.readUTF();
7658 if (android.os.Build.VERSION.RELEASE.equals(vers)
7659 && android.os.Build.VERSION.CODENAME.equals(codename)
7660 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7661 int num = dis.readInt();
7662 while (num > 0) {
7663 num--;
7664 String pkg = dis.readUTF();
7665 String cls = dis.readUTF();
7666 lastDoneReceivers.add(new ComponentName(pkg, cls));
7667 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007668 }
7669 }
7670 } catch (FileNotFoundException e) {
7671 } catch (IOException e) {
7672 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7673 } finally {
7674 if (fis != null) {
7675 try {
7676 fis.close();
7677 } catch (IOException e) {
7678 }
7679 }
7680 }
7681 return lastDoneReceivers;
7682 }
7683
7684 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7685 File file = getCalledPreBootReceiversFile();
7686 FileOutputStream fos = null;
7687 DataOutputStream dos = null;
7688 try {
7689 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7690 fos = new FileOutputStream(file);
7691 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007692 dos.writeInt(LAST_DONE_VERSION);
7693 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007694 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007695 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007696 dos.writeInt(list.size());
7697 for (int i=0; i<list.size(); i++) {
7698 dos.writeUTF(list.get(i).getPackageName());
7699 dos.writeUTF(list.get(i).getClassName());
7700 }
7701 } catch (IOException e) {
7702 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7703 file.delete();
7704 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007705 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007706 if (dos != null) {
7707 try {
7708 dos.close();
7709 } catch (IOException e) {
7710 // TODO Auto-generated catch block
7711 e.printStackTrace();
7712 }
7713 }
7714 }
7715 }
7716
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007717 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 synchronized(this) {
7719 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007720 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 return;
7722 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007723
7724 // Check to see if there are any update receivers to run.
7725 if (!mDidUpdate) {
7726 if (mWaitingUpdate) {
7727 return;
7728 }
7729 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7730 List<ResolveInfo> ris = null;
7731 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007732 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007733 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007734 } catch (RemoteException e) {
7735 }
7736 if (ris != null) {
7737 for (int i=ris.size()-1; i>=0; i--) {
7738 if ((ris.get(i).activityInfo.applicationInfo.flags
7739 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7740 ris.remove(i);
7741 }
7742 }
7743 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007744
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007745 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007746
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007747 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007748 for (int i=0; i<ris.size(); i++) {
7749 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007750 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7751 if (lastDoneReceivers.contains(comp)) {
7752 ris.remove(i);
7753 i--;
7754 }
7755 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007756
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007757 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007758 for (int i=0; i<ris.size(); i++) {
7759 ActivityInfo ai = ris.get(i).activityInfo;
7760 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7761 doneReceivers.add(comp);
7762 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007763 for (int j=0; j<users.length; j++) {
7764 IIntentReceiver finisher = null;
7765 if (i == ris.size()-1 && j == users.length-1) {
7766 finisher = new IIntentReceiver.Stub() {
7767 public void performReceive(Intent intent, int resultCode,
7768 String data, Bundle extras, boolean ordered,
7769 boolean sticky, int sendingUser) {
7770 // The raw IIntentReceiver interface is called
7771 // with the AM lock held, so redispatch to
7772 // execute our code without the lock.
7773 mHandler.post(new Runnable() {
7774 public void run() {
7775 synchronized (ActivityManagerService.this) {
7776 mDidUpdate = true;
7777 }
7778 writeLastDonePreBootReceivers(doneReceivers);
7779 showBootMessage(mContext.getText(
7780 R.string.android_upgrading_complete),
7781 false);
7782 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007783 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007784 });
7785 }
7786 };
7787 }
7788 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7789 + " for user " + users[j]);
7790 broadcastIntentLocked(null, null, intent, null, finisher,
7791 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7792 users[j]);
7793 if (finisher != null) {
7794 mWaitingUpdate = true;
7795 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007796 }
7797 }
7798 }
7799 if (mWaitingUpdate) {
7800 return;
7801 }
7802 mDidUpdate = true;
7803 }
7804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 mSystemReady = true;
7806 if (!mStartRunning) {
7807 return;
7808 }
7809 }
7810
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007811 ArrayList<ProcessRecord> procsToKill = null;
7812 synchronized(mPidsSelfLocked) {
7813 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7814 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7815 if (!isAllowedWhileBooting(proc.info)){
7816 if (procsToKill == null) {
7817 procsToKill = new ArrayList<ProcessRecord>();
7818 }
7819 procsToKill.add(proc);
7820 }
7821 }
7822 }
7823
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007824 synchronized(this) {
7825 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007826 for (int i=procsToKill.size()-1; i>=0; i--) {
7827 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007828 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007829 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007830 }
7831 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007832
7833 // Now that we have cleaned up any update processes, we
7834 // are ready to start launching real processes and know that
7835 // we won't trample on them any more.
7836 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007837 }
7838
Joe Onorato8a9b2202010-02-26 18:56:32 -08007839 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007840 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 SystemClock.uptimeMillis());
7842
7843 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007844 // Make sure we have no pre-ready processes sitting around.
7845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7847 ResolveInfo ri = mContext.getPackageManager()
7848 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007849 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 CharSequence errorMsg = null;
7851 if (ri != null) {
7852 ActivityInfo ai = ri.activityInfo;
7853 ApplicationInfo app = ai.applicationInfo;
7854 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7855 mTopAction = Intent.ACTION_FACTORY_TEST;
7856 mTopData = null;
7857 mTopComponent = new ComponentName(app.packageName,
7858 ai.name);
7859 } else {
7860 errorMsg = mContext.getResources().getText(
7861 com.android.internal.R.string.factorytest_not_system);
7862 }
7863 } else {
7864 errorMsg = mContext.getResources().getText(
7865 com.android.internal.R.string.factorytest_no_action);
7866 }
7867 if (errorMsg != null) {
7868 mTopAction = null;
7869 mTopData = null;
7870 mTopComponent = null;
7871 Message msg = Message.obtain();
7872 msg.what = SHOW_FACTORY_ERROR_MSG;
7873 msg.getData().putCharSequence("msg", errorMsg);
7874 mHandler.sendMessage(msg);
7875 }
7876 }
7877 }
7878
7879 retrieveSettings();
7880
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007881 if (goingCallback != null) goingCallback.run();
7882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 synchronized (this) {
7884 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7885 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007886 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007887 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 if (apps != null) {
7889 int N = apps.size();
7890 int i;
7891 for (i=0; i<N; i++) {
7892 ApplicationInfo info
7893 = (ApplicationInfo)apps.get(i);
7894 if (info != null &&
7895 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007896 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 }
7898 }
7899 }
7900 } catch (RemoteException ex) {
7901 // pm is in same process, this will never happen.
7902 }
7903 }
7904
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007905 // Start up initial activity.
7906 mBooting = true;
7907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007909 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 Message msg = Message.obtain();
7911 msg.what = SHOW_UID_ERROR_MSG;
7912 mHandler.sendMessage(msg);
7913 }
7914 } catch (RemoteException e) {
7915 }
7916
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007917 long ident = Binder.clearCallingIdentity();
7918 try {
7919 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007920 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7921 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007922 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7923 broadcastIntentLocked(null, null, intent,
7924 null, null, 0, null, null, null,
7925 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07007926 intent = new Intent(Intent.ACTION_USER_STARTING);
7927 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7928 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7929 broadcastIntentLocked(null, null, intent,
7930 null, new IIntentReceiver.Stub() {
7931 @Override
7932 public void performReceive(Intent intent, int resultCode, String data,
7933 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
7934 throws RemoteException {
7935 }
7936 }, 0, null, null,
7937 android.Manifest.permission.INTERACT_ACROSS_USERS,
7938 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007939 } finally {
7940 Binder.restoreCallingIdentity(ident);
7941 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007942 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007943 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 }
7945 }
7946
Dan Egnorb7f03672009-12-09 16:22:32 -08007947 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007948 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007950 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007951 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 startAppProblemLocked(app);
7953 app.stopFreezingAllLocked();
7954 return handleAppCrashLocked(app);
7955 }
7956
Dan Egnorb7f03672009-12-09 16:22:32 -08007957 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007958 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007960 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007961 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7962 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 startAppProblemLocked(app);
7964 app.stopFreezingAllLocked();
7965 }
7966
7967 /**
7968 * Generate a process error record, suitable for attachment to a ProcessRecord.
7969 *
7970 * @param app The ProcessRecord in which the error occurred.
7971 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7972 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007973 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 * @param shortMsg Short message describing the crash.
7975 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007976 * @param stackTrace Full crash stack trace, may be null.
7977 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 * @return Returns a fully-formed AppErrorStateInfo record.
7979 */
7980 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007981 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 report.condition = condition;
7985 report.processName = app.processName;
7986 report.pid = app.pid;
7987 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007988 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989 report.shortMsg = shortMsg;
7990 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007991 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992
7993 return report;
7994 }
7995
Dan Egnor42471dd2010-01-07 17:25:22 -08007996 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 synchronized (this) {
7998 app.crashing = false;
7999 app.crashingReport = null;
8000 app.notResponding = false;
8001 app.notRespondingReport = null;
8002 if (app.anrDialog == fromDialog) {
8003 app.anrDialog = null;
8004 }
8005 if (app.waitDialog == fromDialog) {
8006 app.waitDialog = null;
8007 }
8008 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008009 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008010 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008011 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008012 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008013 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 }
8016 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008017
Dan Egnorb7f03672009-12-09 16:22:32 -08008018 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008019 if (mHeadless) {
8020 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8021 return false;
8022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 long now = SystemClock.uptimeMillis();
8024
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008025 Long crashTime;
8026 if (!app.isolated) {
8027 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8028 } else {
8029 crashTime = null;
8030 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008031 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008033 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008035 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008036 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008037 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8038 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008039 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008040 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008042 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8043 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 }
8045 }
8046 if (!app.persistent) {
8047 // We don't want to start this process again until the user
8048 // explicitly does so... but for persistent process, we really
8049 // need to keep it running. If a persistent process is actually
8050 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008051 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008053 if (!app.isolated) {
8054 // XXX We don't have a way to mark isolated processes
8055 // as bad, since they don't have a peristent identity.
8056 mBadProcesses.put(app.info.processName, app.uid, now);
8057 mProcessCrashTimes.remove(app.info.processName, app.uid);
8058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008059 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008061 // Don't let services in this process be restarted and potentially
8062 // annoy the user repeatedly. Unless it is persistent, since those
8063 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008064 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008065 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008066 return false;
8067 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008068 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008069 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008070 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008071 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008072 // If the top running activity is from this crashing
8073 // process, then terminate it to avoid getting in a loop.
8074 Slog.w(TAG, " Force finishing activity "
8075 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008076 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008077 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008078 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008079 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008080 // stopped, to avoid a situation where one will get
8081 // re-start our crashing activity once it gets resumed again.
8082 index--;
8083 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008084 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008085 if (r.state == ActivityState.RESUMED
8086 || r.state == ActivityState.PAUSING
8087 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008088 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008089 Slog.w(TAG, " Force finishing activity "
8090 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008091 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008092 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008093 }
8094 }
8095 }
8096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 }
8098
8099 // Bump up the crash count of any services currently running in the proc.
8100 if (app.services.size() != 0) {
8101 // Any services running in the application need to be placed
8102 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008103 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008105 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 sr.crashCount++;
8107 }
8108 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008109
8110 // If the crashing process is what we consider to be the "home process" and it has been
8111 // replaced by a third-party app, clear the package preferred activities from packages
8112 // with a home activity running in the process to prevent a repeatedly crashing app
8113 // from blocking the user to manually clear the list.
8114 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8115 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8116 Iterator it = mHomeProcess.activities.iterator();
8117 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008118 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008119 if (r.isHomeActivity) {
8120 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8121 try {
8122 ActivityThread.getPackageManager()
8123 .clearPackagePreferredActivities(r.packageName);
8124 } catch (RemoteException c) {
8125 // pm is in same process, this will never happen.
8126 }
8127 }
8128 }
8129 }
8130
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008131 if (!app.isolated) {
8132 // XXX Can't keep track of crash times for isolated processes,
8133 // because they don't have a perisistent identity.
8134 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8135 }
8136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 return true;
8138 }
8139
8140 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008141 if (app.userId == mCurrentUserId) {
8142 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8143 mContext, app.info.packageName, app.info.flags);
8144 } else {
8145 // If this app is not running under the current user, then we
8146 // can't give it a report button because that would require
8147 // launching the report UI under a different user.
8148 app.errorReportReceiver = null;
8149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 skipCurrentReceiverLocked(app);
8151 }
8152
8153 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008154 for (BroadcastQueue queue : mBroadcastQueues) {
8155 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 }
8157 }
8158
Dan Egnor60d87622009-12-16 16:32:58 -08008159 /**
8160 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8161 * The application process will exit immediately after this call returns.
8162 * @param app object of the crashing app, null for the system server
8163 * @param crashInfo describing the exception
8164 */
8165 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008166 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008167 final String processName = app == null ? "system_server"
8168 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008169
8170 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008171 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008172 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008173 crashInfo.exceptionClassName,
8174 crashInfo.exceptionMessage,
8175 crashInfo.throwFileName,
8176 crashInfo.throwLineNumber);
8177
Jeff Sharkeya353d262011-10-28 11:12:06 -07008178 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008179
8180 crashApplication(r, crashInfo);
8181 }
8182
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008183 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008184 IBinder app,
8185 int violationMask,
8186 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008187 ProcessRecord r = findAppProcess(app, "StrictMode");
8188 if (r == null) {
8189 return;
8190 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008191
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008192 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008193 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008194 boolean logIt = true;
8195 synchronized (mAlreadyLoggedViolatedStacks) {
8196 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8197 logIt = false;
8198 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008199 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008200 // the relative pain numbers, without logging all
8201 // the stack traces repeatedly. We'd want to do
8202 // likewise in the client code, which also does
8203 // dup suppression, before the Binder call.
8204 } else {
8205 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8206 mAlreadyLoggedViolatedStacks.clear();
8207 }
8208 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8209 }
8210 }
8211 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008212 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008213 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008214 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008215
8216 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8217 AppErrorResult result = new AppErrorResult();
8218 synchronized (this) {
8219 final long origId = Binder.clearCallingIdentity();
8220
8221 Message msg = Message.obtain();
8222 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8223 HashMap<String, Object> data = new HashMap<String, Object>();
8224 data.put("result", result);
8225 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008226 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008227 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008228 msg.obj = data;
8229 mHandler.sendMessage(msg);
8230
8231 Binder.restoreCallingIdentity(origId);
8232 }
8233 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008234 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008235 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008236 }
8237
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008238 // Depending on the policy in effect, there could be a bunch of
8239 // these in quick succession so we try to batch these together to
8240 // minimize disk writes, number of dropbox entries, and maximize
8241 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008242 private void logStrictModeViolationToDropBox(
8243 ProcessRecord process,
8244 StrictMode.ViolationInfo info) {
8245 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008246 return;
8247 }
8248 final boolean isSystemApp = process == null ||
8249 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8250 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008251 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008252 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8253 final DropBoxManager dbox = (DropBoxManager)
8254 mContext.getSystemService(Context.DROPBOX_SERVICE);
8255
8256 // Exit early if the dropbox isn't configured to accept this report type.
8257 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8258
8259 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008260 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008261 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8262 synchronized (sb) {
8263 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008264 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008265 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8266 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008267 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8268 if (info.violationNumThisLoop != 0) {
8269 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8270 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008271 if (info.numAnimationsRunning != 0) {
8272 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8273 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008274 if (info.broadcastIntentAction != null) {
8275 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8276 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008277 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008278 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008279 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008280 if (info.numInstances != -1) {
8281 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8282 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008283 if (info.tags != null) {
8284 for (String tag : info.tags) {
8285 sb.append("Span-Tag: ").append(tag).append("\n");
8286 }
8287 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008288 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008289 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8290 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008291 }
8292 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008293
8294 // Only buffer up to ~64k. Various logging bits truncate
8295 // things at 128k.
8296 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008297 }
8298
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008299 // Flush immediately if the buffer's grown too large, or this
8300 // is a non-system app. Non-system apps are isolated with a
8301 // different tag & policy and not batched.
8302 //
8303 // Batching is useful during internal testing with
8304 // StrictMode settings turned up high. Without batching,
8305 // thousands of separate files could be created on boot.
8306 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008307 new Thread("Error dump: " + dropboxTag) {
8308 @Override
8309 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008310 String report;
8311 synchronized (sb) {
8312 report = sb.toString();
8313 sb.delete(0, sb.length());
8314 sb.trimToSize();
8315 }
8316 if (report.length() != 0) {
8317 dbox.addText(dropboxTag, report);
8318 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008319 }
8320 }.start();
8321 return;
8322 }
8323
8324 // System app batching:
8325 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008326 // An existing dropbox-writing thread is outstanding, so
8327 // we don't need to start it up. The existing thread will
8328 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008329 return;
8330 }
8331
8332 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8333 // (After this point, we shouldn't access AMS internal data structures.)
8334 new Thread("Error dump: " + dropboxTag) {
8335 @Override
8336 public void run() {
8337 // 5 second sleep to let stacks arrive and be batched together
8338 try {
8339 Thread.sleep(5000); // 5 seconds
8340 } catch (InterruptedException e) {}
8341
8342 String errorReport;
8343 synchronized (mStrictModeBuffer) {
8344 errorReport = mStrictModeBuffer.toString();
8345 if (errorReport.length() == 0) {
8346 return;
8347 }
8348 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8349 mStrictModeBuffer.trimToSize();
8350 }
8351 dbox.addText(dropboxTag, errorReport);
8352 }
8353 }.start();
8354 }
8355
Dan Egnor60d87622009-12-16 16:32:58 -08008356 /**
8357 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8358 * @param app object of the crashing app, null for the system server
8359 * @param tag reported by the caller
8360 * @param crashInfo describing the context of the error
8361 * @return true if the process should exit immediately (WTF is fatal)
8362 */
8363 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008364 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008365 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008366 final String processName = app == null ? "system_server"
8367 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008368
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008369 EventLog.writeEvent(EventLogTags.AM_WTF,
8370 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008371 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008372 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008373 tag, crashInfo.exceptionMessage);
8374
Jeff Sharkeya353d262011-10-28 11:12:06 -07008375 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008376
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008377 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008378 Settings.Global.getInt(mContext.getContentResolver(),
8379 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008380 crashApplication(r, crashInfo);
8381 return true;
8382 } else {
8383 return false;
8384 }
8385 }
8386
8387 /**
8388 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8389 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8390 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008391 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008392 if (app == null) {
8393 return null;
8394 }
8395
8396 synchronized (this) {
8397 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8398 final int NA = apps.size();
8399 for (int ia=0; ia<NA; ia++) {
8400 ProcessRecord p = apps.valueAt(ia);
8401 if (p.thread != null && p.thread.asBinder() == app) {
8402 return p;
8403 }
8404 }
8405 }
8406
Dianne Hackborncb44d962011-03-10 17:02:27 -08008407 Slog.w(TAG, "Can't find mystery application for " + reason
8408 + " from pid=" + Binder.getCallingPid()
8409 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008410 return null;
8411 }
8412 }
8413
8414 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008415 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8416 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008417 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008418 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8419 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008420 // Watchdog thread ends up invoking this function (with
8421 // a null ProcessRecord) to add the stack file to dropbox.
8422 // Do not acquire a lock on this (am) in such cases, as it
8423 // could cause a potential deadlock, if and when watchdog
8424 // is invoked due to unavailability of lock on am and it
8425 // would prevent watchdog from killing system_server.
8426 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008427 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008428 return;
8429 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008430 // Note: ProcessRecord 'process' is guarded by the service
8431 // instance. (notably process.pkgList, which could otherwise change
8432 // concurrently during execution of this method)
8433 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008434 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008435 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008436 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008437 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8438 for (String pkg : process.pkgList) {
8439 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008440 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008441 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008442 if (pi != null) {
8443 sb.append(" v").append(pi.versionCode);
8444 if (pi.versionName != null) {
8445 sb.append(" (").append(pi.versionName).append(")");
8446 }
8447 }
8448 } catch (RemoteException e) {
8449 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008450 }
Dan Egnora455d192010-03-12 08:52:28 -08008451 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008452 }
Dan Egnora455d192010-03-12 08:52:28 -08008453 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008454 }
8455
8456 private static String processClass(ProcessRecord process) {
8457 if (process == null || process.pid == MY_PID) {
8458 return "system_server";
8459 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8460 return "system_app";
8461 } else {
8462 return "data_app";
8463 }
8464 }
8465
8466 /**
8467 * Write a description of an error (crash, WTF, ANR) to the drop box.
8468 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8469 * @param process which caused the error, null means the system server
8470 * @param activity which triggered the error, null if unknown
8471 * @param parent activity related to the error, null if unknown
8472 * @param subject line related to the error, null if absent
8473 * @param report in long form describing the error, null if absent
8474 * @param logFile to include in the report, null if none
8475 * @param crashInfo giving an application stack trace, null if absent
8476 */
8477 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008478 ProcessRecord process, String processName, ActivityRecord activity,
8479 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008480 final String report, final File logFile,
8481 final ApplicationErrorReport.CrashInfo crashInfo) {
8482 // NOTE -- this must never acquire the ActivityManagerService lock,
8483 // otherwise the watchdog may be prevented from resetting the system.
8484
8485 final String dropboxTag = processClass(process) + "_" + eventType;
8486 final DropBoxManager dbox = (DropBoxManager)
8487 mContext.getSystemService(Context.DROPBOX_SERVICE);
8488
8489 // Exit early if the dropbox isn't configured to accept this report type.
8490 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8491
8492 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008493 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008494 if (activity != null) {
8495 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8496 }
8497 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8498 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8499 }
8500 if (parent != null && parent != activity) {
8501 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8502 }
8503 if (subject != null) {
8504 sb.append("Subject: ").append(subject).append("\n");
8505 }
8506 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008507 if (Debug.isDebuggerConnected()) {
8508 sb.append("Debugger: Connected\n");
8509 }
Dan Egnora455d192010-03-12 08:52:28 -08008510 sb.append("\n");
8511
8512 // Do the rest in a worker thread to avoid blocking the caller on I/O
8513 // (After this point, we shouldn't access AMS internal data structures.)
8514 Thread worker = new Thread("Error dump: " + dropboxTag) {
8515 @Override
8516 public void run() {
8517 if (report != null) {
8518 sb.append(report);
8519 }
8520 if (logFile != null) {
8521 try {
8522 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8523 } catch (IOException e) {
8524 Slog.e(TAG, "Error reading " + logFile, e);
8525 }
8526 }
8527 if (crashInfo != null && crashInfo.stackTrace != null) {
8528 sb.append(crashInfo.stackTrace);
8529 }
8530
Jeff Sharkey625239a2012-09-26 22:03:49 -07008531 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8532 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008533 if (lines > 0) {
8534 sb.append("\n");
8535
8536 // Merge several logcat streams, and take the last N lines
8537 InputStreamReader input = null;
8538 try {
8539 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8540 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8541 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8542
8543 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8544 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8545 input = new InputStreamReader(logcat.getInputStream());
8546
8547 int num;
8548 char[] buf = new char[8192];
8549 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8550 } catch (IOException e) {
8551 Slog.e(TAG, "Error running logcat", e);
8552 } finally {
8553 if (input != null) try { input.close(); } catch (IOException e) {}
8554 }
8555 }
8556
8557 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008558 }
Dan Egnora455d192010-03-12 08:52:28 -08008559 };
8560
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008561 if (process == null) {
8562 // If process is null, we are being called from some internal code
8563 // and may be about to die -- run this synchronously.
8564 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008565 } else {
8566 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008567 }
8568 }
8569
8570 /**
8571 * Bring up the "unexpected error" dialog box for a crashing app.
8572 * Deal with edge cases (intercepts from instrumented applications,
8573 * ActivityController, error intent receivers, that sort of thing).
8574 * @param r the application crashing
8575 * @param crashInfo describing the failure
8576 */
8577 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008578 long timeMillis = System.currentTimeMillis();
8579 String shortMsg = crashInfo.exceptionClassName;
8580 String longMsg = crashInfo.exceptionMessage;
8581 String stackTrace = crashInfo.stackTrace;
8582 if (shortMsg != null && longMsg != null) {
8583 longMsg = shortMsg + ": " + longMsg;
8584 } else if (shortMsg != null) {
8585 longMsg = shortMsg;
8586 }
8587
Dan Egnor60d87622009-12-16 16:32:58 -08008588 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008590 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 try {
8592 String name = r != null ? r.processName : null;
8593 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008594 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008595 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008596 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008597 + " at watcher's request");
8598 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008599 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008600 }
8601 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008602 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008603 }
8604 }
8605
8606 final long origId = Binder.clearCallingIdentity();
8607
8608 // If this process is running instrumentation, finish it.
8609 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008610 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008612 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8613 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 Bundle info = new Bundle();
8615 info.putString("shortMsg", shortMsg);
8616 info.putString("longMsg", longMsg);
8617 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8618 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008619 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 }
8621
Dan Egnor60d87622009-12-16 16:32:58 -08008622 // If we can't identify the process or it's already exceeded its crash quota,
8623 // quit right away without showing a crash dialog.
8624 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008626 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 }
8628
8629 Message msg = Message.obtain();
8630 msg.what = SHOW_ERROR_MSG;
8631 HashMap data = new HashMap();
8632 data.put("result", result);
8633 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 msg.obj = data;
8635 mHandler.sendMessage(msg);
8636
8637 Binder.restoreCallingIdentity(origId);
8638 }
8639
8640 int res = result.get();
8641
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008642 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008644 if (r != null && !r.isolated) {
8645 // XXX Can't keep track of crash time for isolated processes,
8646 // since they don't have a persistent identity.
8647 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 SystemClock.uptimeMillis());
8649 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008650 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008651 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008652 }
8653 }
8654
8655 if (appErrorIntent != null) {
8656 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008657 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008658 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008659 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008663
8664 Intent createAppErrorIntentLocked(ProcessRecord r,
8665 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8666 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008667 if (report == null) {
8668 return null;
8669 }
8670 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8671 result.setComponent(r.errorReportReceiver);
8672 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8673 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8674 return result;
8675 }
8676
Dan Egnorb7f03672009-12-09 16:22:32 -08008677 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8678 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008679 if (r.errorReportReceiver == null) {
8680 return null;
8681 }
8682
8683 if (!r.crashing && !r.notResponding) {
8684 return null;
8685 }
8686
Dan Egnorb7f03672009-12-09 16:22:32 -08008687 ApplicationErrorReport report = new ApplicationErrorReport();
8688 report.packageName = r.info.packageName;
8689 report.installerPackageName = r.errorReportReceiver.getPackageName();
8690 report.processName = r.processName;
8691 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008692 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008693
Dan Egnorb7f03672009-12-09 16:22:32 -08008694 if (r.crashing) {
8695 report.type = ApplicationErrorReport.TYPE_CRASH;
8696 report.crashInfo = crashInfo;
8697 } else if (r.notResponding) {
8698 report.type = ApplicationErrorReport.TYPE_ANR;
8699 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008700
Dan Egnorb7f03672009-12-09 16:22:32 -08008701 report.anrInfo.activity = r.notRespondingReport.tag;
8702 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8703 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008704 }
8705
Dan Egnorb7f03672009-12-09 16:22:32 -08008706 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008707 }
8708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008710 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 // assume our apps are happy - lazy create the list
8712 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8713
Dianne Hackborn0c380492012-08-20 17:23:30 -07008714 final boolean allUsers = ActivityManager.checkUidPermission(
8715 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8716 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8717 int userId = UserHandle.getUserId(Binder.getCallingUid());
8718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 synchronized (this) {
8720
8721 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008722 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8723 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008724 if (!allUsers && app.userId != userId) {
8725 continue;
8726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8728 // This one's in trouble, so we'll generate a report for it
8729 // crashes are higher priority (in case there's a crash *and* an anr)
8730 ActivityManager.ProcessErrorStateInfo report = null;
8731 if (app.crashing) {
8732 report = app.crashingReport;
8733 } else if (app.notResponding) {
8734 report = app.notRespondingReport;
8735 }
8736
8737 if (report != null) {
8738 if (errList == null) {
8739 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8740 }
8741 errList.add(report);
8742 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008743 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744 " crashing = " + app.crashing +
8745 " notResponding = " + app.notResponding);
8746 }
8747 }
8748 }
8749 }
8750
8751 return errList;
8752 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008753
8754 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008755 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008756 if (currApp != null) {
8757 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8758 }
8759 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008760 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8761 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008762 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8763 if (currApp != null) {
8764 currApp.lru = 0;
8765 }
8766 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008767 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008768 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8769 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8770 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8771 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8772 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8773 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8774 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8775 } else {
8776 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8777 }
8778 }
8779
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008780 private void fillInProcMemInfo(ProcessRecord app,
8781 ActivityManager.RunningAppProcessInfo outInfo) {
8782 outInfo.pid = app.pid;
8783 outInfo.uid = app.info.uid;
8784 if (mHeavyWeightProcess == app) {
8785 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8786 }
8787 if (app.persistent) {
8788 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8789 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008790 if (app.hasActivities) {
8791 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8792 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008793 outInfo.lastTrimLevel = app.trimMemoryLevel;
8794 int adj = app.curAdj;
8795 outInfo.importance = oomAdjToImportance(adj, outInfo);
8796 outInfo.importanceReasonCode = app.adjTypeCode;
8797 }
8798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008800 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 // Lazy instantiation of list
8802 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008803 final boolean allUsers = ActivityManager.checkUidPermission(
8804 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8805 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8806 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 synchronized (this) {
8808 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008809 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8810 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008811 if (!allUsers && app.userId != userId) {
8812 continue;
8813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008814 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8815 // Generate process state info for running application
8816 ActivityManager.RunningAppProcessInfo currApp =
8817 new ActivityManager.RunningAppProcessInfo(app.processName,
8818 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008819 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008820 if (app.adjSource instanceof ProcessRecord) {
8821 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008822 currApp.importanceReasonImportance = oomAdjToImportance(
8823 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008824 } else if (app.adjSource instanceof ActivityRecord) {
8825 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008826 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8827 }
8828 if (app.adjTarget instanceof ComponentName) {
8829 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8830 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008831 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 // + " lru=" + currApp.lru);
8833 if (runList == null) {
8834 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8835 }
8836 runList.add(currApp);
8837 }
8838 }
8839 }
8840 return runList;
8841 }
8842
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008843 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008844 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008845 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8846 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8847 if (runningApps != null && runningApps.size() > 0) {
8848 Set<String> extList = new HashSet<String>();
8849 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8850 if (app.pkgList != null) {
8851 for (String pkg : app.pkgList) {
8852 extList.add(pkg);
8853 }
8854 }
8855 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008856 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008857 for (String pkg : extList) {
8858 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008859 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008860 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8861 retList.add(info);
8862 }
8863 } catch (RemoteException e) {
8864 }
8865 }
8866 }
8867 return retList;
8868 }
8869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008871 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8872 enforceNotIsolatedCaller("getMyMemoryState");
8873 synchronized (this) {
8874 ProcessRecord proc;
8875 synchronized (mPidsSelfLocked) {
8876 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8877 }
8878 fillInProcMemInfo(proc, outInfo);
8879 }
8880 }
8881
8882 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008884 if (checkCallingPermission(android.Manifest.permission.DUMP)
8885 != PackageManager.PERMISSION_GRANTED) {
8886 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8887 + Binder.getCallingPid()
8888 + ", uid=" + Binder.getCallingUid()
8889 + " without permission "
8890 + android.Manifest.permission.DUMP);
8891 return;
8892 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008893
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008894 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008895 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008896 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008897
8898 int opti = 0;
8899 while (opti < args.length) {
8900 String opt = args[opti];
8901 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8902 break;
8903 }
8904 opti++;
8905 if ("-a".equals(opt)) {
8906 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008907 } else if ("-c".equals(opt)) {
8908 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008909 } else if ("-h".equals(opt)) {
8910 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008911 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008912 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008913 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008914 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008915 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8916 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008917 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008918 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008919 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008920 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008921 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008922 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008923 pw.println(" all: dump all activities");
8924 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008925 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008926 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8927 pw.println(" a partial substring in a component name, a");
8928 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008929 pw.println(" -a: include all available server state.");
8930 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008932 } else {
8933 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008936
8937 long origId = Binder.clearCallingIdentity();
8938 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008939 // Is the caller requesting to dump a particular piece of data?
8940 if (opti < args.length) {
8941 String cmd = args[opti];
8942 opti++;
8943 if ("activities".equals(cmd) || "a".equals(cmd)) {
8944 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008945 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008947 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008948 String[] newArgs;
8949 String name;
8950 if (opti >= args.length) {
8951 name = null;
8952 newArgs = EMPTY_STRING_ARRAY;
8953 } else {
8954 name = args[opti];
8955 opti++;
8956 newArgs = new String[args.length - opti];
8957 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8958 args.length - opti);
8959 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008960 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008961 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008962 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008963 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008964 String[] newArgs;
8965 String name;
8966 if (opti >= args.length) {
8967 name = null;
8968 newArgs = EMPTY_STRING_ARRAY;
8969 } else {
8970 name = args[opti];
8971 opti++;
8972 newArgs = new String[args.length - opti];
8973 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8974 args.length - opti);
8975 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008976 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008977 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008978 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008979 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008980 String[] newArgs;
8981 String name;
8982 if (opti >= args.length) {
8983 name = null;
8984 newArgs = EMPTY_STRING_ARRAY;
8985 } else {
8986 name = args[opti];
8987 opti++;
8988 newArgs = new String[args.length - opti];
8989 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8990 args.length - opti);
8991 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008994 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008995 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8996 synchronized (this) {
8997 dumpOomLocked(fd, pw, args, opti, true);
8998 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008999 } else if ("provider".equals(cmd)) {
9000 String[] newArgs;
9001 String name;
9002 if (opti >= args.length) {
9003 name = null;
9004 newArgs = EMPTY_STRING_ARRAY;
9005 } else {
9006 name = args[opti];
9007 opti++;
9008 newArgs = new String[args.length - opti];
9009 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9010 }
9011 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9012 pw.println("No providers match: " + name);
9013 pw.println("Use -h for help.");
9014 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9016 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009017 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009019 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009020 String[] newArgs;
9021 String name;
9022 if (opti >= args.length) {
9023 name = null;
9024 newArgs = EMPTY_STRING_ARRAY;
9025 } else {
9026 name = args[opti];
9027 opti++;
9028 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009029 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9030 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009031 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009032 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009033 pw.println("No services match: " + name);
9034 pw.println("Use -h for help.");
9035 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009036 } else if ("package".equals(cmd)) {
9037 String[] newArgs;
9038 if (opti >= args.length) {
9039 pw.println("package: no package name specified");
9040 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009041 } else {
9042 dumpPackage = args[opti];
9043 opti++;
9044 newArgs = new String[args.length - opti];
9045 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9046 args.length - opti);
9047 args = newArgs;
9048 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009049 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009050 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009051 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9052 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009053 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009054 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009055 } else {
9056 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9058 pw.println("Bad activity command, or no activities match: " + cmd);
9059 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009060 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009061 }
9062 if (!more) {
9063 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009064 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009066 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009067
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 // No piece of data specified, dump everything.
9069 synchronized (this) {
9070 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009071 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009072 if (needSep) {
9073 pw.println(" ");
9074 }
9075 if (dumpAll) {
9076 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009077 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009078 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009079 if (needSep) {
9080 pw.println(" ");
9081 }
9082 if (dumpAll) {
9083 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009084 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009085 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009086 if (needSep) {
9087 pw.println(" ");
9088 }
9089 if (dumpAll) {
9090 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009091 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009092 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009093 if (needSep) {
9094 pw.println(" ");
9095 }
9096 if (dumpAll) {
9097 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009098 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009099 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009100 if (needSep) {
9101 pw.println(" ");
9102 }
9103 if (dumpAll) {
9104 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009105 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009106 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009107 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009108 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009109 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009110
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009111 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009112 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009113 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9114 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009115 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9116 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009117 pw.println(" ");
9118 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009119 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9120 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009121 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009123 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009124 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009125 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009126 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009127 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009128 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009129 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009130 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009131 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009132 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009133 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9134 pw.println(" ");
9135 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009136 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009137 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009138 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009139 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009140 pw.println(" ");
9141 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009142 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009143 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009146 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009147 if (mMainStack.mPausingActivity != null) {
9148 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009149 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009150 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009151 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009152 if (dumpAll) {
9153 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9154 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009155 pw.println(" mDismissKeyguardOnNextActivity: "
9156 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009159 if (mRecentTasks.size() > 0) {
9160 pw.println();
9161 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009162
9163 final int N = mRecentTasks.size();
9164 for (int i=0; i<N; i++) {
9165 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009166 if (dumpPackage != null) {
9167 if (tr.realActivity == null ||
9168 !dumpPackage.equals(tr.realActivity)) {
9169 continue;
9170 }
9171 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009172 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9173 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009174 if (dumpAll) {
9175 mRecentTasks.get(i).dump(pw, " ");
9176 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177 }
9178 }
9179
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009180 if (dumpAll) {
9181 pw.println(" ");
9182 pw.println(" mCurTask: " + mCurTask);
9183 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009184
9185 return true;
9186 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009187
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009188 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009189 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009190 boolean needSep = false;
9191 int numPers = 0;
9192
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009193 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9194
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009195 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9197 final int NA = procs.size();
9198 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199 ProcessRecord r = procs.valueAt(ia);
9200 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9201 continue;
9202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009203 if (!needSep) {
9204 pw.println(" All known processes:");
9205 needSep = true;
9206 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009207 pw.print(r.persistent ? " *PERS*" : " *APP*");
9208 pw.print(" UID "); pw.print(procs.keyAt(ia));
9209 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210 r.dump(pw, " ");
9211 if (r.persistent) {
9212 numPers++;
9213 }
9214 }
9215 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009217
9218 if (mIsolatedProcesses.size() > 0) {
9219 if (needSep) pw.println(" ");
9220 needSep = true;
9221 pw.println(" Isolated process list (sorted by uid):");
9222 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9223 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9224 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9225 continue;
9226 }
9227 pw.println(String.format("%sIsolated #%2d: %s",
9228 " ", i, r.toString()));
9229 }
9230 }
9231
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009232 if (mLruProcesses.size() > 0) {
9233 if (needSep) pw.println(" ");
9234 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009235 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009236 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009237 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009238 needSep = true;
9239 }
9240
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009241 if (dumpAll) {
9242 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009243 boolean printed = false;
9244 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9245 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9246 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9247 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009248 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009249 if (!printed) {
9250 if (needSep) pw.println(" ");
9251 needSep = true;
9252 pw.println(" PID mappings:");
9253 printed = true;
9254 }
9255 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9256 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 }
9258 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009259 }
9260
9261 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009262 synchronized (mPidsSelfLocked) {
9263 boolean printed = false;
9264 for (int i=0; i<mForegroundProcesses.size(); i++) {
9265 ProcessRecord r = mPidsSelfLocked.get(
9266 mForegroundProcesses.valueAt(i).pid);
9267 if (dumpPackage != null && (r == null
9268 || !dumpPackage.equals(r.info.packageName))) {
9269 continue;
9270 }
9271 if (!printed) {
9272 if (needSep) pw.println(" ");
9273 needSep = true;
9274 pw.println(" Foreground Processes:");
9275 printed = true;
9276 }
9277 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9278 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 }
9282
9283 if (mPersistentStartingProcesses.size() > 0) {
9284 if (needSep) pw.println(" ");
9285 needSep = true;
9286 pw.println(" Persisent processes that are starting:");
9287 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009288 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009290
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009291 if (mRemovedProcesses.size() > 0) {
9292 if (needSep) pw.println(" ");
9293 needSep = true;
9294 pw.println(" Processes that are being removed:");
9295 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009296 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009297 }
9298
9299 if (mProcessesOnHold.size() > 0) {
9300 if (needSep) pw.println(" ");
9301 needSep = true;
9302 pw.println(" Processes that are on old until the system is ready:");
9303 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009304 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009307 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009308
9309 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 long now = SystemClock.uptimeMillis();
9312 for (Map.Entry<String, SparseArray<Long>> procs
9313 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009314 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009315 SparseArray<Long> uids = procs.getValue();
9316 final int N = uids.size();
9317 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009318 int puid = uids.keyAt(i);
9319 ProcessRecord r = mProcessNames.get(pname, puid);
9320 if (dumpPackage != null && (r == null
9321 || !dumpPackage.equals(r.info.packageName))) {
9322 continue;
9323 }
9324 if (!printed) {
9325 if (needSep) pw.println(" ");
9326 needSep = true;
9327 pw.println(" Time since processes crashed:");
9328 printed = true;
9329 }
9330 pw.print(" Process "); pw.print(pname);
9331 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009332 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009333 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9334 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009335 }
9336 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009339 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009340 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009341 for (Map.Entry<String, SparseArray<Long>> procs
9342 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009343 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009344 SparseArray<Long> uids = procs.getValue();
9345 final int N = uids.size();
9346 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009347 int puid = uids.keyAt(i);
9348 ProcessRecord r = mProcessNames.get(pname, puid);
9349 if (dumpPackage != null && (r == null
9350 || !dumpPackage.equals(r.info.packageName))) {
9351 continue;
9352 }
9353 if (!printed) {
9354 if (needSep) pw.println(" ");
9355 needSep = true;
9356 pw.println(" Bad processes:");
9357 }
9358 pw.print(" Bad process "); pw.print(pname);
9359 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009360 pw.print(": crashed at time ");
9361 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 }
9363 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009365
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009366 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009367 pw.println(" mStartedUsers:");
9368 for (int i=0; i<mStartedUsers.size(); i++) {
9369 UserStartedState uss = mStartedUsers.valueAt(i);
9370 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009371 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009372 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009373 pw.print(" mStartedUserArray: [");
9374 for (int i=0; i<mStartedUserArray.length; i++) {
9375 if (i > 0) pw.print(", ");
9376 pw.print(mStartedUserArray[i]);
9377 }
9378 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009379 pw.print(" mUserLru: [");
9380 for (int i=0; i<mUserLru.size(); i++) {
9381 if (i > 0) pw.print(", ");
9382 pw.print(mUserLru.get(i));
9383 }
9384 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009385 if (dumpAll) {
9386 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9387 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009389 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009390 if (dumpAll) {
9391 StringBuilder sb = new StringBuilder(128);
9392 sb.append(" mPreviousProcessVisibleTime: ");
9393 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9394 pw.println(sb);
9395 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009396 if (mHeavyWeightProcess != null) {
9397 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9398 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009399 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009400 if (dumpAll) {
9401 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009402 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009403 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009404 for (Map.Entry<String, Integer> entry
9405 : mCompatModePackages.getPackages().entrySet()) {
9406 String pkg = entry.getKey();
9407 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009408 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9409 continue;
9410 }
9411 if (!printed) {
9412 pw.println(" mScreenCompatPackages:");
9413 printed = true;
9414 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009415 pw.print(" "); pw.print(pkg); pw.print(": ");
9416 pw.print(mode); pw.println();
9417 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009418 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009420 if (mSleeping || mWentToSleep || mLockScreenShown) {
9421 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9422 + " mLockScreenShown " + mLockScreenShown);
9423 }
9424 if (mShuttingDown) {
9425 pw.println(" mShuttingDown=" + mShuttingDown);
9426 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009427 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9428 || mOrigWaitForDebugger) {
9429 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9430 + " mDebugTransient=" + mDebugTransient
9431 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9432 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009433 if (mOpenGlTraceApp != null) {
9434 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9435 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009436 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9437 || mProfileFd != null) {
9438 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9439 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9440 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9441 + mAutoStopProfiler);
9442 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009443 if (mAlwaysFinishActivities || mController != null) {
9444 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9445 + " mController=" + mController);
9446 }
9447 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009450 + " mProcessesReady=" + mProcessesReady
9451 + " mSystemReady=" + mSystemReady);
9452 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 + " mBooted=" + mBooted
9454 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009455 pw.print(" mLastPowerCheckRealtime=");
9456 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9457 pw.println("");
9458 pw.print(" mLastPowerCheckUptime=");
9459 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9460 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009461 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9462 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009463 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009464 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9465 + " mNumHiddenProcs=" + mNumHiddenProcs
9466 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009467 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009468 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009469
9470 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009471 }
9472
Dianne Hackborn287952c2010-09-22 22:34:31 -07009473 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009474 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009475 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009476 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009477 long now = SystemClock.uptimeMillis();
9478 for (int i=0; i<mProcessesToGc.size(); i++) {
9479 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009480 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9481 continue;
9482 }
9483 if (!printed) {
9484 if (needSep) pw.println(" ");
9485 needSep = true;
9486 pw.println(" Processes that are waiting to GC:");
9487 printed = true;
9488 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009489 pw.print(" Process "); pw.println(proc);
9490 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9491 pw.print(", last gced=");
9492 pw.print(now-proc.lastRequestedGc);
9493 pw.print(" ms ago, last lowMem=");
9494 pw.print(now-proc.lastLowMemory);
9495 pw.println(" ms ago");
9496
9497 }
9498 }
9499 return needSep;
9500 }
9501
9502 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9503 int opti, boolean dumpAll) {
9504 boolean needSep = false;
9505
9506 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009507 if (needSep) pw.println(" ");
9508 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009509 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009510 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009511 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009512 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9513 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9514 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9515 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9516 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009517 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009518 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009519 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009520 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009521 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009522 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009523
9524 if (needSep) pw.println(" ");
9525 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009526 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009527 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009528 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009529 needSep = true;
9530 }
9531
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009532 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009533
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009534 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009535 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009536 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009537 if (mHeavyWeightProcess != null) {
9538 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9539 }
9540
9541 return true;
9542 }
9543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544 /**
9545 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009546 * - no provider specified: dump all the providers
9547 * - a flattened component name that matched an existing provider was specified as the
9548 * first arg: dump that one provider
9549 * - the first arg isn't the flattened component name of an existing provider:
9550 * dump all providers whose component contains the first arg as a substring
9551 */
9552 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9553 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009554 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009555 }
9556
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009557 static class ItemMatcher {
9558 ArrayList<ComponentName> components;
9559 ArrayList<String> strings;
9560 ArrayList<Integer> objects;
9561 boolean all;
9562
9563 ItemMatcher() {
9564 all = true;
9565 }
9566
9567 void build(String name) {
9568 ComponentName componentName = ComponentName.unflattenFromString(name);
9569 if (componentName != null) {
9570 if (components == null) {
9571 components = new ArrayList<ComponentName>();
9572 }
9573 components.add(componentName);
9574 all = false;
9575 } else {
9576 int objectId = 0;
9577 // Not a '/' separated full component name; maybe an object ID?
9578 try {
9579 objectId = Integer.parseInt(name, 16);
9580 if (objects == null) {
9581 objects = new ArrayList<Integer>();
9582 }
9583 objects.add(objectId);
9584 all = false;
9585 } catch (RuntimeException e) {
9586 // Not an integer; just do string match.
9587 if (strings == null) {
9588 strings = new ArrayList<String>();
9589 }
9590 strings.add(name);
9591 all = false;
9592 }
9593 }
9594 }
9595
9596 int build(String[] args, int opti) {
9597 for (; opti<args.length; opti++) {
9598 String name = args[opti];
9599 if ("--".equals(name)) {
9600 return opti+1;
9601 }
9602 build(name);
9603 }
9604 return opti;
9605 }
9606
9607 boolean match(Object object, ComponentName comp) {
9608 if (all) {
9609 return true;
9610 }
9611 if (components != null) {
9612 for (int i=0; i<components.size(); i++) {
9613 if (components.get(i).equals(comp)) {
9614 return true;
9615 }
9616 }
9617 }
9618 if (objects != null) {
9619 for (int i=0; i<objects.size(); i++) {
9620 if (System.identityHashCode(object) == objects.get(i)) {
9621 return true;
9622 }
9623 }
9624 }
9625 if (strings != null) {
9626 String flat = comp.flattenToString();
9627 for (int i=0; i<strings.size(); i++) {
9628 if (flat.contains(strings.get(i))) {
9629 return true;
9630 }
9631 }
9632 }
9633 return false;
9634 }
9635 }
9636
Dianne Hackborn625ac272010-09-17 18:29:22 -07009637 /**
9638 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009639 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009640 * - the cmd arg isn't the flattened component name of an existing activity:
9641 * dump all activity whose component contains the cmd as a substring
9642 * - A hex number of the ActivityRecord object instance.
9643 */
9644 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9645 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009646 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009647
9648 if ("all".equals(name)) {
9649 synchronized (this) {
9650 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009651 activities.add(r1);
9652 }
9653 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009654 } else if ("top".equals(name)) {
9655 synchronized (this) {
9656 final int N = mMainStack.mHistory.size();
9657 if (N > 0) {
9658 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9659 }
9660 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009661 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009662 ItemMatcher matcher = new ItemMatcher();
9663 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009664
9665 synchronized (this) {
9666 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009667 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009668 activities.add(r1);
9669 }
9670 }
9671 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009672 }
9673
9674 if (activities.size() <= 0) {
9675 return false;
9676 }
9677
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009678 String[] newArgs = new String[args.length - opti];
9679 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9680
Dianne Hackborn30d71892010-12-11 10:37:55 -08009681 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009682 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009683 for (int i=activities.size()-1; i>=0; i--) {
9684 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009685 if (needSep) {
9686 pw.println();
9687 }
9688 needSep = true;
9689 synchronized (this) {
9690 if (lastTask != r.task) {
9691 lastTask = r.task;
9692 pw.print("TASK "); pw.print(lastTask.affinity);
9693 pw.print(" id="); pw.println(lastTask.taskId);
9694 if (dumpAll) {
9695 lastTask.dump(pw, " ");
9696 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009697 }
9698 }
9699 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009700 }
9701 return true;
9702 }
9703
9704 /**
9705 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9706 * there is a thread associated with the activity.
9707 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009708 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009709 final ActivityRecord r, String[] args, boolean dumpAll) {
9710 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009711 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009712 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9713 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9714 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009715 if (r.app != null) pw.println(r.app.pid);
9716 else pw.println("(not running)");
9717 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009718 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009719 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009720 }
9721 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009722 // flush anything that is already in the PrintWriter since the thread is going
9723 // to write to the file descriptor directly
9724 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009725 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009726 TransferPipe tp = new TransferPipe();
9727 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009728 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9729 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009730 tp.go(fd);
9731 } finally {
9732 tp.kill();
9733 }
9734 } catch (IOException e) {
9735 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009736 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009737 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009738 }
9739 }
9740 }
9741
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009742 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009743 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009744 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009745 boolean onlyHistory = false;
9746
9747 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009748 if (opti < args.length && "-s".equals(args[opti])) {
9749 dumpAll = false;
9750 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009751 onlyHistory = true;
9752 dumpPackage = null;
9753 }
9754
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009755 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009756 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009758 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009759 Iterator it = mRegisteredReceivers.values().iterator();
9760 while (it.hasNext()) {
9761 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009762 if (dumpPackage != null && (r.app == null ||
9763 !dumpPackage.equals(r.app.info.packageName))) {
9764 continue;
9765 }
9766 if (!printed) {
9767 pw.println(" Registered Receivers:");
9768 needSep = true;
9769 printed = true;
9770 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009771 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009772 r.dump(pw, " ");
9773 }
9774 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009775
9776 if (mReceiverResolver.dump(pw, needSep ?
9777 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9778 " ", dumpPackage, false)) {
9779 needSep = true;
9780 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009781 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009782
9783 for (BroadcastQueue q : mBroadcastQueues) {
9784 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009786
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009787 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009788
Dianne Hackborn786b4402012-08-27 15:14:02 -07009789 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009790 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9791 if (needSep) {
9792 pw.println();
9793 }
9794 needSep = true;
9795 pw.print(" Sticky broadcasts for user ");
9796 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9797 StringBuilder sb = new StringBuilder(128);
9798 for (Map.Entry<String, ArrayList<Intent>> ent
9799 : mStickyBroadcasts.valueAt(user).entrySet()) {
9800 pw.print(" * Sticky action "); pw.print(ent.getKey());
9801 if (dumpAll) {
9802 pw.println(":");
9803 ArrayList<Intent> intents = ent.getValue();
9804 final int N = intents.size();
9805 for (int i=0; i<N; i++) {
9806 sb.setLength(0);
9807 sb.append(" Intent: ");
9808 intents.get(i).toShortString(sb, false, true, false, false);
9809 pw.println(sb.toString());
9810 Bundle bundle = intents.get(i).getExtras();
9811 if (bundle != null) {
9812 pw.print(" ");
9813 pw.println(bundle.toString());
9814 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009815 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009816 } else {
9817 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009818 }
9819 }
9820 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009821 }
9822
Dianne Hackborn786b4402012-08-27 15:14:02 -07009823 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009824 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009825 for (BroadcastQueue queue : mBroadcastQueues) {
9826 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9827 + queue.mBroadcastsScheduled);
9828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009829 pw.println(" mHandler:");
9830 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009831 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009833
9834 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009835 }
9836
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009837 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009838 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009839 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009840
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009841 ItemMatcher matcher = new ItemMatcher();
9842 matcher.build(args, opti);
9843
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009844 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009845
9846 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009847
9848 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009849 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009850 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009851 ContentProviderRecord r = mLaunchingProviders.get(i);
9852 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9853 continue;
9854 }
9855 if (!printed) {
9856 if (needSep) pw.println(" ");
9857 needSep = true;
9858 pw.println(" Launching content providers:");
9859 printed = true;
9860 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009861 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009862 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009863 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009864 }
9865
9866 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009867 if (needSep) pw.println();
9868 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009869 pw.println("Granted Uri Permissions:");
9870 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9871 int uid = mGrantedUriPermissions.keyAt(i);
9872 HashMap<Uri, UriPermission> perms
9873 = mGrantedUriPermissions.valueAt(i);
9874 pw.print(" * UID "); pw.print(uid);
9875 pw.println(" holds:");
9876 for (UriPermission perm : perms.values()) {
9877 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009878 if (dumpAll) {
9879 perm.dump(pw, " ");
9880 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009881 }
9882 }
9883 needSep = true;
9884 }
9885
9886 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009887 }
9888
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009889 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009890 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009891 boolean needSep = false;
9892
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009893 if (mIntentSenderRecords.size() > 0) {
9894 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009895 Iterator<WeakReference<PendingIntentRecord>> it
9896 = mIntentSenderRecords.values().iterator();
9897 while (it.hasNext()) {
9898 WeakReference<PendingIntentRecord> ref = it.next();
9899 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009900 if (dumpPackage != null && (rec == null
9901 || !dumpPackage.equals(rec.key.packageName))) {
9902 continue;
9903 }
9904 if (!printed) {
9905 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9906 printed = true;
9907 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009908 needSep = true;
9909 if (rec != null) {
9910 pw.print(" * "); pw.println(rec);
9911 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009912 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009913 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009914 } else {
9915 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009916 }
9917 }
9918 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009919
9920 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009921 }
9922
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009923 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009924 String prefix, String label, boolean complete, boolean brief, boolean client,
9925 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009926 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009927 boolean needNL = false;
9928 final String innerPrefix = prefix + " ";
9929 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009930 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009931 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009932 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9933 continue;
9934 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009935 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009936 if (needNL) {
9937 pw.println(" ");
9938 needNL = false;
9939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009940 if (lastTask != r.task) {
9941 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009942 pw.print(prefix);
9943 pw.print(full ? "* " : " ");
9944 pw.println(lastTask);
9945 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009946 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009947 } else if (complete) {
9948 // Complete + brief == give a summary. Isn't that obvious?!?
9949 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009950 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009951 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009952 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009954 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009955 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9956 pw.print(" #"); pw.print(i); pw.print(": ");
9957 pw.println(r);
9958 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009959 r.dump(pw, innerPrefix);
9960 } else if (complete) {
9961 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009962 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009963 if (r.app != null) {
9964 pw.print(innerPrefix); pw.println(r.app);
9965 }
9966 }
9967 if (client && r.app != null && r.app.thread != null) {
9968 // flush anything that is already in the PrintWriter since the thread is going
9969 // to write to the file descriptor directly
9970 pw.flush();
9971 try {
9972 TransferPipe tp = new TransferPipe();
9973 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009974 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9975 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009976 // Short timeout, since blocking here can
9977 // deadlock with the application.
9978 tp.go(fd, 2000);
9979 } finally {
9980 tp.kill();
9981 }
9982 } catch (IOException e) {
9983 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9984 } catch (RemoteException e) {
9985 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9986 }
9987 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009989 }
9990 }
9991
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009992 private static String buildOomTag(String prefix, String space, int val, int base) {
9993 if (val == base) {
9994 if (space == null) return prefix;
9995 return prefix + " ";
9996 }
9997 return prefix + "+" + Integer.toString(val-base);
9998 }
9999
10000 private static final int dumpProcessList(PrintWriter pw,
10001 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010002 String prefix, String normalLabel, String persistentLabel,
10003 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010004 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010005 final int N = list.size()-1;
10006 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010007 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010008 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10009 continue;
10010 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010011 pw.println(String.format("%s%s #%2d: %s",
10012 prefix, (r.persistent ? persistentLabel : normalLabel),
10013 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010014 if (r.persistent) {
10015 numPers++;
10016 }
10017 }
10018 return numPers;
10019 }
10020
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010021 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010022 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010023 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010024 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010025
Dianne Hackborn905577f2011-09-07 18:31:28 -070010026 ArrayList<Pair<ProcessRecord, Integer>> list
10027 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10028 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010029 ProcessRecord r = origList.get(i);
10030 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10031 continue;
10032 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010033 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10034 }
10035
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010036 if (list.size() <= 0) {
10037 return false;
10038 }
10039
Dianne Hackborn905577f2011-09-07 18:31:28 -070010040 Comparator<Pair<ProcessRecord, Integer>> comparator
10041 = new Comparator<Pair<ProcessRecord, Integer>>() {
10042 @Override
10043 public int compare(Pair<ProcessRecord, Integer> object1,
10044 Pair<ProcessRecord, Integer> object2) {
10045 if (object1.first.setAdj != object2.first.setAdj) {
10046 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10047 }
10048 if (object1.second.intValue() != object2.second.intValue()) {
10049 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10050 }
10051 return 0;
10052 }
10053 };
10054
10055 Collections.sort(list, comparator);
10056
Dianne Hackborn287952c2010-09-22 22:34:31 -070010057 final long curRealtime = SystemClock.elapsedRealtime();
10058 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10059 final long curUptime = SystemClock.uptimeMillis();
10060 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10061
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010062 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010063 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010064 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010065 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010066 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010067 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10068 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010069 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10070 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010071 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10072 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010073 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10074 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010075 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010076 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010077 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10078 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10079 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10080 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10081 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10082 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10083 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10084 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010085 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10086 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010087 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10088 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010089 } else {
10090 oomAdj = Integer.toString(r.setAdj);
10091 }
10092 String schedGroup;
10093 switch (r.setSchedGroup) {
10094 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10095 schedGroup = "B";
10096 break;
10097 case Process.THREAD_GROUP_DEFAULT:
10098 schedGroup = "F";
10099 break;
10100 default:
10101 schedGroup = Integer.toString(r.setSchedGroup);
10102 break;
10103 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010104 String foreground;
10105 if (r.foregroundActivities) {
10106 foreground = "A";
10107 } else if (r.foregroundServices) {
10108 foreground = "S";
10109 } else {
10110 foreground = " ";
10111 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010112 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010113 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010114 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10115 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010116 if (r.adjSource != null || r.adjTarget != null) {
10117 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010118 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010119 if (r.adjTarget instanceof ComponentName) {
10120 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10121 } else if (r.adjTarget != null) {
10122 pw.print(r.adjTarget.toString());
10123 } else {
10124 pw.print("{null}");
10125 }
10126 pw.print("<=");
10127 if (r.adjSource instanceof ProcessRecord) {
10128 pw.print("Proc{");
10129 pw.print(((ProcessRecord)r.adjSource).toShortString());
10130 pw.println("}");
10131 } else if (r.adjSource != null) {
10132 pw.println(r.adjSource.toString());
10133 } else {
10134 pw.println("{null}");
10135 }
10136 }
10137 if (inclDetails) {
10138 pw.print(prefix);
10139 pw.print(" ");
10140 pw.print("oom: max="); pw.print(r.maxAdj);
10141 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010142 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010143 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010144 pw.print(" curRaw="); pw.print(r.curRawAdj);
10145 pw.print(" setRaw="); pw.print(r.setRawAdj);
10146 pw.print(" cur="); pw.print(r.curAdj);
10147 pw.print(" set="); pw.println(r.setAdj);
10148 pw.print(prefix);
10149 pw.print(" ");
10150 pw.print("keeping="); pw.print(r.keeping);
10151 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010152 pw.print(" empty="); pw.print(r.empty);
10153 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010154
10155 if (!r.keeping) {
10156 if (r.lastWakeTime != 0) {
10157 long wtime;
10158 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10159 synchronized (stats) {
10160 wtime = stats.getProcessWakeTime(r.info.uid,
10161 r.pid, curRealtime);
10162 }
10163 long timeUsed = wtime - r.lastWakeTime;
10164 pw.print(prefix);
10165 pw.print(" ");
10166 pw.print("keep awake over ");
10167 TimeUtils.formatDuration(realtimeSince, pw);
10168 pw.print(" used ");
10169 TimeUtils.formatDuration(timeUsed, pw);
10170 pw.print(" (");
10171 pw.print((timeUsed*100)/realtimeSince);
10172 pw.println("%)");
10173 }
10174 if (r.lastCpuTime != 0) {
10175 long timeUsed = r.curCpuTime - r.lastCpuTime;
10176 pw.print(prefix);
10177 pw.print(" ");
10178 pw.print("run cpu over ");
10179 TimeUtils.formatDuration(uptimeSince, pw);
10180 pw.print(" used ");
10181 TimeUtils.formatDuration(timeUsed, pw);
10182 pw.print(" (");
10183 pw.print((timeUsed*100)/uptimeSince);
10184 pw.println("%)");
10185 }
10186 }
10187 }
10188 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010189 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010190 }
10191
Dianne Hackbornb437e092011-08-05 17:50:29 -070010192 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010193 ArrayList<ProcessRecord> procs;
10194 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010195 if (args != null && args.length > start
10196 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010197 procs = new ArrayList<ProcessRecord>();
10198 int pid = -1;
10199 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010201 } catch (NumberFormatException e) {
10202
10203 }
10204 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10205 ProcessRecord proc = mLruProcesses.get(i);
10206 if (proc.pid == pid) {
10207 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010208 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010209 procs.add(proc);
10210 }
10211 }
10212 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010213 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010214 return null;
10215 }
10216 } else {
10217 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10218 }
10219 }
10220 return procs;
10221 }
10222
10223 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10224 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010225 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010226 if (procs == null) {
10227 return;
10228 }
10229
10230 long uptime = SystemClock.uptimeMillis();
10231 long realtime = SystemClock.elapsedRealtime();
10232 pw.println("Applications Graphics Acceleration Info:");
10233 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10234
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010235 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10236 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010237 if (r.thread != null) {
10238 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10239 pw.flush();
10240 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010241 TransferPipe tp = new TransferPipe();
10242 try {
10243 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10244 tp.go(fd);
10245 } finally {
10246 tp.kill();
10247 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010248 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010249 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010250 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010251 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010252 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010253 pw.flush();
10254 }
10255 }
10256 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010257 }
10258
Jeff Brown6754ba22011-12-14 20:20:01 -080010259 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10260 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10261 if (procs == null) {
10262 return;
10263 }
10264
10265 pw.println("Applications Database Info:");
10266
10267 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10268 ProcessRecord r = procs.get(i);
10269 if (r.thread != null) {
10270 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10271 pw.flush();
10272 try {
10273 TransferPipe tp = new TransferPipe();
10274 try {
10275 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10276 tp.go(fd);
10277 } finally {
10278 tp.kill();
10279 }
10280 } catch (IOException e) {
10281 pw.println("Failure while dumping the app: " + r);
10282 pw.flush();
10283 } catch (RemoteException e) {
10284 pw.println("Got a RemoteException while dumping the app " + r);
10285 pw.flush();
10286 }
10287 }
10288 }
10289 }
10290
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010291 final static class MemItem {
10292 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010293 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010294 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010295 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010296 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010297
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010298 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010299 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010300 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010301 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010302 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010303 }
10304 }
10305
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010306 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010307 boolean sort) {
10308 if (sort) {
10309 Collections.sort(items, new Comparator<MemItem>() {
10310 @Override
10311 public int compare(MemItem lhs, MemItem rhs) {
10312 if (lhs.pss < rhs.pss) {
10313 return 1;
10314 } else if (lhs.pss > rhs.pss) {
10315 return -1;
10316 }
10317 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010318 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010319 });
10320 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010321
10322 for (int i=0; i<items.size(); i++) {
10323 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010324 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010325 if (mi.subitems != null) {
10326 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10327 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010328 }
10329 }
10330
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010331 // These are in KB.
10332 static final long[] DUMP_MEM_BUCKETS = new long[] {
10333 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10334 120*1024, 160*1024, 200*1024,
10335 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10336 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10337 };
10338
Dianne Hackborn672342c2011-11-29 11:29:02 -080010339 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10340 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010341 int start = label.lastIndexOf('.');
10342 if (start >= 0) start++;
10343 else start = 0;
10344 int end = label.length();
10345 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10346 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10347 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10348 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010349 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010350 out.append(label, start, end);
10351 return;
10352 }
10353 }
10354 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010355 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010356 out.append(label, start, end);
10357 }
10358
10359 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10360 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10361 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10362 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10363 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10364 };
10365 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10366 "System", "Persistent", "Foreground",
10367 "Visible", "Perceptible", "Heavy Weight",
10368 "Backup", "A Services", "Home", "Previous",
10369 "B Services", "Background"
10370 };
10371
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010372 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010373 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010374 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010375 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010376 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010377
10378 int opti = 0;
10379 while (opti < args.length) {
10380 String opt = args[opti];
10381 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10382 break;
10383 }
10384 opti++;
10385 if ("-a".equals(opt)) {
10386 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010387 } else if ("--oom".equals(opt)) {
10388 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010389 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010390 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010391 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010392 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010393 pw.println("If [process] is specified it can be the name or ");
10394 pw.println("pid of a specific process to dump.");
10395 return;
10396 } else {
10397 pw.println("Unknown argument: " + opt + "; use -h for help");
10398 }
10399 }
10400
10401 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010402 if (procs == null) {
10403 return;
10404 }
10405
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010406 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010407 long uptime = SystemClock.uptimeMillis();
10408 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010409
10410 if (procs.size() == 1 || isCheckinRequest) {
10411 dumpAll = true;
10412 }
10413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010414 if (isCheckinRequest) {
10415 // short checkin version
10416 pw.println(uptime + "," + realtime);
10417 pw.flush();
10418 } else {
10419 pw.println("Applications Memory Usage (kB):");
10420 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10421 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010422
Dianne Hackbornb437e092011-08-05 17:50:29 -070010423 String[] innerArgs = new String[args.length-opti];
10424 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10425
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010426 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10427 long nativePss=0, dalvikPss=0, otherPss=0;
10428 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10429
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010430 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10431 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10432 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010433
10434 long totalPss = 0;
10435
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010436 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10437 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010439 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010440 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10441 pw.flush();
10442 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010443 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010444 if (dumpAll) {
10445 try {
10446 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10447 } catch (RemoteException e) {
10448 if (!isCheckinRequest) {
10449 pw.println("Got RemoteException!");
10450 pw.flush();
10451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010452 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010453 } else {
10454 mi = new Debug.MemoryInfo();
10455 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010456 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010457
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010458 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010459 long myTotalPss = mi.getTotalPss();
10460 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010461 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010462 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010463 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010464
10465 nativePss += mi.nativePss;
10466 dalvikPss += mi.dalvikPss;
10467 otherPss += mi.otherPss;
10468 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10469 long mem = mi.getOtherPss(j);
10470 miscPss[j] += mem;
10471 otherPss -= mem;
10472 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010473
10474 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010475 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10476 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010477 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010478 if (oomProcs[oomIndex] == null) {
10479 oomProcs[oomIndex] = new ArrayList<MemItem>();
10480 }
10481 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010482 break;
10483 }
10484 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010486 }
10487 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010488
10489 if (!isCheckinRequest && procs.size() > 1) {
10490 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10491
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010492 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10493 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10494 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010495 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010496 String label = Debug.MemoryInfo.getOtherLabel(j);
10497 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010498 }
10499
Dianne Hackbornb437e092011-08-05 17:50:29 -070010500 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10501 for (int j=0; j<oomPss.length; j++) {
10502 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010503 String label = DUMP_MEM_OOM_LABEL[j];
10504 MemItem item = new MemItem(label, label, oomPss[j],
10505 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010506 item.subitems = oomProcs[j];
10507 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010508 }
10509 }
10510
Dianne Hackborn672342c2011-11-29 11:29:02 -080010511 if (outTag != null || outStack != null) {
10512 if (outTag != null) {
10513 appendMemBucket(outTag, totalPss, "total", false);
10514 }
10515 if (outStack != null) {
10516 appendMemBucket(outStack, totalPss, "total", true);
10517 }
10518 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010519 for (int i=0; i<oomMems.size(); i++) {
10520 MemItem miCat = oomMems.get(i);
10521 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10522 continue;
10523 }
10524 if (miCat.id < ProcessList.SERVICE_ADJ
10525 || miCat.id == ProcessList.HOME_APP_ADJ
10526 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010527 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10528 outTag.append(" / ");
10529 }
10530 if (outStack != null) {
10531 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10532 if (firstLine) {
10533 outStack.append(":");
10534 firstLine = false;
10535 }
10536 outStack.append("\n\t at ");
10537 } else {
10538 outStack.append("$");
10539 }
10540 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010541 for (int j=0; j<miCat.subitems.size(); j++) {
10542 MemItem mi = miCat.subitems.get(j);
10543 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010544 if (outTag != null) {
10545 outTag.append(" ");
10546 }
10547 if (outStack != null) {
10548 outStack.append("$");
10549 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010550 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010551 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10552 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10553 }
10554 if (outStack != null) {
10555 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10556 }
10557 }
10558 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10559 outStack.append("(");
10560 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10561 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10562 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10563 outStack.append(":");
10564 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10565 }
10566 }
10567 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010568 }
10569 }
10570 }
10571 }
10572
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010573 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010574 pw.println();
10575 pw.println("Total PSS by process:");
10576 dumpMemItems(pw, " ", procMems, true);
10577 pw.println();
10578 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010579 pw.println("Total PSS by OOM adjustment:");
10580 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010581 if (!oomOnly) {
10582 PrintWriter out = categoryPw != null ? categoryPw : pw;
10583 out.println();
10584 out.println("Total PSS by category:");
10585 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010586 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010587 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010588 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010589 final int[] SINGLE_LONG_FORMAT = new int[] {
10590 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10591 };
10592 long[] longOut = new long[1];
10593 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10594 SINGLE_LONG_FORMAT, null, longOut, null);
10595 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10596 longOut[0] = 0;
10597 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10598 SINGLE_LONG_FORMAT, null, longOut, null);
10599 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10600 longOut[0] = 0;
10601 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10602 SINGLE_LONG_FORMAT, null, longOut, null);
10603 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10604 longOut[0] = 0;
10605 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10606 SINGLE_LONG_FORMAT, null, longOut, null);
10607 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10608 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10609 pw.print(shared); pw.println(" kB");
10610 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10611 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613 }
10614
10615 /**
10616 * Searches array of arguments for the specified string
10617 * @param args array of argument strings
10618 * @param value value to search for
10619 * @return true if the value is contained in the array
10620 */
10621 private static boolean scanArgs(String[] args, String value) {
10622 if (args != null) {
10623 for (String arg : args) {
10624 if (value.equals(arg)) {
10625 return true;
10626 }
10627 }
10628 }
10629 return false;
10630 }
10631
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010632 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10633 ContentProviderRecord cpr, boolean always) {
10634 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10635
10636 if (!inLaunching || always) {
10637 synchronized (cpr) {
10638 cpr.launchingApp = null;
10639 cpr.notifyAll();
10640 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010641 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010642 String names[] = cpr.info.authority.split(";");
10643 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010644 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010645 }
10646 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010647
10648 for (int i=0; i<cpr.connections.size(); i++) {
10649 ContentProviderConnection conn = cpr.connections.get(i);
10650 if (conn.waiting) {
10651 // If this connection is waiting for the provider, then we don't
10652 // need to mess with its process unless we are always removing
10653 // or for some reason the provider is not currently launching.
10654 if (inLaunching && !always) {
10655 continue;
10656 }
10657 }
10658 ProcessRecord capp = conn.client;
10659 conn.dead = true;
10660 if (conn.stableCount > 0) {
10661 if (!capp.persistent && capp.thread != null
10662 && capp.pid != 0
10663 && capp.pid != MY_PID) {
10664 Slog.i(TAG, "Kill " + capp.processName
10665 + " (pid " + capp.pid + "): provider " + cpr.info.name
10666 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010667 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010668 capp.processName, capp.setAdj, "dying provider "
10669 + cpr.name.toShortString());
10670 Process.killProcessQuiet(capp.pid);
10671 }
10672 } else if (capp.thread != null && conn.provider.provider != null) {
10673 try {
10674 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10675 } catch (RemoteException e) {
10676 }
10677 // In the protocol here, we don't expect the client to correctly
10678 // clean up this connection, we'll just remove it.
10679 cpr.connections.remove(i);
10680 conn.client.conProviders.remove(conn);
10681 }
10682 }
10683
10684 if (inLaunching && always) {
10685 mLaunchingProviders.remove(cpr);
10686 }
10687 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 }
10689
10690 /**
10691 * Main code for cleaning up a process when it has gone away. This is
10692 * called both as a result of the process dying, or directly when stopping
10693 * a process when running in single process mode.
10694 */
10695 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010696 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010697 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010698 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 }
10700
Dianne Hackborn36124872009-10-08 16:22:03 -070010701 mProcessesToGc.remove(app);
10702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010703 // Dismiss any open dialogs.
10704 if (app.crashDialog != null) {
10705 app.crashDialog.dismiss();
10706 app.crashDialog = null;
10707 }
10708 if (app.anrDialog != null) {
10709 app.anrDialog.dismiss();
10710 app.anrDialog = null;
10711 }
10712 if (app.waitDialog != null) {
10713 app.waitDialog.dismiss();
10714 app.waitDialog = null;
10715 }
10716
10717 app.crashing = false;
10718 app.notResponding = false;
10719
10720 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010721 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 app.thread = null;
10723 app.forcingToForeground = null;
10724 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010725 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010726 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010727 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010729 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730
10731 boolean restart = false;
10732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010733 // Remove published content providers.
10734 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010735 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010737 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010738
10739 final boolean always = app.bad || !allowRestart;
10740 if (removeDyingProviderLocked(app, cpr, always) || always) {
10741 // We left the provider in the launching list, need to
10742 // restart it.
10743 restart = true;
10744 }
10745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010747 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010748 }
10749 app.pubProviders.clear();
10750 }
10751
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010752 // Take care of any launching providers waiting for this process.
10753 if (checkAppInLaunchingProvidersLocked(app, false)) {
10754 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010757 // Unregister from connected content providers.
10758 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010759 for (int i=0; i<app.conProviders.size(); i++) {
10760 ContentProviderConnection conn = app.conProviders.get(i);
10761 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 }
10763 app.conProviders.clear();
10764 }
10765
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010766 // At this point there may be remaining entries in mLaunchingProviders
10767 // where we were the only one waiting, so they are no longer of use.
10768 // Look for these and clean up if found.
10769 // XXX Commented out for now. Trying to figure out a way to reproduce
10770 // the actual situation to identify what is actually going on.
10771 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010772 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010773 ContentProviderRecord cpr = (ContentProviderRecord)
10774 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010775 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010776 synchronized (cpr) {
10777 cpr.launchingApp = null;
10778 cpr.notifyAll();
10779 }
10780 }
10781 }
10782 }
10783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 skipCurrentReceiverLocked(app);
10785
10786 // Unregister any receivers.
10787 if (app.receivers.size() > 0) {
10788 Iterator<ReceiverList> it = app.receivers.iterator();
10789 while (it.hasNext()) {
10790 removeReceiverLocked(it.next());
10791 }
10792 app.receivers.clear();
10793 }
10794
Christopher Tate181fafa2009-05-14 11:12:14 -070010795 // If the app is undergoing backup, tell the backup manager about it
10796 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010797 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10798 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010799 try {
10800 IBackupManager bm = IBackupManager.Stub.asInterface(
10801 ServiceManager.getService(Context.BACKUP_SERVICE));
10802 bm.agentDisconnected(app.info.packageName);
10803 } catch (RemoteException e) {
10804 // can't happen; backup manager is local
10805 }
10806 }
10807
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010808 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10809 ProcessChangeItem item = mPendingProcessChanges.get(i);
10810 if (item.pid == app.pid) {
10811 mPendingProcessChanges.remove(i);
10812 mAvailProcessChanges.add(item);
10813 }
10814 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010815 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 // If the caller is restarting this app, then leave it in its
10818 // current lists and let the caller take care of it.
10819 if (restarting) {
10820 return;
10821 }
10822
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010823 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010824 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010826 mProcessNames.remove(app.processName, app.uid);
10827 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010828 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010829 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10830 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010831 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 } else if (!app.removed) {
10834 // This app is persistent, so we need to keep its record around.
10835 // If it is not already on the pending app list, add it there
10836 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10838 mPersistentStartingProcesses.add(app);
10839 restart = true;
10840 }
10841 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010842 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010843 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 mProcessesOnHold.remove(app);
10845
The Android Open Source Project4df24232009-03-05 14:34:35 -080010846 if (app == mHomeProcess) {
10847 mHomeProcess = null;
10848 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010849 if (app == mPreviousProcess) {
10850 mPreviousProcess = null;
10851 }
10852
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010853 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 // We have components that still need to be running in the
10855 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010856 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 startProcessLocked(app, "restart", app.processName);
10858 } else if (app.pid > 0 && app.pid != MY_PID) {
10859 // Goodbye!
10860 synchronized (mPidsSelfLocked) {
10861 mPidsSelfLocked.remove(app.pid);
10862 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10863 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010864 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 }
10866 }
10867
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010868 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10869 // Look through the content providers we are waiting to have launched,
10870 // and if any run in this process then either schedule a restart of
10871 // the process or kill the client waiting for it if this process has
10872 // gone bad.
10873 int NL = mLaunchingProviders.size();
10874 boolean restart = false;
10875 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010876 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010877 if (cpr.launchingApp == app) {
10878 if (!alwaysBad && !app.bad) {
10879 restart = true;
10880 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010881 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010882 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010883 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010884 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010885 }
10886 }
10887 }
10888 return restart;
10889 }
10890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 // =========================================================
10892 // SERVICES
10893 // =========================================================
10894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10896 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010897 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010898 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010899 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 }
10901 }
10902
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010903 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010904 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010905 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010906 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010907 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010908 }
10909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010911 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010912 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010913 // Refuse possible leaked file descriptors
10914 if (service != null && service.hasFileDescriptors() == true) {
10915 throw new IllegalArgumentException("File descriptors passed in Intent");
10916 }
10917
Amith Yamasani742a6712011-05-04 14:49:28 -070010918 if (DEBUG_SERVICE)
10919 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 synchronized(this) {
10921 final int callingPid = Binder.getCallingPid();
10922 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010923 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010925 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010926 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 Binder.restoreCallingIdentity(origId);
10928 return res;
10929 }
10930 }
10931
10932 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010933 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010935 if (DEBUG_SERVICE)
10936 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010937 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010938 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010939 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940 Binder.restoreCallingIdentity(origId);
10941 return res;
10942 }
10943 }
10944
10945 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010946 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010947 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 // Refuse possible leaked file descriptors
10949 if (service != null && service.hasFileDescriptors() == true) {
10950 throw new IllegalArgumentException("File descriptors passed in Intent");
10951 }
10952
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010953 checkValidCaller(Binder.getCallingUid(), userId);
10954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010955 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010956 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958 }
10959
10960 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010961 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 // Refuse possible leaked file descriptors
10963 if (service != null && service.hasFileDescriptors() == true) {
10964 throw new IllegalArgumentException("File descriptors passed in Intent");
10965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010967 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 }
10970
10971 public boolean stopServiceToken(ComponentName className, IBinder token,
10972 int startId) {
10973 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010974 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976 }
10977
10978 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010979 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010981 mServices.setServiceForegroundLocked(className, token, id, notification,
10982 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010983 }
10984 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010985
Dianne Hackborn41203752012-08-31 14:05:51 -070010986 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10987 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010988 final int callingUserId = UserHandle.getUserId(callingUid);
10989 if (callingUserId != userId) {
10990 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10991 if ((requireFull || checkComponentPermission(
10992 android.Manifest.permission.INTERACT_ACROSS_USERS,
10993 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10994 && checkComponentPermission(
10995 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10996 callingPid, callingUid, -1, true)
10997 != PackageManager.PERMISSION_GRANTED) {
10998 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10999 // In this case, they would like to just execute as their
11000 // owner user instead of failing.
11001 userId = callingUserId;
11002 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011003 StringBuilder builder = new StringBuilder(128);
11004 builder.append("Permission Denial: ");
11005 builder.append(name);
11006 if (callerPackage != null) {
11007 builder.append(" from ");
11008 builder.append(callerPackage);
11009 }
11010 builder.append(" asks to run as user ");
11011 builder.append(userId);
11012 builder.append(" but is calling from user ");
11013 builder.append(UserHandle.getUserId(callingUid));
11014 builder.append("; this requires ");
11015 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11016 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011017 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011018 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11019 }
11020 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011021 Slog.w(TAG, msg);
11022 throw new SecurityException(msg);
11023 }
11024 }
11025 }
11026 if (userId == UserHandle.USER_CURRENT
11027 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011028 // Note that we may be accessing this outside of a lock...
11029 // shouldn't be a big deal, if this is being called outside
11030 // of a locked context there is intrinsically a race with
11031 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011032 userId = mCurrentUserId;
11033 }
11034 if (!allowAll && userId < 0) {
11035 throw new IllegalArgumentException(
11036 "Call does not support special user #" + userId);
11037 }
11038 }
11039 return userId;
11040 }
11041
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011042 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11043 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011044 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011045 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011046 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11047 if (ActivityManager.checkUidPermission(
11048 android.Manifest.permission.INTERACT_ACROSS_USERS,
11049 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11050 ComponentName comp = new ComponentName(aInfo.packageName, className);
11051 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11052 + " requests FLAG_SINGLE_USER, but app does not hold "
11053 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11054 Slog.w(TAG, msg);
11055 throw new SecurityException(msg);
11056 }
11057 result = true;
11058 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011059 } else if (componentProcessName == aInfo.packageName) {
11060 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11061 } else if ("system".equals(componentProcessName)) {
11062 result = true;
11063 }
11064 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011065 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11066 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011067 }
11068 return result;
11069 }
11070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011071 public int bindService(IApplicationThread caller, IBinder token,
11072 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011073 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011074 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011075 // Refuse possible leaked file descriptors
11076 if (service != null && service.hasFileDescriptors() == true) {
11077 throw new IllegalArgumentException("File descriptors passed in Intent");
11078 }
11079
11080 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011081 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11082 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 }
11084 }
11085
11086 public boolean unbindService(IServiceConnection connection) {
11087 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011088 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011090 }
11091
11092 public void publishService(IBinder token, Intent intent, IBinder service) {
11093 // Refuse possible leaked file descriptors
11094 if (intent != null && intent.hasFileDescriptors() == true) {
11095 throw new IllegalArgumentException("File descriptors passed in Intent");
11096 }
11097
11098 synchronized(this) {
11099 if (!(token instanceof ServiceRecord)) {
11100 throw new IllegalArgumentException("Invalid service token");
11101 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011102 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 }
11104 }
11105
11106 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11107 // Refuse possible leaked file descriptors
11108 if (intent != null && intent.hasFileDescriptors() == true) {
11109 throw new IllegalArgumentException("File descriptors passed in Intent");
11110 }
11111
11112 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011113 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 }
11115 }
11116
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011117 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 synchronized(this) {
11119 if (!(token instanceof ServiceRecord)) {
11120 throw new IllegalArgumentException("Invalid service token");
11121 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011122 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124 }
11125
11126 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011127 // BACKUP AND RESTORE
11128 // =========================================================
11129
11130 // Cause the target app to be launched if necessary and its backup agent
11131 // instantiated. The backup agent will invoke backupAgentCreated() on the
11132 // activity manager to announce its creation.
11133 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011134 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11135 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011136
11137 synchronized(this) {
11138 // !!! TODO: currently no check here that we're already bound
11139 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11140 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11141 synchronized (stats) {
11142 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11143 }
11144
Dianne Hackborne7f97212011-02-24 14:40:20 -080011145 // Backup agent is now in use, its package can't be stopped.
11146 try {
11147 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011148 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011149 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011150 } catch (IllegalArgumentException e) {
11151 Slog.w(TAG, "Failed trying to unstop package "
11152 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011153 }
11154
Christopher Tate181fafa2009-05-14 11:12:14 -070011155 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011156 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11157 ? new ComponentName(app.packageName, app.backupAgentName)
11158 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011159 // startProcessLocked() returns existing proc's record if it's already running
11160 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011161 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011162 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011163 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011164 return false;
11165 }
11166
11167 r.app = proc;
11168 mBackupTarget = r;
11169 mBackupAppName = app.packageName;
11170
Christopher Tate6fa95972009-06-05 18:43:55 -070011171 // Try not to kill the process during backup
11172 updateOomAdjLocked(proc);
11173
Christopher Tate181fafa2009-05-14 11:12:14 -070011174 // If the process is already attached, schedule the creation of the backup agent now.
11175 // If it is not yet live, this will be done when it attaches to the framework.
11176 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011177 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011178 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011179 proc.thread.scheduleCreateBackupAgent(app,
11180 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011181 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011182 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011183 }
11184 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011185 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011186 }
11187 // Invariants: at this point, the target app process exists and the application
11188 // is either already running or in the process of coming up. mBackupTarget and
11189 // mBackupAppName describe the app, so that when it binds back to the AM we
11190 // know that it's scheduled for a backup-agent operation.
11191 }
11192
11193 return true;
11194 }
11195
Christopher Tate346acb12012-10-15 19:20:25 -070011196 @Override
11197 public void clearPendingBackup() {
11198 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11199 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11200
11201 synchronized (this) {
11202 mBackupTarget = null;
11203 mBackupAppName = null;
11204 }
11205 }
11206
Christopher Tate181fafa2009-05-14 11:12:14 -070011207 // A backup agent has just come up
11208 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011209 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011210 + " = " + agent);
11211
11212 synchronized(this) {
11213 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011214 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011215 return;
11216 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011217 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011218
Dianne Hackborn06740692010-09-22 22:46:21 -070011219 long oldIdent = Binder.clearCallingIdentity();
11220 try {
11221 IBackupManager bm = IBackupManager.Stub.asInterface(
11222 ServiceManager.getService(Context.BACKUP_SERVICE));
11223 bm.agentConnected(agentPackageName, agent);
11224 } catch (RemoteException e) {
11225 // can't happen; the backup manager service is local
11226 } catch (Exception e) {
11227 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11228 e.printStackTrace();
11229 } finally {
11230 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011231 }
11232 }
11233
11234 // done with this agent
11235 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011236 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011237 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011238 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011239 return;
11240 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011241
11242 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011243 try {
11244 if (mBackupAppName == null) {
11245 Slog.w(TAG, "Unbinding backup agent with no active backup");
11246 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011247 }
Christopher Tate346acb12012-10-15 19:20:25 -070011248
11249 if (!mBackupAppName.equals(appInfo.packageName)) {
11250 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11251 return;
11252 }
11253
11254 // Not backing this app up any more; reset its OOM adjustment
11255 final ProcessRecord proc = mBackupTarget.app;
11256 updateOomAdjLocked(proc);
11257
11258 // If the app crashed during backup, 'thread' will be null here
11259 if (proc.thread != null) {
11260 try {
11261 proc.thread.scheduleDestroyBackupAgent(appInfo,
11262 compatibilityInfoForPackageLocked(appInfo));
11263 } catch (Exception e) {
11264 Slog.e(TAG, "Exception when unbinding backup agent:");
11265 e.printStackTrace();
11266 }
11267 }
11268 } finally {
11269 mBackupTarget = null;
11270 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011271 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011272 }
11273 }
11274 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011275 // BROADCASTS
11276 // =========================================================
11277
Josh Bartel7f208742010-02-25 11:01:44 -060011278 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011279 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011281 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11282 if (stickies == null) {
11283 return cur;
11284 }
11285 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011286 if (list == null) {
11287 return cur;
11288 }
11289 int N = list.size();
11290 for (int i=0; i<N; i++) {
11291 Intent intent = list.get(i);
11292 if (filter.match(resolver, intent, true, TAG) >= 0) {
11293 if (cur == null) {
11294 cur = new ArrayList<Intent>();
11295 }
11296 cur.add(intent);
11297 }
11298 }
11299 return cur;
11300 }
11301
Christopher Tatef46723b2012-01-26 14:19:24 -080011302 boolean isPendingBroadcastProcessLocked(int pid) {
11303 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11304 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306
Christopher Tatef46723b2012-01-26 14:19:24 -080011307 void skipPendingBroadcastLocked(int pid) {
11308 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11309 for (BroadcastQueue queue : mBroadcastQueues) {
11310 queue.skipPendingBroadcastLocked(pid);
11311 }
11312 }
11313
11314 // The app just attached; send any pending broadcasts that it should receive
11315 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11316 boolean didSomething = false;
11317 for (BroadcastQueue queue : mBroadcastQueues) {
11318 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011319 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011320 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 }
11322
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011323 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011324 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011325 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011326 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011327 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 synchronized(this) {
11329 ProcessRecord callerApp = null;
11330 if (caller != null) {
11331 callerApp = getRecordForAppLocked(caller);
11332 if (callerApp == null) {
11333 throw new SecurityException(
11334 "Unable to find app for caller " + caller
11335 + " (pid=" + Binder.getCallingPid()
11336 + ") when registering receiver " + receiver);
11337 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011338 if (callerApp.info.uid != Process.SYSTEM_UID &&
11339 !callerApp.pkgList.contains(callerPackage)) {
11340 throw new SecurityException("Given caller package " + callerPackage
11341 + " is not running in process " + callerApp);
11342 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011343 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011344 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011345 } else {
11346 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011347 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011348 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011349 }
11350
Dianne Hackborn139748f2012-09-24 11:36:57 -070011351 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011352 true, true, "registerReceiver", callerPackage);
11353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354 List allSticky = null;
11355
11356 // Look for any matching sticky broadcasts...
11357 Iterator actions = filter.actionsIterator();
11358 if (actions != null) {
11359 while (actions.hasNext()) {
11360 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011361 allSticky = getStickiesLocked(action, filter, allSticky,
11362 UserHandle.USER_ALL);
11363 allSticky = getStickiesLocked(action, filter, allSticky,
11364 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365 }
11366 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011367 allSticky = getStickiesLocked(null, filter, allSticky,
11368 UserHandle.USER_ALL);
11369 allSticky = getStickiesLocked(null, filter, allSticky,
11370 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011371 }
11372
11373 // The first sticky in the list is returned directly back to
11374 // the client.
11375 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11376
Joe Onorato8a9b2202010-02-26 18:56:32 -080011377 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011378 + ": " + sticky);
11379
11380 if (receiver == null) {
11381 return sticky;
11382 }
11383
11384 ReceiverList rl
11385 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11386 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011387 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11388 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 if (rl.app != null) {
11390 rl.app.receivers.add(rl);
11391 } else {
11392 try {
11393 receiver.asBinder().linkToDeath(rl, 0);
11394 } catch (RemoteException e) {
11395 return sticky;
11396 }
11397 rl.linkedToDeath = true;
11398 }
11399 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011400 } else if (rl.uid != callingUid) {
11401 throw new IllegalArgumentException(
11402 "Receiver requested to register for uid " + callingUid
11403 + " was previously registered for uid " + rl.uid);
11404 } else if (rl.pid != callingPid) {
11405 throw new IllegalArgumentException(
11406 "Receiver requested to register for pid " + callingPid
11407 + " was previously registered for pid " + rl.pid);
11408 } else if (rl.userId != userId) {
11409 throw new IllegalArgumentException(
11410 "Receiver requested to register for user " + userId
11411 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011413 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011414 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011415 rl.add(bf);
11416 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011417 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 }
11419 mReceiverResolver.addFilter(bf);
11420
11421 // Enqueue broadcasts for all existing stickies that match
11422 // this filter.
11423 if (allSticky != null) {
11424 ArrayList receivers = new ArrayList();
11425 receivers.add(bf);
11426
11427 int N = allSticky.size();
11428 for (int i=0; i<N; i++) {
11429 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011430 BroadcastQueue queue = broadcastQueueForIntent(intent);
11431 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011432 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011433 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011434 queue.enqueueParallelBroadcastLocked(r);
11435 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011436 }
11437 }
11438
11439 return sticky;
11440 }
11441 }
11442
11443 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011444 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011445
Christopher Tatef46723b2012-01-26 14:19:24 -080011446 final long origId = Binder.clearCallingIdentity();
11447 try {
11448 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449
Christopher Tatef46723b2012-01-26 14:19:24 -080011450 synchronized(this) {
11451 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011452 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011453 if (rl != null) {
11454 if (rl.curBroadcast != null) {
11455 BroadcastRecord r = rl.curBroadcast;
11456 final boolean doNext = finishReceiverLocked(
11457 receiver.asBinder(), r.resultCode, r.resultData,
11458 r.resultExtras, r.resultAbort, true);
11459 if (doNext) {
11460 doTrim = true;
11461 r.queue.processNextBroadcast(false);
11462 }
11463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464
Christopher Tatef46723b2012-01-26 14:19:24 -080011465 if (rl.app != null) {
11466 rl.app.receivers.remove(rl);
11467 }
11468 removeReceiverLocked(rl);
11469 if (rl.linkedToDeath) {
11470 rl.linkedToDeath = false;
11471 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 }
11474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475
Christopher Tatef46723b2012-01-26 14:19:24 -080011476 // If we actually concluded any broadcasts, we might now be able
11477 // to trim the recipients' apps from our working set
11478 if (doTrim) {
11479 trimApplications();
11480 return;
11481 }
11482
11483 } finally {
11484 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 }
11487
11488 void removeReceiverLocked(ReceiverList rl) {
11489 mRegisteredReceivers.remove(rl.receiver.asBinder());
11490 int N = rl.size();
11491 for (int i=0; i<N; i++) {
11492 mReceiverResolver.removeFilter(rl.get(i));
11493 }
11494 }
11495
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011496 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011497 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11498 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011499 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011500 try {
11501 r.thread.dispatchPackageBroadcast(cmd, packages);
11502 } catch (RemoteException ex) {
11503 }
11504 }
11505 }
11506 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011507
11508 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11509 int[] users) {
11510 List<ResolveInfo> receivers = null;
11511 try {
11512 HashSet<ComponentName> singleUserReceivers = null;
11513 boolean scannedFirstReceivers = false;
11514 for (int user : users) {
11515 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11516 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011517 if (user != 0 && newReceivers != null) {
11518 // If this is not the primary user, we need to check for
11519 // any receivers that should be filtered out.
11520 for (int i=0; i<newReceivers.size(); i++) {
11521 ResolveInfo ri = newReceivers.get(i);
11522 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11523 newReceivers.remove(i);
11524 i--;
11525 }
11526 }
11527 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011528 if (newReceivers != null && newReceivers.size() == 0) {
11529 newReceivers = null;
11530 }
11531 if (receivers == null) {
11532 receivers = newReceivers;
11533 } else if (newReceivers != null) {
11534 // We need to concatenate the additional receivers
11535 // found with what we have do far. This would be easy,
11536 // but we also need to de-dup any receivers that are
11537 // singleUser.
11538 if (!scannedFirstReceivers) {
11539 // Collect any single user receivers we had already retrieved.
11540 scannedFirstReceivers = true;
11541 for (int i=0; i<receivers.size(); i++) {
11542 ResolveInfo ri = receivers.get(i);
11543 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11544 ComponentName cn = new ComponentName(
11545 ri.activityInfo.packageName, ri.activityInfo.name);
11546 if (singleUserReceivers == null) {
11547 singleUserReceivers = new HashSet<ComponentName>();
11548 }
11549 singleUserReceivers.add(cn);
11550 }
11551 }
11552 }
11553 // Add the new results to the existing results, tracking
11554 // and de-dupping single user receivers.
11555 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011556 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011557 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11558 ComponentName cn = new ComponentName(
11559 ri.activityInfo.packageName, ri.activityInfo.name);
11560 if (singleUserReceivers == null) {
11561 singleUserReceivers = new HashSet<ComponentName>();
11562 }
11563 if (!singleUserReceivers.contains(cn)) {
11564 singleUserReceivers.add(cn);
11565 receivers.add(ri);
11566 }
11567 } else {
11568 receivers.add(ri);
11569 }
11570 }
11571 }
11572 }
11573 } catch (RemoteException ex) {
11574 // pm is in same process, this will never happen.
11575 }
11576 return receivers;
11577 }
11578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011579 private final int broadcastIntentLocked(ProcessRecord callerApp,
11580 String callerPackage, Intent intent, String resolvedType,
11581 IIntentReceiver resultTo, int resultCode, String resultData,
11582 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011583 boolean ordered, boolean sticky, int callingPid, int callingUid,
11584 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011585 intent = new Intent(intent);
11586
Dianne Hackborne7f97212011-02-24 14:40:20 -080011587 // By default broadcasts do not go to stopped apps.
11588 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11589
Joe Onorato8a9b2202010-02-26 18:56:32 -080011590 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011592 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011593 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011594 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011596
Dianne Hackborn139748f2012-09-24 11:36:57 -070011597 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011598 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011599
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011600 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011601 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011602 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011603 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11604 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11605 Slog.w(TAG, "Skipping broadcast of " + intent
11606 + ": user " + userId + " is stopped");
11607 return ActivityManager.BROADCAST_SUCCESS;
11608 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011609 }
11610
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011611 /*
11612 * Prevent non-system code (defined here to be non-persistent
11613 * processes) from sending protected broadcasts.
11614 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011615 int callingAppId = UserHandle.getAppId(callingUid);
11616 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11617 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011618 callingUid == 0) {
11619 // Always okay.
11620 } else if (callerApp == null || !callerApp.persistent) {
11621 try {
11622 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11623 intent.getAction())) {
11624 String msg = "Permission Denial: not allowed to send broadcast "
11625 + intent.getAction() + " from pid="
11626 + callingPid + ", uid=" + callingUid;
11627 Slog.w(TAG, msg);
11628 throw new SecurityException(msg);
11629 }
11630 } catch (RemoteException e) {
11631 Slog.w(TAG, "Remote exception", e);
11632 return ActivityManager.BROADCAST_SUCCESS;
11633 }
11634 }
11635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 // Handle special intents: if this broadcast is from the package
11637 // manager about a package being removed, we need to remove all of
11638 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011639 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011641 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11642 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011643 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011644 || uidRemoved) {
11645 if (checkComponentPermission(
11646 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011647 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011648 == PackageManager.PERMISSION_GRANTED) {
11649 if (uidRemoved) {
11650 final Bundle intentExtras = intent.getExtras();
11651 final int uid = intentExtras != null
11652 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11653 if (uid >= 0) {
11654 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11655 synchronized (bs) {
11656 bs.removeUidStatsLocked(uid);
11657 }
11658 }
11659 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011660 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011661 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011662 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011663 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11664 if (list != null && (list.length > 0)) {
11665 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011666 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011667 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011668 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011669 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011670 }
11671 } else {
11672 Uri data = intent.getData();
11673 String ssp;
11674 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11675 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11676 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011677 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11678 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011679 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011680 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011681 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011682 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 }
11685 }
11686 }
11687 } else {
11688 String msg = "Permission Denial: " + intent.getAction()
11689 + " broadcast from " + callerPackage + " (pid=" + callingPid
11690 + ", uid=" + callingUid + ")"
11691 + " requires "
11692 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011693 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011694 throw new SecurityException(msg);
11695 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011696
11697 // Special case for adding a package: by default turn on compatibility
11698 // mode.
11699 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011700 Uri data = intent.getData();
11701 String ssp;
11702 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11703 mCompatModePackages.handlePackageAddedLocked(ssp,
11704 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 }
11707
11708 /*
11709 * If this is the time zone changed action, queue up a message that will reset the timezone
11710 * of all currently running processes. This message will get queued up before the broadcast
11711 * happens.
11712 */
11713 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11714 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11715 }
11716
Robert Greenwalt03595d02010-11-02 14:08:23 -070011717 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11718 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11719 }
11720
Robert Greenwalt434203a2010-10-11 16:00:27 -070011721 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11722 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11723 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11724 }
11725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726 // Add to the sticky list if requested.
11727 if (sticky) {
11728 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11729 callingPid, callingUid)
11730 != PackageManager.PERMISSION_GRANTED) {
11731 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11732 + callingPid + ", uid=" + callingUid
11733 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011734 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735 throw new SecurityException(msg);
11736 }
11737 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011738 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011740 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 }
11742 if (intent.getComponent() != null) {
11743 throw new SecurityException(
11744 "Sticky broadcasts can't target a specific component");
11745 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011746 // We use userId directly here, since the "all" target is maintained
11747 // as a separate set of sticky broadcasts.
11748 if (userId != UserHandle.USER_ALL) {
11749 // But first, if this is not a broadcast to all users, then
11750 // make sure it doesn't conflict with an existing broadcast to
11751 // all users.
11752 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11753 UserHandle.USER_ALL);
11754 if (stickies != null) {
11755 ArrayList<Intent> list = stickies.get(intent.getAction());
11756 if (list != null) {
11757 int N = list.size();
11758 int i;
11759 for (i=0; i<N; i++) {
11760 if (intent.filterEquals(list.get(i))) {
11761 throw new IllegalArgumentException(
11762 "Sticky broadcast " + intent + " for user "
11763 + userId + " conflicts with existing global broadcast");
11764 }
11765 }
11766 }
11767 }
11768 }
11769 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11770 if (stickies == null) {
11771 stickies = new HashMap<String, ArrayList<Intent>>();
11772 mStickyBroadcasts.put(userId, stickies);
11773 }
11774 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011775 if (list == null) {
11776 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011777 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 }
11779 int N = list.size();
11780 int i;
11781 for (i=0; i<N; i++) {
11782 if (intent.filterEquals(list.get(i))) {
11783 // This sticky already exists, replace it.
11784 list.set(i, new Intent(intent));
11785 break;
11786 }
11787 }
11788 if (i >= N) {
11789 list.add(new Intent(intent));
11790 }
11791 }
11792
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011793 int[] users;
11794 if (userId == UserHandle.USER_ALL) {
11795 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011796 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011797 } else {
11798 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011799 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011800 }
11801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011802 // Figure out who all will receive this broadcast.
11803 List receivers = null;
11804 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011805 // Need to resolve the intent to interested receivers...
11806 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11807 == 0) {
11808 receivers = collectReceiverComponents(intent, resolvedType, users);
11809 }
11810 if (intent.getComponent() == null) {
11811 registeredReceivers = mReceiverResolver.queryIntent(intent,
11812 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011813 }
11814
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011815 final boolean replacePending =
11816 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11817
Joe Onorato8a9b2202010-02-26 18:56:32 -080011818 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011819 + " replacePending=" + replacePending);
11820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11822 if (!ordered && NR > 0) {
11823 // If we are not serializing this broadcast, then send the
11824 // registered receivers separately so they don't wait for the
11825 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011826 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11827 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 callerPackage, callingPid, callingUid, requiredPermission,
11829 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011830 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011831 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011832 TAG, "Enqueueing parallel broadcast " + r);
11833 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011834 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011835 queue.enqueueParallelBroadcastLocked(r);
11836 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838 registeredReceivers = null;
11839 NR = 0;
11840 }
11841
11842 // Merge into one list.
11843 int ir = 0;
11844 if (receivers != null) {
11845 // A special case for PACKAGE_ADDED: do not allow the package
11846 // being added to see this broadcast. This prevents them from
11847 // using this as a back door to get run as soon as they are
11848 // installed. Maybe in the future we want to have a special install
11849 // broadcast or such for apps, but we'd like to deliberately make
11850 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011851 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011852 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11853 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11854 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011855 Uri data = intent.getData();
11856 if (data != null) {
11857 String pkgName = data.getSchemeSpecificPart();
11858 if (pkgName != null) {
11859 skipPackages = new String[] { pkgName };
11860 }
11861 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011862 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011863 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011864 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011865 if (skipPackages != null && (skipPackages.length > 0)) {
11866 for (String skipPackage : skipPackages) {
11867 if (skipPackage != null) {
11868 int NT = receivers.size();
11869 for (int it=0; it<NT; it++) {
11870 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11871 if (curt.activityInfo.packageName.equals(skipPackage)) {
11872 receivers.remove(it);
11873 it--;
11874 NT--;
11875 }
11876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 }
11878 }
11879 }
11880
11881 int NT = receivers != null ? receivers.size() : 0;
11882 int it = 0;
11883 ResolveInfo curt = null;
11884 BroadcastFilter curr = null;
11885 while (it < NT && ir < NR) {
11886 if (curt == null) {
11887 curt = (ResolveInfo)receivers.get(it);
11888 }
11889 if (curr == null) {
11890 curr = registeredReceivers.get(ir);
11891 }
11892 if (curr.getPriority() >= curt.priority) {
11893 // Insert this broadcast record into the final list.
11894 receivers.add(it, curr);
11895 ir++;
11896 curr = null;
11897 it++;
11898 NT++;
11899 } else {
11900 // Skip to the next ResolveInfo in the final list.
11901 it++;
11902 curt = null;
11903 }
11904 }
11905 }
11906 while (ir < NR) {
11907 if (receivers == null) {
11908 receivers = new ArrayList();
11909 }
11910 receivers.add(registeredReceivers.get(ir));
11911 ir++;
11912 }
11913
11914 if ((receivers != null && receivers.size() > 0)
11915 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011916 BroadcastQueue queue = broadcastQueueForIntent(intent);
11917 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011918 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011919 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011920 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011921 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011923 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924 if (DEBUG_BROADCAST) {
11925 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011926 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011927 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011928 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011929 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011930 queue.enqueueOrderedBroadcastLocked(r);
11931 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 }
11934
Dianne Hackborna4972e92012-03-14 10:38:05 -070011935 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 }
11937
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011938 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 // Refuse possible leaked file descriptors
11940 if (intent != null && intent.hasFileDescriptors() == true) {
11941 throw new IllegalArgumentException("File descriptors passed in Intent");
11942 }
11943
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011944 int flags = intent.getFlags();
11945
11946 if (!mProcessesReady) {
11947 // if the caller really truly claims to know what they're doing, go
11948 // ahead and allow the broadcast without launching any receivers
11949 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11950 intent = new Intent(intent);
11951 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11952 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11953 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11954 + " before boot completion");
11955 throw new IllegalStateException("Cannot broadcast before boot completed");
11956 }
11957 }
11958
11959 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11960 throw new IllegalArgumentException(
11961 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11962 }
11963
11964 return intent;
11965 }
11966
11967 public final int broadcastIntent(IApplicationThread caller,
11968 Intent intent, String resolvedType, IIntentReceiver resultTo,
11969 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011970 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011971 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011973 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11976 final int callingPid = Binder.getCallingPid();
11977 final int callingUid = Binder.getCallingUid();
11978 final long origId = Binder.clearCallingIdentity();
11979 int res = broadcastIntentLocked(callerApp,
11980 callerApp != null ? callerApp.info.packageName : null,
11981 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011982 resultCode, resultData, map, requiredPermission, serialized, sticky,
11983 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 Binder.restoreCallingIdentity(origId);
11985 return res;
11986 }
11987 }
11988
11989 int broadcastIntentInPackage(String packageName, int uid,
11990 Intent intent, String resolvedType, IIntentReceiver resultTo,
11991 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011992 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011993 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011994 intent = verifyBroadcastLocked(intent);
11995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011996 final long origId = Binder.clearCallingIdentity();
11997 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11998 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011999 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000 Binder.restoreCallingIdentity(origId);
12001 return res;
12002 }
12003 }
12004
Amith Yamasani742a6712011-05-04 14:49:28 -070012005 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012006 // Refuse possible leaked file descriptors
12007 if (intent != null && intent.hasFileDescriptors() == true) {
12008 throw new IllegalArgumentException("File descriptors passed in Intent");
12009 }
12010
Dianne Hackborn139748f2012-09-24 11:36:57 -070012011 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012012 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 synchronized(this) {
12015 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12016 != PackageManager.PERMISSION_GRANTED) {
12017 String msg = "Permission Denial: unbroadcastIntent() from pid="
12018 + Binder.getCallingPid()
12019 + ", uid=" + Binder.getCallingUid()
12020 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012021 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012022 throw new SecurityException(msg);
12023 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012024 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12025 if (stickies != null) {
12026 ArrayList<Intent> list = stickies.get(intent.getAction());
12027 if (list != null) {
12028 int N = list.size();
12029 int i;
12030 for (i=0; i<N; i++) {
12031 if (intent.filterEquals(list.get(i))) {
12032 list.remove(i);
12033 break;
12034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012036 if (list.size() <= 0) {
12037 stickies.remove(intent.getAction());
12038 }
12039 }
12040 if (stickies.size() <= 0) {
12041 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012042 }
12043 }
12044 }
12045 }
12046
12047 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12048 String resultData, Bundle resultExtras, boolean resultAbort,
12049 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012050 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12051 if (r == null) {
12052 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012053 return false;
12054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012055
Christopher Tatef46723b2012-01-26 14:19:24 -080012056 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12057 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 }
12059
12060 public void finishReceiver(IBinder who, int resultCode, String resultData,
12061 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012062 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063
12064 // Refuse possible leaked file descriptors
12065 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12066 throw new IllegalArgumentException("File descriptors passed in Bundle");
12067 }
12068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012070 try {
12071 boolean doNext = false;
12072 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073
Christopher Tatef46723b2012-01-26 14:19:24 -080012074 synchronized(this) {
12075 r = broadcastRecordForReceiverLocked(who);
12076 if (r != null) {
12077 doNext = r.queue.finishReceiverLocked(r, resultCode,
12078 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012080 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012081
Christopher Tatef46723b2012-01-26 14:19:24 -080012082 if (doNext) {
12083 r.queue.processNextBroadcast(false);
12084 }
12085 trimApplications();
12086 } finally {
12087 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012091 // =========================================================
12092 // INSTRUMENTATION
12093 // =========================================================
12094
12095 public boolean startInstrumentation(ComponentName className,
12096 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012097 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012098 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012099 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012100 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 // Refuse possible leaked file descriptors
12102 if (arguments != null && arguments.hasFileDescriptors()) {
12103 throw new IllegalArgumentException("File descriptors passed in Bundle");
12104 }
12105
12106 synchronized(this) {
12107 InstrumentationInfo ii = null;
12108 ApplicationInfo ai = null;
12109 try {
12110 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012111 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012112 ai = AppGlobals.getPackageManager().getApplicationInfo(
12113 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012114 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012115 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012116 }
12117 if (ii == null) {
12118 reportStartInstrumentationFailure(watcher, className,
12119 "Unable to find instrumentation info for: " + className);
12120 return false;
12121 }
12122 if (ai == null) {
12123 reportStartInstrumentationFailure(watcher, className,
12124 "Unable to find instrumentation target package: " + ii.targetPackage);
12125 return false;
12126 }
12127
12128 int match = mContext.getPackageManager().checkSignatures(
12129 ii.targetPackage, ii.packageName);
12130 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12131 String msg = "Permission Denial: starting instrumentation "
12132 + className + " from pid="
12133 + Binder.getCallingPid()
12134 + ", uid=" + Binder.getCallingPid()
12135 + " not allowed because package " + ii.packageName
12136 + " does not have a signature matching the target "
12137 + ii.targetPackage;
12138 reportStartInstrumentationFailure(watcher, className, msg);
12139 throw new SecurityException(msg);
12140 }
12141
12142 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012143 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012144 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012145 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012147 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012148 app.instrumentationProfileFile = profileFile;
12149 app.instrumentationArguments = arguments;
12150 app.instrumentationWatcher = watcher;
12151 app.instrumentationResultClass = className;
12152 Binder.restoreCallingIdentity(origId);
12153 }
12154
12155 return true;
12156 }
12157
12158 /**
12159 * Report errors that occur while attempting to start Instrumentation. Always writes the
12160 * error to the logs, but if somebody is watching, send the report there too. This enables
12161 * the "am" command to report errors with more information.
12162 *
12163 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12164 * @param cn The component name of the instrumentation.
12165 * @param report The error report.
12166 */
12167 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12168 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012169 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012170 try {
12171 if (watcher != null) {
12172 Bundle results = new Bundle();
12173 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12174 results.putString("Error", report);
12175 watcher.instrumentationStatus(cn, -1, results);
12176 }
12177 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012178 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012179 }
12180 }
12181
12182 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12183 if (app.instrumentationWatcher != null) {
12184 try {
12185 // NOTE: IInstrumentationWatcher *must* be oneway here
12186 app.instrumentationWatcher.instrumentationFinished(
12187 app.instrumentationClass,
12188 resultCode,
12189 results);
12190 } catch (RemoteException e) {
12191 }
12192 }
12193 app.instrumentationWatcher = null;
12194 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012195 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196 app.instrumentationProfileFile = null;
12197 app.instrumentationArguments = null;
12198
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012199 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012200 }
12201
12202 public void finishInstrumentation(IApplicationThread target,
12203 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012204 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012205 // Refuse possible leaked file descriptors
12206 if (results != null && results.hasFileDescriptors()) {
12207 throw new IllegalArgumentException("File descriptors passed in Intent");
12208 }
12209
12210 synchronized(this) {
12211 ProcessRecord app = getRecordForAppLocked(target);
12212 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012213 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012214 return;
12215 }
12216 final long origId = Binder.clearCallingIdentity();
12217 finishInstrumentationLocked(app, resultCode, results);
12218 Binder.restoreCallingIdentity(origId);
12219 }
12220 }
12221
12222 // =========================================================
12223 // CONFIGURATION
12224 // =========================================================
12225
12226 public ConfigurationInfo getDeviceConfigurationInfo() {
12227 ConfigurationInfo config = new ConfigurationInfo();
12228 synchronized (this) {
12229 config.reqTouchScreen = mConfiguration.touchscreen;
12230 config.reqKeyboardType = mConfiguration.keyboard;
12231 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012232 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12233 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012234 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12235 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012236 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12237 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012238 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12239 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012240 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012241 }
12242 return config;
12243 }
12244
12245 public Configuration getConfiguration() {
12246 Configuration ci;
12247 synchronized(this) {
12248 ci = new Configuration(mConfiguration);
12249 }
12250 return ci;
12251 }
12252
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012253 public void updatePersistentConfiguration(Configuration values) {
12254 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12255 "updateConfiguration()");
12256 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12257 "updateConfiguration()");
12258 if (values == null) {
12259 throw new NullPointerException("Configuration must not be null");
12260 }
12261
12262 synchronized(this) {
12263 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012264 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012265 Binder.restoreCallingIdentity(origId);
12266 }
12267 }
12268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012269 public void updateConfiguration(Configuration values) {
12270 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12271 "updateConfiguration()");
12272
12273 synchronized(this) {
12274 if (values == null && mWindowManager != null) {
12275 // sentinel: fetch the current configuration from the window manager
12276 values = mWindowManager.computeNewConfiguration();
12277 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012278
12279 if (mWindowManager != null) {
12280 mProcessList.applyDisplaySize(mWindowManager);
12281 }
12282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012284 if (values != null) {
12285 Settings.System.clearConfiguration(values);
12286 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012287 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012288 Binder.restoreCallingIdentity(origId);
12289 }
12290 }
12291
12292 /**
12293 * Do either or both things: (1) change the current configuration, and (2)
12294 * make sure the given activity is running with the (now) current
12295 * configuration. Returns true if the activity has been left running, or
12296 * false if <var>starting</var> is being destroyed to match the new
12297 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012298 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012299 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012300 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012301 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012302 // do nothing if we are headless
12303 if (mHeadless) return true;
12304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305 int changes = 0;
12306
12307 boolean kept = true;
12308
12309 if (values != null) {
12310 Configuration newConfig = new Configuration(mConfiguration);
12311 changes = newConfig.updateFrom(values);
12312 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012313 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012314 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012315 }
12316
Doug Zongker2bec3d42009-12-04 12:52:44 -080012317 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012318
Dianne Hackborn813075a62011-11-14 17:45:19 -080012319 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320 saveLocaleLocked(values.locale,
12321 !values.locale.equals(mConfiguration.locale),
12322 values.userSetLocale);
12323 }
12324
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012325 mConfigurationSeq++;
12326 if (mConfigurationSeq <= 0) {
12327 mConfigurationSeq = 1;
12328 }
12329 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012331 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012332
12333 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012334
12335 // TODO: If our config changes, should we auto dismiss any currently
12336 // showing dialogs?
12337 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012338
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012339 AttributeCache ac = AttributeCache.instance();
12340 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012341 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012344 // Make sure all resources in our process are updated
12345 // right now, so that anyone who is going to retrieve
12346 // resource values after we return will be sure to get
12347 // the new ones. This is especially important during
12348 // boot, where the first config change needs to guarantee
12349 // all resources have that config before following boot
12350 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012351 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012352
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012353 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012354 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012355 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012356 mHandler.sendMessage(msg);
12357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012359 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12360 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 try {
12362 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012363 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012364 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012365 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012366 }
12367 } catch (Exception e) {
12368 }
12369 }
12370 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012371 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012372 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12373 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012374 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012375 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012376 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012377 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12378 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12379 broadcastIntentLocked(null, null, intent,
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012380 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012381 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 }
12384 }
12385
12386 if (changes != 0 && starting == null) {
12387 // If the configuration changed, and the caller is not already
12388 // in the process of starting an activity, then find the top
12389 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012390 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012391 }
12392
12393 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012394 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012395 // And we need to make sure at this point that all other activities
12396 // are made visible with the correct configuration.
12397 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012398 }
12399
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012400 if (values != null && mWindowManager != null) {
12401 mWindowManager.setNewConfiguration(mConfiguration);
12402 }
12403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012404 return kept;
12405 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012406
12407 /**
12408 * Decide based on the configuration whether we should shouw the ANR,
12409 * crash, etc dialogs. The idea is that if there is no affordnace to
12410 * press the on-screen buttons, we shouldn't show the dialog.
12411 *
12412 * A thought: SystemUI might also want to get told about this, the Power
12413 * dialog / global actions also might want different behaviors.
12414 */
12415 private static final boolean shouldShowDialogs(Configuration config) {
12416 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12417 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419
12420 /**
12421 * Save the locale. You must be inside a synchronized (this) block.
12422 */
12423 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12424 if(isDiff) {
12425 SystemProperties.set("user.language", l.getLanguage());
12426 SystemProperties.set("user.region", l.getCountry());
12427 }
12428
12429 if(isPersist) {
12430 SystemProperties.set("persist.sys.language", l.getLanguage());
12431 SystemProperties.set("persist.sys.country", l.getCountry());
12432 SystemProperties.set("persist.sys.localevar", l.getVariant());
12433 }
12434 }
12435
Adam Powelldd8fab22012-03-22 17:47:27 -070012436 @Override
12437 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12438 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012439 return srec != null && srec.task.affinity != null &&
12440 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012441 }
12442
12443 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12444 Intent resultData) {
12445 ComponentName dest = destIntent.getComponent();
12446
12447 synchronized (this) {
12448 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012449 if (srec == null) {
12450 return false;
12451 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012452 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12453 final int start = history.indexOf(srec);
12454 if (start < 0) {
12455 // Current activity is not in history stack; do nothing.
12456 return false;
12457 }
12458 int finishTo = start - 1;
12459 ActivityRecord parent = null;
12460 boolean foundParentInTask = false;
12461 if (dest != null) {
12462 TaskRecord tr = srec.task;
12463 for (int i = start - 1; i >= 0; i--) {
12464 ActivityRecord r = history.get(i);
12465 if (tr != r.task) {
12466 // Couldn't find parent in the same task; stop at the one above this.
12467 // (Root of current task; in-app "home" behavior)
12468 // Always at least finish the current activity.
12469 finishTo = Math.min(start - 1, i + 1);
12470 parent = history.get(finishTo);
12471 break;
12472 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12473 r.info.name.equals(dest.getClassName())) {
12474 finishTo = i;
12475 parent = r;
12476 foundParentInTask = true;
12477 break;
12478 }
12479 }
12480 }
12481
12482 if (mController != null) {
12483 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12484 if (next != null) {
12485 // ask watcher if this is allowed
12486 boolean resumeOK = true;
12487 try {
12488 resumeOK = mController.activityResuming(next.packageName);
12489 } catch (RemoteException e) {
12490 mController = null;
12491 }
12492
12493 if (!resumeOK) {
12494 return false;
12495 }
12496 }
12497 }
12498 final long origId = Binder.clearCallingIdentity();
12499 for (int i = start; i > finishTo; i--) {
12500 ActivityRecord r = history.get(i);
12501 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012502 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012503 // Only return the supplied result for the first activity finished
12504 resultCode = Activity.RESULT_CANCELED;
12505 resultData = null;
12506 }
12507
12508 if (parent != null && foundParentInTask) {
12509 final int parentLaunchMode = parent.info.launchMode;
12510 final int destIntentFlags = destIntent.getFlags();
12511 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12512 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12513 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12514 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012515 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012516 } else {
12517 try {
12518 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012519 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012520 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12521 null, aInfo, parent.appToken, null,
12522 0, -1, parent.launchedFromUid, 0, null, true, null);
12523 foundParentInTask = res == ActivityManager.START_SUCCESS;
12524 } catch (RemoteException e) {
12525 foundParentInTask = false;
12526 }
12527 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012528 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012529 }
12530 }
12531 Binder.restoreCallingIdentity(origId);
12532 return foundParentInTask;
12533 }
12534 }
12535
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012536 public int getLaunchedFromUid(IBinder activityToken) {
12537 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12538 if (srec == null) {
12539 return -1;
12540 }
12541 return srec.launchedFromUid;
12542 }
12543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012544 // =========================================================
12545 // LIFETIME MANAGEMENT
12546 // =========================================================
12547
Christopher Tatef46723b2012-01-26 14:19:24 -080012548 // Returns which broadcast queue the app is the current [or imminent] receiver
12549 // on, or 'null' if the app is not an active broadcast recipient.
12550 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12551 BroadcastRecord r = app.curReceiver;
12552 if (r != null) {
12553 return r.queue;
12554 }
12555
12556 // It's not the current receiver, but it might be starting up to become one
12557 synchronized (this) {
12558 for (BroadcastQueue queue : mBroadcastQueues) {
12559 r = queue.mPendingBroadcast;
12560 if (r != null && r.curApp == app) {
12561 // found it; report which queue it's in
12562 return queue;
12563 }
12564 }
12565 }
12566
12567 return null;
12568 }
12569
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012570 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012571 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012572 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012573 // This adjustment has already been computed. If we are calling
12574 // from the top, we may have already computed our adjustment with
12575 // an earlier hidden adjustment that isn't really for us... if
12576 // so, use the new hidden adjustment.
12577 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012578 if (app.hasActivities) {
12579 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12580 } else if (app.hasClientActivities) {
12581 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12582 } else {
12583 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12584 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012585 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012586 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012587 }
12588
12589 if (app.thread == null) {
12590 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012591 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012592 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012593 }
12594
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012595 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12596 app.adjSource = null;
12597 app.adjTarget = null;
12598 app.empty = false;
12599 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012600 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012601
12602 final int activitiesSize = app.activities.size();
12603
Dianne Hackborn7d608422011-08-07 16:24:18 -070012604 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012605 // The max adjustment doesn't allow this app to be anything
12606 // below foreground, so it is not worth doing work for it.
12607 app.adjType = "fixed";
12608 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012609 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012610 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012611 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012612 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012613 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012614 // System process can do UI, and when they do we want to have
12615 // them trim their memory after the user leaves the UI. To
12616 // facilitate this, here we need to determine whether or not it
12617 // is currently showing UI.
12618 app.systemNoUi = true;
12619 if (app == TOP_APP) {
12620 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012621 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012622 } else if (activitiesSize > 0) {
12623 for (int j = 0; j < activitiesSize; j++) {
12624 final ActivityRecord r = app.activities.get(j);
12625 if (r.visible) {
12626 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012627 }
12628 if (r.app == app) {
12629 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012630 }
12631 }
12632 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012633 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012634 }
12635
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012636 app.keeping = false;
12637 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012638 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012639
The Android Open Source Project4df24232009-03-05 14:34:35 -080012640 // Determine the importance of the process, starting with most
12641 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012642 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012643 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012644 boolean foregroundActivities = false;
12645 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012646 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012647 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012649 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012650 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012651 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012652 foregroundActivities = true;
12653 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012654 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012655 } else if (app.instrumentationClass != null) {
12656 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012657 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012658 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012659 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012660 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012661 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012662 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012663 // counts as being in the foreground for OOM killer purposes.
12664 // It's placed in a sched group based on the nature of the
12665 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012666 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012667 schedGroup = (queue == mFgBroadcastQueue)
12668 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012669 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012670 } else if (app.executingServices.size() > 0) {
12671 // An app that is currently executing a service callback also
12672 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012673 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012674 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012675 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012676 } else {
12677 // Assume process is hidden (has activities); we will correct
12678 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012680 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012681 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012682 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012684
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012685 boolean hasStoppingActivities = false;
12686
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012687 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012688 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012689 for (int j = 0; j < activitiesSize; j++) {
12690 final ActivityRecord r = app.activities.get(j);
12691 if (r.visible) {
12692 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012693 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12694 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012695 app.adjType = "visible";
12696 }
12697 schedGroup = Process.THREAD_GROUP_DEFAULT;
12698 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012699 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012700 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012701 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012702 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012703 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12704 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012705 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012706 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012707 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012708 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012709 } else if (r.state == ActivityState.STOPPING) {
12710 // We will apply the actual adjustment later, because
12711 // we want to allow this process to immediately go through
12712 // any memory trimming that is in effect.
12713 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012714 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012715 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012716 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012717 if (r.app == app) {
12718 app.hasActivities = true;
12719 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012720 }
12721 }
12722
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012723 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012724 if (app.hasClientActivities) {
12725 adj = clientHiddenAdj;
12726 app.adjType = "bg-client-act";
12727 } else {
12728 // Whoops, this process is completely empty as far as we know
12729 // at this point.
12730 adj = emptyAdj;
12731 app.empty = true;
12732 app.adjType = "bg-empty";
12733 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012734 }
12735
Dianne Hackborn7d608422011-08-07 16:24:18 -070012736 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012737 if (app.foregroundServices) {
12738 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012739 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012740 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012741 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012742 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012743 } else if (app.forcingToForeground != null) {
12744 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012745 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012746 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012747 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012748 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012749 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012750 }
12751 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012752
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012753 if (app.foregroundServices) {
12754 interesting = true;
12755 }
12756
Dianne Hackborn7d608422011-08-07 16:24:18 -070012757 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012758 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012759 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012760 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012761 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012762 app.adjType = "heavy";
12763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012764
Dianne Hackborn7d608422011-08-07 16:24:18 -070012765 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012766 // This process is hosting what we currently consider to be the
12767 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012768 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012769 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012770 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012771 app.adjType = "home";
12772 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012773
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012774 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12775 && app.activities.size() > 0) {
12776 // This was the previous process that showed UI to the user.
12777 // We want to try to keep it around more aggressively, to give
12778 // a good experience around switching between two apps.
12779 adj = ProcessList.PREVIOUS_APP_ADJ;
12780 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12781 app.hidden = false;
12782 app.adjType = "previous";
12783 }
12784
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012785 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12786 + " reason=" + app.adjType);
12787
The Android Open Source Project4df24232009-03-05 14:34:35 -080012788 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 // there are applications dependent on our services or providers, but
12790 // this gives us a baseline and makes sure we don't get into an
12791 // infinite recursion.
12792 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012793 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012794
Christopher Tate6fa95972009-06-05 18:43:55 -070012795 if (mBackupTarget != null && app == mBackupTarget.app) {
12796 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012797 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012798 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012799 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012800 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012801 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012802 }
12803 }
12804
Dianne Hackborn7d608422011-08-07 16:24:18 -070012805 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012806 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012807 final long now = SystemClock.uptimeMillis();
12808 // This process is more important if the top activity is
12809 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012810 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012811 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012812 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012813 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012814 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012815 // If this process has shown some UI, let it immediately
12816 // go to the LRU list because it may be pretty heavy with
12817 // UI stuff. We'll tag it with a label just to help
12818 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012819 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012820 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012822 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012823 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012824 // This service has seen some activity within
12825 // recent memory, so we will keep its process ahead
12826 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012827 if (adj > ProcessList.SERVICE_ADJ) {
12828 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012829 app.adjType = "started-services";
12830 app.hidden = false;
12831 }
12832 }
12833 // If we have let the service slide into the background
12834 // state, still have some text describing what it is doing
12835 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012836 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012837 app.adjType = "started-bg-services";
12838 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012839 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012840 // Don't kill this process because it is doing work; it
12841 // has said it is doing work.
12842 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012844 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012845 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012846 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012847 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012848 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012849 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012850 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012851 // XXX should compute this based on the max of
12852 // all connected clients.
12853 ConnectionRecord cr = clist.get(i);
12854 if (cr.binding.client == app) {
12855 // Binding to ourself is not interesting.
12856 continue;
12857 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012858 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012859 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012860 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012861 int myHiddenAdj = hiddenAdj;
12862 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012863 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012864 myHiddenAdj = client.hiddenAdj;
12865 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012866 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012867 }
12868 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012869 int myClientHiddenAdj = clientHiddenAdj;
12870 if (myClientHiddenAdj > client.clientHiddenAdj) {
12871 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12872 myClientHiddenAdj = client.clientHiddenAdj;
12873 } else {
12874 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12875 }
12876 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012877 int myEmptyAdj = emptyAdj;
12878 if (myEmptyAdj > client.emptyAdj) {
12879 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12880 myEmptyAdj = client.emptyAdj;
12881 } else {
12882 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12883 }
12884 }
12885 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012886 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012887 String adjType = null;
12888 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12889 // Not doing bind OOM management, so treat
12890 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012891 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012892 // If this process has shown some UI, let it immediately
12893 // go to the LRU list because it may be pretty heavy with
12894 // UI stuff. We'll tag it with a label just to help
12895 // debug and understand what is going on.
12896 if (adj > clientAdj) {
12897 adjType = "bound-bg-ui-services";
12898 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012899 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012900 clientAdj = adj;
12901 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012902 if (now >= (s.lastActivity
12903 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012904 // This service has not seen activity within
12905 // recent memory, so allow it to drop to the
12906 // LRU list if there is no other reason to keep
12907 // it around. We'll also tag it with a label just
12908 // to help debug and undertand what is going on.
12909 if (adj > clientAdj) {
12910 adjType = "bound-bg-services";
12911 }
12912 clientAdj = adj;
12913 }
12914 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012915 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12916 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12917 // If this connection is keeping the service
12918 // created, then we want to try to better follow
12919 // its memory management semantics for activities.
12920 // That is, if it is sitting in the background
12921 // LRU list as a hidden process (with activities),
12922 // we don't want the service it is connected to
12923 // to go into the empty LRU and quickly get killed,
12924 // because I'll we'll do is just end up restarting
12925 // the service.
12926 app.hasClientActivities |= client.hasActivities;
12927 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012928 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012929 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012930 // If this process has recently shown UI, and
12931 // the process that is binding to it is less
12932 // important than being visible, then we don't
12933 // care about the binding as much as we care
12934 // about letting this process get into the LRU
12935 // list to be killed and restarted if needed for
12936 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012937 if (app.hasShownUi && app != mHomeProcess
12938 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012939 adjType = "bound-bg-ui-services";
12940 } else {
12941 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12942 |Context.BIND_IMPORTANT)) != 0) {
12943 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012944 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12945 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12946 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12947 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12948 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012949 adj = clientAdj;
12950 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012951 app.pendingUiClean = true;
12952 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12953 adj = ProcessList.VISIBLE_APP_ADJ;
12954 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012955 }
12956 if (!client.hidden) {
12957 app.hidden = false;
12958 }
12959 if (client.keeping) {
12960 app.keeping = true;
12961 }
12962 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012963 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012964 }
12965 if (adjType != null) {
12966 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012967 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12968 .REASON_SERVICE_IN_USE;
12969 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012970 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012971 app.adjTarget = s.name;
12972 }
12973 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12974 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12975 schedGroup = Process.THREAD_GROUP_DEFAULT;
12976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 }
12978 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012979 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012980 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012981 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012982 (a.visible || a.state == ActivityState.RESUMED
12983 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012984 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012985 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12986 schedGroup = Process.THREAD_GROUP_DEFAULT;
12987 }
12988 app.hidden = false;
12989 app.adjType = "service";
12990 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12991 .REASON_SERVICE_IN_USE;
12992 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012993 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012994 app.adjTarget = s.name;
12995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012997 }
12998 }
12999 }
13000 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013001
Dianne Hackborn287952c2010-09-22 22:34:31 -070013002 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013003 // would like to avoid killing it unless it would prevent the current
13004 // application from running. By default we put the process in
13005 // with the rest of the background processes; as we scan through
13006 // its services we may bump it up from there.
13007 if (adj > hiddenAdj) {
13008 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013009 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013010 app.adjType = "bg-services";
13011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013012 }
13013
Dianne Hackborn7d608422011-08-07 16:24:18 -070013014 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013015 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013016 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013017 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013018 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013019 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013020 for (int i = cpr.connections.size()-1;
13021 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13022 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13023 i--) {
13024 ContentProviderConnection conn = cpr.connections.get(i);
13025 ProcessRecord client = conn.client;
13026 if (client == app) {
13027 // Being our own client is not interesting.
13028 continue;
13029 }
13030 int myHiddenAdj = hiddenAdj;
13031 if (myHiddenAdj > client.hiddenAdj) {
13032 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13033 myHiddenAdj = client.hiddenAdj;
13034 } else {
13035 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013036 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013037 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013038 int myClientHiddenAdj = clientHiddenAdj;
13039 if (myClientHiddenAdj > client.clientHiddenAdj) {
13040 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13041 myClientHiddenAdj = client.clientHiddenAdj;
13042 } else {
13043 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13044 }
13045 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013046 int myEmptyAdj = emptyAdj;
13047 if (myEmptyAdj > client.emptyAdj) {
13048 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13049 myEmptyAdj = client.emptyAdj;
13050 } else {
13051 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13052 }
13053 }
13054 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013055 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013056 if (adj > clientAdj) {
13057 if (app.hasShownUi && app != mHomeProcess
13058 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13059 app.adjType = "bg-ui-provider";
13060 } else {
13061 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13062 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13063 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013064 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013065 if (!client.hidden) {
13066 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013067 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013068 if (client.keeping) {
13069 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013070 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013071 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13072 .REASON_PROVIDER_IN_USE;
13073 app.adjSource = client;
13074 app.adjSourceOom = clientAdj;
13075 app.adjTarget = cpr.name;
13076 }
13077 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13078 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 }
13080 }
13081 // If the provider has external (non-framework) process
13082 // dependencies, ensure that its adjustment is at least
13083 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013084 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013085 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13086 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013087 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013088 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013089 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013090 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013091 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013092 }
13093 }
13094 }
13095 }
13096
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013097 if (adj == ProcessList.SERVICE_ADJ) {
13098 if (doingAll) {
13099 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13100 mNewNumServiceProcs++;
13101 }
13102 if (app.serviceb) {
13103 adj = ProcessList.SERVICE_B_ADJ;
13104 }
13105 } else {
13106 app.serviceb = false;
13107 }
13108
13109 app.nonStoppingAdj = adj;
13110
13111 if (hasStoppingActivities) {
13112 // Only upgrade adjustment.
13113 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13114 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13115 app.adjType = "stopping";
13116 }
13117 }
13118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013119 app.curRawAdj = adj;
13120
Joe Onorato8a9b2202010-02-26 18:56:32 -080013121 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13123 if (adj > app.maxAdj) {
13124 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013125 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013126 schedGroup = Process.THREAD_GROUP_DEFAULT;
13127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013129 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013130 app.keeping = true;
13131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013133 if (app.hasAboveClient) {
13134 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13135 // then we need to drop its adjustment to be lower than the service's
13136 // in order to honor the request. We want to drop it by one adjustment
13137 // level... but there is special meaning applied to various levels so
13138 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013139 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013140 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013141 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13142 adj = ProcessList.VISIBLE_APP_ADJ;
13143 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13144 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13145 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13146 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013147 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013148 adj++;
13149 }
13150 }
13151
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013152 int importance = app.memImportance;
13153 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13154 app.curAdj = adj;
13155 app.curSchedGroup = schedGroup;
13156 if (!interesting) {
13157 // For this reporting, if there is not something explicitly
13158 // interesting in this process then we will push it to the
13159 // background importance.
13160 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13161 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13162 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13163 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13164 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13165 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13166 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13167 } else if (adj >= ProcessList.SERVICE_ADJ) {
13168 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13169 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13170 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13171 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13172 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13173 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13174 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13175 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13176 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13177 } else {
13178 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13179 }
13180 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013181
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013182 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13183 if (foregroundActivities != app.foregroundActivities) {
13184 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13185 }
13186 if (changes != 0) {
13187 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13188 app.memImportance = importance;
13189 app.foregroundActivities = foregroundActivities;
13190 int i = mPendingProcessChanges.size()-1;
13191 ProcessChangeItem item = null;
13192 while (i >= 0) {
13193 item = mPendingProcessChanges.get(i);
13194 if (item.pid == app.pid) {
13195 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13196 break;
13197 }
13198 i--;
13199 }
13200 if (i < 0) {
13201 // No existing item in pending changes; need a new one.
13202 final int NA = mAvailProcessChanges.size();
13203 if (NA > 0) {
13204 item = mAvailProcessChanges.remove(NA-1);
13205 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13206 } else {
13207 item = new ProcessChangeItem();
13208 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13209 }
13210 item.changes = 0;
13211 item.pid = app.pid;
13212 item.uid = app.info.uid;
13213 if (mPendingProcessChanges.size() == 0) {
13214 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13215 "*** Enqueueing dispatch processes changed!");
13216 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13217 }
13218 mPendingProcessChanges.add(item);
13219 }
13220 item.changes |= changes;
13221 item.importance = importance;
13222 item.foregroundActivities = foregroundActivities;
13223 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13224 + Integer.toHexString(System.identityHashCode(item))
13225 + " " + app.toShortString() + ": changes=" + item.changes
13226 + " importance=" + item.importance
13227 + " foreground=" + item.foregroundActivities
13228 + " type=" + app.adjType + " source=" + app.adjSource
13229 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013230 }
13231
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013232 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013233 }
13234
13235 /**
13236 * Ask a given process to GC right now.
13237 */
13238 final void performAppGcLocked(ProcessRecord app) {
13239 try {
13240 app.lastRequestedGc = SystemClock.uptimeMillis();
13241 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013242 if (app.reportLowMemory) {
13243 app.reportLowMemory = false;
13244 app.thread.scheduleLowMemory();
13245 } else {
13246 app.thread.processInBackground();
13247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 }
13249 } catch (Exception e) {
13250 // whatever.
13251 }
13252 }
13253
13254 /**
13255 * Returns true if things are idle enough to perform GCs.
13256 */
Josh Bartel7f208742010-02-25 11:01:44 -060013257 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013258 boolean processingBroadcasts = false;
13259 for (BroadcastQueue q : mBroadcastQueues) {
13260 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13261 processingBroadcasts = true;
13262 }
13263 }
13264 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013265 && (mSleeping || (mMainStack.mResumedActivity != null &&
13266 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267 }
13268
13269 /**
13270 * Perform GCs on all processes that are waiting for it, but only
13271 * if things are idle.
13272 */
13273 final void performAppGcsLocked() {
13274 final int N = mProcessesToGc.size();
13275 if (N <= 0) {
13276 return;
13277 }
Josh Bartel7f208742010-02-25 11:01:44 -060013278 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013279 while (mProcessesToGc.size() > 0) {
13280 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013281 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013282 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13283 <= SystemClock.uptimeMillis()) {
13284 // To avoid spamming the system, we will GC processes one
13285 // at a time, waiting a few seconds between each.
13286 performAppGcLocked(proc);
13287 scheduleAppGcsLocked();
13288 return;
13289 } else {
13290 // It hasn't been long enough since we last GCed this
13291 // process... put it in the list to wait for its time.
13292 addProcessToGcListLocked(proc);
13293 break;
13294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013295 }
13296 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013297
13298 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013299 }
13300 }
13301
13302 /**
13303 * If all looks good, perform GCs on all processes waiting for them.
13304 */
13305 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013306 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013307 performAppGcsLocked();
13308 return;
13309 }
13310 // Still not idle, wait some more.
13311 scheduleAppGcsLocked();
13312 }
13313
13314 /**
13315 * Schedule the execution of all pending app GCs.
13316 */
13317 final void scheduleAppGcsLocked() {
13318 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013319
13320 if (mProcessesToGc.size() > 0) {
13321 // Schedule a GC for the time to the next process.
13322 ProcessRecord proc = mProcessesToGc.get(0);
13323 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13324
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013325 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013326 long now = SystemClock.uptimeMillis();
13327 if (when < (now+GC_TIMEOUT)) {
13328 when = now + GC_TIMEOUT;
13329 }
13330 mHandler.sendMessageAtTime(msg, when);
13331 }
13332 }
13333
13334 /**
13335 * Add a process to the array of processes waiting to be GCed. Keeps the
13336 * list in sorted order by the last GC time. The process can't already be
13337 * on the list.
13338 */
13339 final void addProcessToGcListLocked(ProcessRecord proc) {
13340 boolean added = false;
13341 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13342 if (mProcessesToGc.get(i).lastRequestedGc <
13343 proc.lastRequestedGc) {
13344 added = true;
13345 mProcessesToGc.add(i+1, proc);
13346 break;
13347 }
13348 }
13349 if (!added) {
13350 mProcessesToGc.add(0, proc);
13351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013352 }
13353
13354 /**
13355 * Set up to ask a process to GC itself. This will either do it
13356 * immediately, or put it on the list of processes to gc the next
13357 * time things are idle.
13358 */
13359 final void scheduleAppGcLocked(ProcessRecord app) {
13360 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013361 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013362 return;
13363 }
13364 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013365 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013366 scheduleAppGcsLocked();
13367 }
13368 }
13369
Dianne Hackborn287952c2010-09-22 22:34:31 -070013370 final void checkExcessivePowerUsageLocked(boolean doKills) {
13371 updateCpuStatsNow();
13372
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013373 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013374 boolean doWakeKills = doKills;
13375 boolean doCpuKills = doKills;
13376 if (mLastPowerCheckRealtime == 0) {
13377 doWakeKills = false;
13378 }
13379 if (mLastPowerCheckUptime == 0) {
13380 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013381 }
13382 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013383 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013384 }
13385 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013386 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13387 final long curUptime = SystemClock.uptimeMillis();
13388 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13389 mLastPowerCheckRealtime = curRealtime;
13390 mLastPowerCheckUptime = curUptime;
13391 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13392 doWakeKills = false;
13393 }
13394 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13395 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013396 }
13397 int i = mLruProcesses.size();
13398 while (i > 0) {
13399 i--;
13400 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013401 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013402 long wtime;
13403 synchronized (stats) {
13404 wtime = stats.getProcessWakeTime(app.info.uid,
13405 app.pid, curRealtime);
13406 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013407 long wtimeUsed = wtime - app.lastWakeTime;
13408 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13409 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013410 StringBuilder sb = new StringBuilder(128);
13411 sb.append("Wake for ");
13412 app.toShortString(sb);
13413 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013414 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013415 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013416 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013417 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013418 sb.append((wtimeUsed*100)/realtimeSince);
13419 sb.append("%)");
13420 Slog.i(TAG, sb.toString());
13421 sb.setLength(0);
13422 sb.append("CPU for ");
13423 app.toShortString(sb);
13424 sb.append(": over ");
13425 TimeUtils.formatDuration(uptimeSince, sb);
13426 sb.append(" used ");
13427 TimeUtils.formatDuration(cputimeUsed, sb);
13428 sb.append(" (");
13429 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013430 sb.append("%)");
13431 Slog.i(TAG, sb.toString());
13432 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013433 // If a process has held a wake lock for more
13434 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013435 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013436 if (doWakeKills && realtimeSince > 0
13437 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13438 synchronized (stats) {
13439 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13440 realtimeSince, wtimeUsed);
13441 }
13442 Slog.w(TAG, "Excessive wake lock in " + app.processName
13443 + " (pid " + app.pid + "): held " + wtimeUsed
13444 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013445 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013446 app.processName, app.setAdj, "excessive wake lock");
13447 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013448 } else if (doCpuKills && uptimeSince > 0
13449 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13450 synchronized (stats) {
13451 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13452 uptimeSince, cputimeUsed);
13453 }
13454 Slog.w(TAG, "Excessive CPU in " + app.processName
13455 + " (pid " + app.pid + "): used " + cputimeUsed
13456 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013457 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013458 app.processName, app.setAdj, "excessive cpu");
13459 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013460 } else {
13461 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013462 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013463 }
13464 }
13465 }
13466 }
13467
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013468 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013469 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013470 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013471 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013472 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013473
13474 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013475 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013476 }
13477
Dianne Hackborn287952c2010-09-22 22:34:31 -070013478 final boolean wasKeeping = app.keeping;
13479
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013480 boolean success = true;
13481
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013482 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013483
Jeff Brown10e89712011-07-08 18:52:57 -070013484 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013485 if (wasKeeping && !app.keeping) {
13486 // This app is no longer something we want to keep. Note
13487 // its current wake lock time to later know to kill it if
13488 // it is not behaving well.
13489 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13490 synchronized (stats) {
13491 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13492 app.pid, SystemClock.elapsedRealtime());
13493 }
13494 app.lastCpuTime = app.curCpuTime;
13495 }
13496
13497 app.setRawAdj = app.curRawAdj;
13498 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013499
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013500 if (app.curAdj != app.setAdj) {
13501 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013502 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013503 TAG, "Set " + app.pid + " " + app.processName +
13504 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013505 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013506 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013507 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013508 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013509 }
13510 }
13511 if (app.setSchedGroup != app.curSchedGroup) {
13512 app.setSchedGroup = app.curSchedGroup;
13513 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13514 "Setting process group of " + app.processName
13515 + " to " + app.curSchedGroup);
13516 if (app.waitingToKill != null &&
13517 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13518 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013519 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013520 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013521 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013522 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013523 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013524 } else {
13525 if (true) {
13526 long oldId = Binder.clearCallingIdentity();
13527 try {
13528 Process.setProcessGroup(app.pid, app.curSchedGroup);
13529 } catch (Exception e) {
13530 Slog.w(TAG, "Failed setting process group of " + app.pid
13531 + " to " + app.curSchedGroup);
13532 e.printStackTrace();
13533 } finally {
13534 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013535 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013536 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013537 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013538 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013539 app.thread.setSchedulingGroup(app.curSchedGroup);
13540 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013541 }
13542 }
13543 }
13544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013545 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013546 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013547 }
13548
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013549 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013550 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013551 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013552 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013554 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013555 }
13556 }
13557 return resumedActivity;
13558 }
13559
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013560 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013561 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013562 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13563 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013564 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13565 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013566
13567 mAdjSeq++;
13568
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013569 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13570 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013571 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13572 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013573 if (nowHidden != wasHidden) {
13574 // Changed to/from hidden state, so apps after it in the LRU
13575 // list may also be changed.
13576 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013577 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013578 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013579 }
13580
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013581 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013582 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013583 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013584 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013585
13586 if (false) {
13587 RuntimeException e = new RuntimeException();
13588 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013589 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590 }
13591
13592 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013593 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013594
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013595 final int emptyProcessLimit;
13596 final int hiddenProcessLimit;
13597 if (mProcessLimit <= 0) {
13598 emptyProcessLimit = hiddenProcessLimit = 0;
13599 } else if (mProcessLimit == 1) {
13600 emptyProcessLimit = 1;
13601 hiddenProcessLimit = 0;
13602 } else {
13603 emptyProcessLimit = (mProcessLimit*2)/3;
13604 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13605 }
13606
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013607 // Let's determine how many processes we have running vs.
13608 // how many slots we have for background processes; we may want
13609 // to put multiple processes in a slot of there are enough of
13610 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013611 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13612 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013613 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13614 if (numEmptyProcs > hiddenProcessLimit) {
13615 // If there are more empty processes than our limit on hidden
13616 // processes, then use the hidden process limit for the factor.
13617 // This ensures that the really old empty processes get pushed
13618 // down to the bottom, so if we are running low on memory we will
13619 // have a better chance at keeping around more hidden processes
13620 // instead of a gazillion empty processes.
13621 numEmptyProcs = hiddenProcessLimit;
13622 }
13623 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013624 if (emptyFactor < 1) emptyFactor = 1;
13625 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13626 if (hiddenFactor < 1) hiddenFactor = 1;
13627 int stepHidden = 0;
13628 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013629 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013630 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013631 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013632
13633 mNumNonHiddenProcs = 0;
13634 mNumHiddenProcs = 0;
13635
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013636 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013637 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013638 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013639 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013640 int nextHiddenAdj = curHiddenAdj+1;
13641 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13642 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013643 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013644 while (i > 0) {
13645 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013646 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013647 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013648 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013649 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013650 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13651 // This process was assigned as a hidden process... step the
13652 // hidden level.
13653 mNumHiddenProcs++;
13654 if (curHiddenAdj != nextHiddenAdj) {
13655 stepHidden++;
13656 if (stepHidden >= hiddenFactor) {
13657 stepHidden = 0;
13658 curHiddenAdj = nextHiddenAdj;
13659 nextHiddenAdj += 2;
13660 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13661 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13662 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013663 if (curClientHiddenAdj <= curHiddenAdj) {
13664 curClientHiddenAdj = curHiddenAdj + 1;
13665 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13666 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13667 }
13668 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013669 }
13670 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013671 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013672 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013673 Slog.i(TAG, "No longer want " + app.processName
13674 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013675 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013676 app.processName, app.setAdj, "too many background");
13677 app.killedBackground = true;
13678 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013679 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013680 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13681 // This process has a client that has activities. We will have
13682 // given it the current hidden adj; here we will just leave it
13683 // without stepping the hidden adj.
13684 curClientHiddenAdj++;
13685 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13686 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13687 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013688 } else {
13689 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13690 // This process was assigned as an empty process... step the
13691 // empty level.
13692 if (curEmptyAdj != nextEmptyAdj) {
13693 stepEmpty++;
13694 if (stepEmpty >= emptyFactor) {
13695 stepEmpty = 0;
13696 curEmptyAdj = nextEmptyAdj;
13697 nextEmptyAdj += 2;
13698 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13699 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13700 }
13701 }
13702 }
13703 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13704 mNumNonHiddenProcs++;
13705 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013706 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13707 && !app.hasClientActivities) {
13708 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13709 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013710 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013711 + " (pid " + app.pid + "): empty for "
13712 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13713 / 1000) + "s");
13714 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13715 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013716 app.killedBackground = true;
13717 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013718 } else {
13719 numEmpty++;
13720 if (numEmpty > emptyProcessLimit) {
13721 Slog.i(TAG, "No longer want " + app.processName
13722 + " (pid " + app.pid + "): empty #" + numEmpty);
13723 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13724 app.processName, app.setAdj, "too many background");
13725 app.killedBackground = true;
13726 Process.killProcessQuiet(app.pid);
13727 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013728 }
13729 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013730 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013731 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013732 // If this is an isolated process, and there are no
13733 // services running in it, then the process is no longer
13734 // needed. We agressively kill these because we can by
13735 // definition not re-use the same process again, and it is
13736 // good to avoid having whatever code was running in them
13737 // left sitting around after no longer needed.
13738 Slog.i(TAG, "Isolated process " + app.processName
13739 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013740 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013741 app.processName, app.setAdj, "isolated not needed");
13742 app.killedBackground = true;
13743 Process.killProcessQuiet(app.pid);
13744 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013745 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13746 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13747 && !app.killedBackground) {
13748 numTrimming++;
13749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013750 }
13751 }
13752
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013753 mNumServiceProcs = mNewNumServiceProcs;
13754
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013755 // Now determine the memory trimming level of background processes.
13756 // Unfortunately we need to start at the back of the list to do this
13757 // properly. We only do this if the number of background apps we
13758 // are managing to keep around is less than half the maximum we desire;
13759 // if we are keeping a good number around, we'll let them use whatever
13760 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013761 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13762 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013763 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013764 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013765 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013766 int minFactor = 2;
13767 if (mHomeProcess != null) minFactor++;
13768 if (mPreviousProcess != null) minFactor++;
13769 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013770 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013771 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013772 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013773 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013774 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013775 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13776 } else {
13777 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13778 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013779 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013780 for (i=0; i<N; i++) {
13781 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013782 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13783 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013784 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013785 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13786 try {
13787 app.thread.scheduleTrimMemory(curLevel);
13788 } catch (RemoteException e) {
13789 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013790 if (false) {
13791 // For now we won't do this; our memory trimming seems
13792 // to be good enough at this point that destroying
13793 // activities causes more harm than good.
13794 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13795 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013796 // Need to do this on its own message because the stack may not
13797 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013798 // For these apps we will also finish their activities
13799 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013800 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013801 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013802 }
13803 }
13804 app.trimMemoryLevel = curLevel;
13805 step++;
13806 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013807 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013808 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013809 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13810 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013811 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013812 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13813 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013814 break;
13815 }
13816 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013817 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013818 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013819 && app.thread != null) {
13820 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013821 app.thread.scheduleTrimMemory(
13822 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013823 } catch (RemoteException e) {
13824 }
13825 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013826 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013827 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013828 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013829 && app.pendingUiClean) {
13830 // If this application is now in the background and it
13831 // had done UI, then give it the special trim level to
13832 // have it free UI resources.
13833 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13834 if (app.trimMemoryLevel < level && app.thread != null) {
13835 try {
13836 app.thread.scheduleTrimMemory(level);
13837 } catch (RemoteException e) {
13838 }
13839 }
13840 app.pendingUiClean = false;
13841 }
13842 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013843 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013844 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013845 } catch (RemoteException e) {
13846 }
13847 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013848 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013849 }
13850 }
13851 } else {
13852 final int N = mLruProcesses.size();
13853 for (i=0; i<N; i++) {
13854 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013855 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013856 && app.pendingUiClean) {
13857 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13858 && app.thread != null) {
13859 try {
13860 app.thread.scheduleTrimMemory(
13861 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13862 } catch (RemoteException e) {
13863 }
13864 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013865 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013866 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013867 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013868 }
13869 }
13870
13871 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013872 // Need to do this on its own message because the stack may not
13873 // be in a consistent state at this point.
13874 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013876 }
13877
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013878 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013879 synchronized (this) {
13880 int i;
13881
13882 // First remove any unused application processes whose package
13883 // has been removed.
13884 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13885 final ProcessRecord app = mRemovedProcesses.get(i);
13886 if (app.activities.size() == 0
13887 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013888 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013889 TAG, "Exiting empty application process "
13890 + app.processName + " ("
13891 + (app.thread != null ? app.thread.asBinder() : null)
13892 + ")\n");
13893 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013894 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013895 app.processName, app.setAdj, "empty");
13896 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013897 } else {
13898 try {
13899 app.thread.scheduleExit();
13900 } catch (Exception e) {
13901 // Ignore exceptions.
13902 }
13903 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013904 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013905 mRemovedProcesses.remove(i);
13906
13907 if (app.persistent) {
13908 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013909 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013910 }
13911 }
13912 }
13913 }
13914
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013915 // Now update the oom adj for all processes.
13916 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013917 }
13918 }
13919
13920 /** This method sends the specified signal to each of the persistent apps */
13921 public void signalPersistentProcesses(int sig) throws RemoteException {
13922 if (sig != Process.SIGNAL_USR1) {
13923 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13924 }
13925
13926 synchronized (this) {
13927 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13928 != PackageManager.PERMISSION_GRANTED) {
13929 throw new SecurityException("Requires permission "
13930 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13931 }
13932
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013933 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13934 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013935 if (r.thread != null && r.persistent) {
13936 Process.sendSignal(r.pid, sig);
13937 }
13938 }
13939 }
13940 }
13941
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013942 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13943 if (proc == null || proc == mProfileProc) {
13944 proc = mProfileProc;
13945 path = mProfileFile;
13946 profileType = mProfileType;
13947 clearProfilerLocked();
13948 }
13949 if (proc == null) {
13950 return;
13951 }
13952 try {
13953 proc.thread.profilerControl(false, path, null, profileType);
13954 } catch (RemoteException e) {
13955 throw new IllegalStateException("Process disappeared");
13956 }
13957 }
13958
13959 private void clearProfilerLocked() {
13960 if (mProfileFd != null) {
13961 try {
13962 mProfileFd.close();
13963 } catch (IOException e) {
13964 }
13965 }
13966 mProfileApp = null;
13967 mProfileProc = null;
13968 mProfileFile = null;
13969 mProfileType = 0;
13970 mAutoStopProfiler = false;
13971 }
13972
Dianne Hackborn1676c852012-09-10 14:52:30 -070013973 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013974 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013975
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013976 try {
13977 synchronized (this) {
13978 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13979 // its own permission.
13980 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13981 != PackageManager.PERMISSION_GRANTED) {
13982 throw new SecurityException("Requires permission "
13983 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013984 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013985
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013986 if (start && fd == null) {
13987 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013988 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013989
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013990 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013991 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013992 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013993 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013994
13995 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013996 throw new IllegalArgumentException("Unknown process: " + process);
13997 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013998
13999 if (start) {
14000 stopProfilerLocked(null, null, 0);
14001 setProfileApp(proc.info, proc.processName, path, fd, false);
14002 mProfileProc = proc;
14003 mProfileType = profileType;
14004 try {
14005 fd = fd.dup();
14006 } catch (IOException e) {
14007 fd = null;
14008 }
14009 proc.thread.profilerControl(start, path, fd, profileType);
14010 fd = null;
14011 mProfileFd = null;
14012 } else {
14013 stopProfilerLocked(proc, path, profileType);
14014 if (fd != null) {
14015 try {
14016 fd.close();
14017 } catch (IOException e) {
14018 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014019 }
14020 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014021
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014022 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014023 }
14024 } catch (RemoteException e) {
14025 throw new IllegalStateException("Process disappeared");
14026 } finally {
14027 if (fd != null) {
14028 try {
14029 fd.close();
14030 } catch (IOException e) {
14031 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014032 }
14033 }
14034 }
Andy McFadden824c5102010-07-09 16:26:57 -070014035
Dianne Hackborn1676c852012-09-10 14:52:30 -070014036 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014037 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014038 userId, true, true, callName, null);
14039 ProcessRecord proc = null;
14040 try {
14041 int pid = Integer.parseInt(process);
14042 synchronized (mPidsSelfLocked) {
14043 proc = mPidsSelfLocked.get(pid);
14044 }
14045 } catch (NumberFormatException e) {
14046 }
14047
14048 if (proc == null) {
14049 HashMap<String, SparseArray<ProcessRecord>> all
14050 = mProcessNames.getMap();
14051 SparseArray<ProcessRecord> procs = all.get(process);
14052 if (procs != null && procs.size() > 0) {
14053 proc = procs.valueAt(0);
14054 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14055 for (int i=1; i<procs.size(); i++) {
14056 ProcessRecord thisProc = procs.valueAt(i);
14057 if (thisProc.userId == userId) {
14058 proc = thisProc;
14059 break;
14060 }
14061 }
14062 }
14063 }
14064 }
14065
14066 return proc;
14067 }
14068
14069 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014070 String path, ParcelFileDescriptor fd) throws RemoteException {
14071
14072 try {
14073 synchronized (this) {
14074 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14075 // its own permission (same as profileControl).
14076 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14077 != PackageManager.PERMISSION_GRANTED) {
14078 throw new SecurityException("Requires permission "
14079 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14080 }
14081
14082 if (fd == null) {
14083 throw new IllegalArgumentException("null fd");
14084 }
14085
Dianne Hackborn1676c852012-09-10 14:52:30 -070014086 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014087 if (proc == null || proc.thread == null) {
14088 throw new IllegalArgumentException("Unknown process: " + process);
14089 }
14090
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014091 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14092 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014093 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14094 throw new SecurityException("Process not debuggable: " + proc);
14095 }
14096 }
14097
14098 proc.thread.dumpHeap(managed, path, fd);
14099 fd = null;
14100 return true;
14101 }
14102 } catch (RemoteException e) {
14103 throw new IllegalStateException("Process disappeared");
14104 } finally {
14105 if (fd != null) {
14106 try {
14107 fd.close();
14108 } catch (IOException e) {
14109 }
14110 }
14111 }
14112 }
14113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014114 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14115 public void monitor() {
14116 synchronized (this) { }
14117 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014118
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014119 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014120 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14121 ProcessRecord processRecord = mLruProcesses.get(i);
14122 try {
14123 if (processRecord.thread != null) {
14124 processRecord.thread.setCoreSettings(settings);
14125 }
14126 } catch (RemoteException re) {
14127 /* ignore */
14128 }
14129 }
14130 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014131
14132 // Multi-user methods
14133
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014134 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070014135 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014136 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14137 != PackageManager.PERMISSION_GRANTED) {
14138 String msg = "Permission Denial: switchUser() from pid="
14139 + Binder.getCallingPid()
14140 + ", uid=" + Binder.getCallingUid()
14141 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14142 Slog.w(TAG, msg);
14143 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014144 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014145
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014146 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014147 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014148 synchronized (this) {
14149 final int oldUserId = mCurrentUserId;
14150 if (oldUserId == userId) {
14151 return true;
14152 }
14153
14154 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14155 if (userInfo == null) {
14156 Slog.w(TAG, "No user info for user #" + userId);
14157 return false;
14158 }
14159
14160 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14161 R.anim.screen_user_enter);
14162
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014163 boolean needStart = false;
14164
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014165 // If the user we are switching to is not currently started, then
14166 // we need to start it now.
14167 if (mStartedUsers.get(userId) == null) {
14168 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014169 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014170 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014171 }
14172
14173 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014174 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014175 final Integer userIdInt = Integer.valueOf(userId);
14176 mUserLru.remove(userIdInt);
14177 mUserLru.add(userIdInt);
14178
Craig Mautnerf1b67412012-09-19 13:18:29 -070014179 mWindowManager.setCurrentUser(userId);
14180
Adam Cohenf7522022012-10-03 20:03:18 -070014181 // Once the internal notion of the active user has switched, we lock the device
14182 // with the option to show the user switcher on the keyguard.
14183 mWindowManager.lockNow(LockPatternUtils.USER_SWITCH_LOCK_OPTIONS);
14184
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014185 final UserStartedState uss = mStartedUsers.get(userId);
14186
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014187 // Make sure user is in the started state. If it is currently
14188 // stopping, we need to knock that off.
14189 if (uss.mState == UserStartedState.STATE_STOPPING) {
14190 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14191 // so we can just fairly silently bring the user back from
14192 // the almost-dead.
14193 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014194 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014195 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014196 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14197 // This means ACTION_SHUTDOWN has been sent, so we will
14198 // need to treat this as a new boot of the user.
14199 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014200 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014201 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014202 }
14203
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014204 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14205 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14206 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14207 oldUserId, userId, uss));
14208 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14209 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014210 if (needStart) {
14211 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14212 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14213 | Intent.FLAG_RECEIVER_FOREGROUND);
14214 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14215 broadcastIntentLocked(null, null, intent,
14216 null, null, 0, null, null, null,
14217 false, false, MY_PID, Process.SYSTEM_UID, userId);
14218 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014219
14220 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14221 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014222 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014223 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014224 broadcastIntentLocked(null, null, intent, null,
14225 new IIntentReceiver.Stub() {
14226 public void performReceive(Intent intent, int resultCode,
14227 String data, Bundle extras, boolean ordered,
14228 boolean sticky, int sendingUser) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014229 userInitialized(uss);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014230 }
14231 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14232 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014233 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014234 } else {
14235 getUserManagerLocked().makeInitialized(userInfo.id);
14236 }
14237 }
14238
14239 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14240 if (!haveActivities) {
14241 startHomeActivityLocked(userId);
14242 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014243
Jeff Sharkey86597df2012-11-09 15:00:31 -080014244 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014245 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014246 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014247 if (needStart) {
14248 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14249 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14250 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14251 broadcastIntentLocked(null, null, intent,
14252 null, new IIntentReceiver.Stub() {
14253 @Override
14254 public void performReceive(Intent intent, int resultCode, String data,
14255 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14256 throws RemoteException {
14257 }
14258 }, 0, null, null,
14259 android.Manifest.permission.INTERACT_ACROSS_USERS,
14260 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14261 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014262 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014263 } finally {
14264 Binder.restoreCallingIdentity(ident);
14265 }
Amith Yamasani13593602012-03-22 16:16:17 -070014266
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014267 return true;
14268 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014269
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014270 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14271 long ident = Binder.clearCallingIdentity();
14272 try {
14273 Intent intent;
14274 if (oldUserId >= 0) {
14275 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014276 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14277 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014278 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14279 broadcastIntentLocked(null, null, intent,
14280 null, null, 0, null, null, null,
14281 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14282 }
14283 if (newUserId >= 0) {
14284 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014285 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14286 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014287 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14288 broadcastIntentLocked(null, null, intent,
14289 null, null, 0, null, null, null,
14290 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14291 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014292 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14293 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014294 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14295 broadcastIntentLocked(null, null, intent,
14296 null, null, 0, null, null,
14297 android.Manifest.permission.MANAGE_USERS,
14298 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14299 }
14300 } finally {
14301 Binder.restoreCallingIdentity(ident);
14302 }
14303 }
14304
14305 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14306 final int newUserId) {
14307 final int N = mUserSwitchObservers.beginBroadcast();
14308 if (N > 0) {
14309 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14310 int mCount = 0;
14311 @Override
14312 public void sendResult(Bundle data) throws RemoteException {
14313 synchronized (ActivityManagerService.this) {
14314 if (mCurUserSwitchCallback == this) {
14315 mCount++;
14316 if (mCount == N) {
14317 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14318 }
14319 }
14320 }
14321 }
14322 };
14323 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014324 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014325 mCurUserSwitchCallback = callback;
14326 }
14327 for (int i=0; i<N; i++) {
14328 try {
14329 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14330 newUserId, callback);
14331 } catch (RemoteException e) {
14332 }
14333 }
14334 } else {
14335 synchronized (this) {
14336 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14337 }
14338 }
14339 mUserSwitchObservers.finishBroadcast();
14340 }
14341
14342 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14343 synchronized (this) {
14344 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14345 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14346 }
14347 }
14348
14349 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14350 mCurUserSwitchCallback = null;
14351 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14352 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14353 oldUserId, newUserId, uss));
14354 }
14355
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014356 void userInitialized(UserStartedState uss) {
14357 synchronized (ActivityManagerService.this) {
14358 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14359 uss.initializing = false;
14360 completeSwitchAndInitalizeLocked(uss);
14361 }
14362 }
14363
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014364 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14365 final int N = mUserSwitchObservers.beginBroadcast();
14366 for (int i=0; i<N; i++) {
14367 try {
14368 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14369 } catch (RemoteException e) {
14370 }
14371 }
14372 mUserSwitchObservers.finishBroadcast();
14373 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014374 uss.switching = false;
14375 completeSwitchAndInitalizeLocked(uss);
14376 }
14377 }
14378
14379 void completeSwitchAndInitalizeLocked(UserStartedState uss) {
14380 if (!uss.switching && !uss.initializing) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014381 mWindowManager.stopFreezingScreen();
14382 }
14383 }
14384
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014385 void finishUserSwitch(UserStartedState uss) {
14386 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014387 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014388 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14389 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014390 final int userId = uss.mHandle.getIdentifier();
14391 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14392 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14393 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014394 null, null, 0, null, null,
14395 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014396 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014397 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014398 int num = mUserLru.size();
14399 int i = 0;
14400 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14401 Integer oldUserId = mUserLru.get(i);
14402 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14403 if (oldUss == null) {
14404 // Shouldn't happen, but be sane if it does.
14405 mUserLru.remove(i);
14406 num--;
14407 continue;
14408 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014409 if (oldUss.mState == UserStartedState.STATE_STOPPING
14410 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014411 // This user is already stopping, doesn't count.
14412 num--;
14413 i++;
14414 continue;
14415 }
14416 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14417 // Owner and current can't be stopped, but count as running.
14418 i++;
14419 continue;
14420 }
14421 // This is a user to be stopped.
14422 stopUserLocked(oldUserId, null);
14423 num--;
14424 i++;
14425 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014426 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014427 }
14428
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014429 @Override
14430 public int stopUser(final int userId, final IStopUserCallback callback) {
14431 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14432 != PackageManager.PERMISSION_GRANTED) {
14433 String msg = "Permission Denial: switchUser() from pid="
14434 + Binder.getCallingPid()
14435 + ", uid=" + Binder.getCallingUid()
14436 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14437 Slog.w(TAG, msg);
14438 throw new SecurityException(msg);
14439 }
14440 if (userId <= 0) {
14441 throw new IllegalArgumentException("Can't stop primary user " + userId);
14442 }
Amith Yamasani13593602012-03-22 16:16:17 -070014443 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014444 return stopUserLocked(userId, callback);
14445 }
14446 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014447
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014448 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14449 if (mCurrentUserId == userId) {
14450 return ActivityManager.USER_OP_IS_CURRENT;
14451 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014452
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014453 final UserStartedState uss = mStartedUsers.get(userId);
14454 if (uss == null) {
14455 // User is not started, nothing to do... but we do need to
14456 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014457 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014458 mHandler.post(new Runnable() {
14459 @Override
14460 public void run() {
14461 try {
14462 callback.userStopped(userId);
14463 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014464 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014465 }
14466 });
14467 }
14468 return ActivityManager.USER_OP_SUCCESS;
14469 }
14470
14471 if (callback != null) {
14472 uss.mStopCallbacks.add(callback);
14473 }
14474
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014475 if (uss.mState != UserStartedState.STATE_STOPPING
14476 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014477 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014478 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014479
14480 long ident = Binder.clearCallingIdentity();
14481 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014482 // We are going to broadcast ACTION_USER_STOPPING and then
14483 // once that is down send a final ACTION_SHUTDOWN and then
14484 // stop the user.
14485 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14486 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14487 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14488 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14489 // This is the result receiver for the final shutdown broadcast.
14490 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014491 @Override
14492 public void performReceive(Intent intent, int resultCode, String data,
14493 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14494 finishUserStop(uss);
14495 }
14496 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014497 // This is the result receiver for the initial stopping broadcast.
14498 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14499 @Override
14500 public void performReceive(Intent intent, int resultCode, String data,
14501 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14502 // On to the next.
14503 synchronized (ActivityManagerService.this) {
14504 if (uss.mState != UserStartedState.STATE_STOPPING) {
14505 // Whoops, we are being started back up. Abort, abort!
14506 return;
14507 }
14508 uss.mState = UserStartedState.STATE_SHUTDOWN;
14509 }
14510 broadcastIntentLocked(null, null, shutdownIntent,
14511 null, shutdownReceiver, 0, null, null, null,
14512 true, false, MY_PID, Process.SYSTEM_UID, userId);
14513 }
14514 };
14515 // Kick things off.
14516 broadcastIntentLocked(null, null, stoppingIntent,
14517 null, stoppingReceiver, 0, null, null,
14518 android.Manifest.permission.INTERACT_ACROSS_USERS,
14519 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014520 } finally {
14521 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014522 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014523 }
Amith Yamasani13593602012-03-22 16:16:17 -070014524
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014525 return ActivityManager.USER_OP_SUCCESS;
14526 }
14527
14528 void finishUserStop(UserStartedState uss) {
14529 final int userId = uss.mHandle.getIdentifier();
14530 boolean stopped;
14531 ArrayList<IStopUserCallback> callbacks;
14532 synchronized (this) {
14533 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014534 if (mStartedUsers.get(userId) != uss) {
14535 stopped = false;
14536 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014537 stopped = false;
14538 } else {
14539 stopped = true;
14540 // User can no longer run.
14541 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014542 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014543 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014544
14545 // Clean up all state and processes associated with the user.
14546 // Kill all the processes for the user.
14547 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014548 }
14549 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014550
14551 for (int i=0; i<callbacks.size(); i++) {
14552 try {
14553 if (stopped) callbacks.get(i).userStopped(userId);
14554 else callbacks.get(i).userStopAborted(userId);
14555 } catch (RemoteException e) {
14556 }
14557 }
14558 }
14559
14560 @Override
14561 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014562 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14563 != PackageManager.PERMISSION_GRANTED) && (
14564 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14565 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014566 String msg = "Permission Denial: getCurrentUser() from pid="
14567 + Binder.getCallingPid()
14568 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014569 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014570 Slog.w(TAG, msg);
14571 throw new SecurityException(msg);
14572 }
14573 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014574 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014575 }
Amith Yamasani13593602012-03-22 16:16:17 -070014576 }
14577
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014578 int getCurrentUserIdLocked() {
14579 return mCurrentUserId;
14580 }
14581
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014582 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014583 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014584 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14585 != PackageManager.PERMISSION_GRANTED) {
14586 String msg = "Permission Denial: isUserRunning() from pid="
14587 + Binder.getCallingPid()
14588 + ", uid=" + Binder.getCallingUid()
14589 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14590 Slog.w(TAG, msg);
14591 throw new SecurityException(msg);
14592 }
14593 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014594 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014595 }
14596 }
14597
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014598 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014599 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014600 if (state == null) {
14601 return false;
14602 }
14603 if (orStopped) {
14604 return true;
14605 }
14606 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014607 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014608 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014609
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014610 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014611 public int[] getRunningUserIds() {
14612 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14613 != PackageManager.PERMISSION_GRANTED) {
14614 String msg = "Permission Denial: isUserRunning() from pid="
14615 + Binder.getCallingPid()
14616 + ", uid=" + Binder.getCallingUid()
14617 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14618 Slog.w(TAG, msg);
14619 throw new SecurityException(msg);
14620 }
14621 synchronized (this) {
14622 return mStartedUserArray;
14623 }
14624 }
14625
14626 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014627 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014628 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014629 UserStartedState uss = mStartedUsers.valueAt(i);
14630 // This list does not include stopping users.
14631 if (uss.mState != UserStartedState.STATE_STOPPING
14632 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14633 num++;
14634 }
14635 }
14636 mStartedUserArray = new int[num];
14637 num = 0;
14638 for (int i=0; i<mStartedUsers.size(); i++) {
14639 UserStartedState uss = mStartedUsers.valueAt(i);
14640 if (uss.mState != UserStartedState.STATE_STOPPING
14641 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14642 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14643 num++;
14644 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014645 }
14646 }
14647
14648 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014649 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14650 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14651 != PackageManager.PERMISSION_GRANTED) {
14652 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14653 + Binder.getCallingPid()
14654 + ", uid=" + Binder.getCallingUid()
14655 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14656 Slog.w(TAG, msg);
14657 throw new SecurityException(msg);
14658 }
14659
14660 mUserSwitchObservers.register(observer);
14661 }
14662
14663 @Override
14664 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14665 mUserSwitchObservers.unregister(observer);
14666 }
14667
Dianne Hackborn1676c852012-09-10 14:52:30 -070014668 private boolean userExists(int userId) {
14669 if (userId == 0) {
14670 return true;
14671 }
14672 UserManagerService ums = getUserManagerLocked();
14673 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14674 }
14675
14676 int[] getUsersLocked() {
14677 UserManagerService ums = getUserManagerLocked();
14678 return ums != null ? ums.getUserIds() : new int[] { 0 };
14679 }
14680
14681 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014682 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014683 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14684 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014685 }
14686 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014687 }
14688
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014689 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014690 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014691
14692 throw new SecurityException("Caller uid=" + uid
14693 + " is not privileged to communicate with user=" + userId);
14694 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014695
14696 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014697 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014698 }
14699
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014700 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014701 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014702 ApplicationInfo newInfo = new ApplicationInfo(info);
14703 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014704 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14705 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014706 return newInfo;
14707 }
14708
14709 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014710 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014711 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014712 return aInfo;
14713 }
14714
14715 ActivityInfo info = new ActivityInfo(aInfo);
14716 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14717 return info;
14718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014719}