blob: 6dbb7ce616760b032ffb70eb23e20ff93e91c6bc [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborn1676c852012-09-10 14:52:30 -070030import com.android.server.pm.UserManagerService;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080031import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032
Dianne Hackborndd71fc82009-12-16 19:24:32 -080033import dalvik.system.Zygote;
34
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.app.Activity;
36import android.app.ActivityManager;
37import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070038import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.ActivityThread;
40import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070041import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020042import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070044import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.IApplicationThread;
46import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070047import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070048import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070050import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.app.IThumbnailReceiver;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070052import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070054import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070055import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080057import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020058import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080059import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080060import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070061import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070063import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.ContentResolver;
65import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020066import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070067import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070068import android.content.IIntentReceiver;
69import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070070import android.content.Intent;
71import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070072import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.ActivityInfo;
74import android.content.pm.ApplicationInfo;
75import android.content.pm.ConfigurationInfo;
76import android.content.pm.IPackageDataObserver;
77import android.content.pm.IPackageManager;
78import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080079import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070081import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070082import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070083import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.pm.ProviderInfo;
85import android.content.pm.ResolveInfo;
86import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040087import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.content.res.Configuration;
89import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070090import android.net.Proxy;
91import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.net.Uri;
93import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080095import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070096import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080097import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080099import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.FileUtils;
101import android.os.Handler;
102import android.os.IBinder;
103import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700104import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700105import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.Looper;
107import android.os.Message;
108import android.os.Parcel;
109import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700111import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400113import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700115import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.os.SystemClock;
117import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700118import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700120import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800122import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700123import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700125import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700127import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import android.view.Gravity;
129import android.view.LayoutInflater;
130import android.view.View;
131import android.view.WindowManager;
132import android.view.WindowManagerPolicy;
133
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700134import java.io.BufferedInputStream;
135import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700136import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.DataInputStream;
138import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.File;
140import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700141import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700143import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200144import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800145import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700147import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.lang.ref.WeakReference;
149import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700150import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700151import java.util.Collections;
152import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.util.HashMap;
154import java.util.HashSet;
155import java.util.Iterator;
156import java.util.List;
157import java.util.Locale;
158import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700159import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700160import java.util.concurrent.atomic.AtomicBoolean;
161import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700163public final class ActivityManagerService extends ActivityManagerNative
164 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700165 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700167 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400169 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean DEBUG_SWITCH = localLOGV || false;
171 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700172 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final boolean DEBUG_PAUSE = localLOGV || false;
174 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
175 static final boolean DEBUG_TRANSITION = localLOGV || false;
176 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800177 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700178 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700180 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final boolean DEBUG_VISBILITY = localLOGV || false;
182 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700183 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700184 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700185 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800186 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700188 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700189 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700190 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700191 static final boolean DEBUG_POWER = localLOGV || false;
192 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700193 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 static final boolean VALIDATE_TOKENS = false;
195 static final boolean SHOW_ACTIVITY_START_TIME = true;
196
197 // Control over CPU and battery monitoring.
198 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
199 static final boolean MONITOR_CPU_USAGE = true;
200 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
201 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
202 static final boolean MONITOR_THREAD_CPU_USAGE = false;
203
Dianne Hackborn1655be42009-05-08 14:29:01 -0700204 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700205 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700206
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800207 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700209 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 // Maximum number of recent tasks that we can remember.
212 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700213
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700214 // Amount of time after a call to stopAppSwitches() during which we will
215 // prevent further untrusted switches from happening.
216 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
218 // How long we wait for a launched process to attach to the activity manager
219 // before we decide it's never going to come up for real.
220 static final int PROC_START_TIMEOUT = 10*1000;
221
Jeff Brown3f9dd282011-07-08 20:02:19 -0700222 // How long we wait for a launched process to attach to the activity manager
223 // before we decide it's never going to come up for real, when the process was
224 // started with a wrapper for instrumentation (such as Valgrind) because it
225 // could take much longer than usual.
226 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 // How long to wait after going idle before forcing apps to GC.
229 static final int GC_TIMEOUT = 5*1000;
230
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700231 // The minimum amount of time between successive GC requests for a process.
232 static final int GC_MIN_INTERVAL = 60*1000;
233
Dianne Hackborn287952c2010-09-22 22:34:31 -0700234 // The rate at which we check for apps using excessive power -- 15 mins.
235 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
236
237 // The minimum sample duration we will allow before deciding we have
238 // enough data on wake locks to start killing things.
239 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
240
241 // The minimum sample duration we will allow before deciding we have
242 // enough data on CPU usage to start killing things.
243 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800246 static final int BROADCAST_FG_TIMEOUT = 10*1000;
247 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // How long we wait until we timeout on key dispatching.
250 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // How long we wait until we timeout on key dispatching during instrumentation.
253 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
254
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700255 // Amount of time we wait for observers to handle a user switch before
256 // giving up on them and unfreezing the screen.
257 static final int USER_SWITCH_TIMEOUT = 2*1000;
258
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700259 // Maximum number of users we allow to be running at a time.
260 static final int MAX_RUNNING_USERS = 3;
261
Dan Egnor42471dd2010-01-07 17:25:22 -0800262 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263
264 static final String[] EMPTY_STRING_ARRAY = new String[0];
265
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700266 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700267
268 private final boolean mHeadless;
269
Joe Onorato54a4a412011-11-02 20:50:08 -0700270 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
271 // default actuion automatically. Important for devices without direct input
272 // devices.
273 private boolean mShowDialogs = true;
274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700276 * Description of a request to start a new activity, which has been held
277 * due to app switches being disabled.
278 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700279 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700280 ActivityRecord r;
281 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700282 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700283 }
284
285 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
286 = new ArrayList<PendingActivityLaunch>();
287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800289 BroadcastQueue mFgBroadcastQueue;
290 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800291 // Convenient for easy iteration over the queues. Foreground is first
292 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800293 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800294
295 BroadcastQueue broadcastQueueForIntent(Intent intent) {
296 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
297 if (DEBUG_BACKGROUND_BROADCAST) {
298 Slog.i(TAG, "Broadcast intent " + intent + " on "
299 + (isFg ? "foreground" : "background")
300 + " queue");
301 }
302 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
303 }
304
305 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
306 for (BroadcastQueue queue : mBroadcastQueues) {
307 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
308 if (r != null) {
309 return r;
310 }
311 }
312 return null;
313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314
315 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 * Activity we have told the window manager to have key focus.
317 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700318 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700319 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 * List of intents that were used to start the most recent tasks.
321 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700322 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323
324 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700325 * Process management.
326 */
327 final ProcessList mProcessList = new ProcessList();
328
329 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 * All of the applications we currently have running organized by name.
331 * The keys are strings of the application package name (as
332 * returned by the package manager), and the keys are ApplicationRecord
333 * objects.
334 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700335 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336
337 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800338 * The currently running isolated processes.
339 */
340 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
341
342 /**
343 * Counter for assigning isolated process uids, to avoid frequently reusing the
344 * same ones.
345 */
346 int mNextIsolatedProcessUid = 0;
347
348 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700349 * The currently running heavy-weight process, if any.
350 */
351 ProcessRecord mHeavyWeightProcess = null;
352
353 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 * The last time that various processes have crashed.
355 */
356 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
357
358 /**
359 * Set of applications that we consider to be bad, and will reject
360 * incoming broadcasts from (which the user has no control over).
361 * Processes are added to this set when they have crashed twice within
362 * a minimum amount of time; they are removed from it when they are
363 * later restarted (hopefully due to some user action). The value is the
364 * time it was added to the list.
365 */
366 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
367
368 /**
369 * All of the processes we currently have running organized by pid.
370 * The keys are the pid running the application.
371 *
372 * <p>NOTE: This object is protected by its own lock, NOT the global
373 * activity manager lock!
374 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700375 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376
377 /**
378 * All of the processes that have been forced to be foreground. The key
379 * is the pid of the caller who requested it (we hold a death
380 * link on it).
381 */
382 abstract class ForegroundToken implements IBinder.DeathRecipient {
383 int pid;
384 IBinder token;
385 }
386 final SparseArray<ForegroundToken> mForegroundProcesses
387 = new SparseArray<ForegroundToken>();
388
389 /**
390 * List of records for processes that someone had tried to start before the
391 * system was ready. We don't start them at that point, but ensure they
392 * are started by the time booting is complete.
393 */
394 final ArrayList<ProcessRecord> mProcessesOnHold
395 = new ArrayList<ProcessRecord>();
396
397 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 * List of persistent applications that are in the process
399 * of being started.
400 */
401 final ArrayList<ProcessRecord> mPersistentStartingProcesses
402 = new ArrayList<ProcessRecord>();
403
404 /**
405 * Processes that are being forcibly torn down.
406 */
407 final ArrayList<ProcessRecord> mRemovedProcesses
408 = new ArrayList<ProcessRecord>();
409
410 /**
411 * List of running applications, sorted by recent usage.
412 * The first entry in the list is the least recently used.
413 * It contains ApplicationRecord objects. This list does NOT include
414 * any persistent application records (since we never want to exit them).
415 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800416 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 = new ArrayList<ProcessRecord>();
418
419 /**
420 * List of processes that should gc as soon as things are idle.
421 */
422 final ArrayList<ProcessRecord> mProcessesToGc
423 = new ArrayList<ProcessRecord>();
424
425 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800426 * This is the process holding what we currently consider to be
427 * the "home" activity.
428 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700429 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800430
431 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700432 * This is the process holding the activity the user last visited that
433 * is in a different process from the one they are currently in.
434 */
435 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800436
437 /**
438 * The time at which the previous process was last visible.
439 */
440 long mPreviousProcessVisibleTime;
441
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700442 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700443 * Which uses have been started, so are allowed to run code.
444 */
445 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
446
447 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700448 * LRU list of history of current users. Most recently current is at the end.
449 */
450 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
451
452 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700453 * Constant array of the users that are currently started.
454 */
455 int[] mStartedUserArray = new int[] { 0 };
456
457 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700458 * Registered observers of the user switching mechanics.
459 */
460 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
461 = new RemoteCallbackList<IUserSwitchObserver>();
462
463 /**
464 * Currently active user switch.
465 */
466 Object mCurUserSwitchCallback;
467
468 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400469 * Packages that the user has asked to have run in screen size
470 * compatibility mode instead of filling the screen.
471 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700472 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400473
474 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 * Set of PendingResultRecord objects that are currently active.
476 */
477 final HashSet mPendingResultRecords = new HashSet();
478
479 /**
480 * Set of IntentSenderRecord objects that are currently active.
481 */
482 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
483 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
484
485 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800486 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700487 * already logged DropBox entries for. Guarded by itself. If
488 * something (rogue user app) forces this over
489 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
490 */
491 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
492 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
493
494 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700495 * Strict Mode background batched logging state.
496 *
497 * The string buffer is guarded by itself, and its lock is also
498 * used to determine if another batched write is already
499 * in-flight.
500 */
501 private final StringBuilder mStrictModeBuffer = new StringBuilder();
502
503 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 * Keeps track of all IIntentReceivers that have been registered for
505 * broadcasts. Hash keys are the receiver IBinder, hash value is
506 * a ReceiverList.
507 */
508 final HashMap mRegisteredReceivers = new HashMap();
509
510 /**
511 * Resolver for broadcast intents to registered receivers.
512 * Holds BroadcastFilter (subclass of IntentFilter).
513 */
514 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
515 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
516 @Override
517 protected boolean allowFilterResult(
518 BroadcastFilter filter, List<BroadcastFilter> dest) {
519 IBinder target = filter.receiverList.receiver.asBinder();
520 for (int i=dest.size()-1; i>=0; i--) {
521 if (dest.get(i).receiverList.receiver.asBinder() == target) {
522 return false;
523 }
524 }
525 return true;
526 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700527
528 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700529 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700530 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
531 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700532 return super.newResult(filter, match, userId);
533 }
534 return null;
535 }
536
537 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700538 protected BroadcastFilter[] newArray(int size) {
539 return new BroadcastFilter[size];
540 }
541
542 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700543 protected String packageForFilter(BroadcastFilter filter) {
544 return filter.packageName;
545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 };
547
548 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700549 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700551 * that action (which should usually be one). The SparseArray is keyed
552 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
553 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700555 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
556 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700558 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
560 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700561 * Backup/restore process management
562 */
563 String mBackupAppName = null;
564 BackupRecord mBackupTarget = null;
565
566 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 * List of PendingThumbnailsRecord objects of clients who are still
568 * waiting to receive all of the thumbnails for a task.
569 */
570 final ArrayList mPendingThumbnails = new ArrayList();
571
572 /**
573 * List of HistoryRecord objects that have been finished and must
574 * still report back to a pending thumbnail receiver.
575 */
576 final ArrayList mCancelledThumbnails = new ArrayList();
577
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700578 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 /**
581 * List of content providers who have clients waiting for them. The
582 * application is currently being launched and the provider will be
583 * removed from this list once it is published.
584 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700585 final ArrayList<ContentProviderRecord> mLaunchingProviders
586 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
588 /**
589 * Global set of specific Uri permissions that have been granted.
590 */
591 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
592 = new SparseArray<HashMap<Uri, UriPermission>>();
593
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800594 CoreSettingsObserver mCoreSettingsObserver;
595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 /**
597 * Thread-local storage used to carry caller permissions over through
598 * indirect content-provider access.
599 * @see #ActivityManagerService.openContentUri()
600 */
601 private class Identity {
602 public int pid;
603 public int uid;
604
605 Identity(int _pid, int _uid) {
606 pid = _pid;
607 uid = _uid;
608 }
609 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
612
613 /**
614 * All information we have collected about the runtime performance of
615 * any user id that can impact battery performance.
616 */
617 final BatteryStatsService mBatteryStatsService;
618
619 /**
620 * information about component usage
621 */
622 final UsageStatsService mUsageStatsService;
623
624 /**
625 * Current configuration information. HistoryRecord objects are given
626 * a reference to this object to indicate which configuration they are
627 * currently running in, so this object must be kept immutable.
628 */
629 Configuration mConfiguration = new Configuration();
630
631 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800632 * Current sequencing integer of the configuration, for skipping old
633 * configurations.
634 */
635 int mConfigurationSeq = 0;
636
637 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700638 * Hardware-reported OpenGLES version.
639 */
640 final int GL_ES_VERSION;
641
642 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 * List of initialization arguments to pass to all processes when binding applications to them.
644 * For example, references to the commonly used services.
645 */
646 HashMap<String, IBinder> mAppBindArgs;
647
648 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700649 * Temporary to avoid allocations. Protected by main lock.
650 */
651 final StringBuilder mStringBuilder = new StringBuilder(256);
652
653 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 * Used to control how we initialize the service.
655 */
656 boolean mStartRunning = false;
657 ComponentName mTopComponent;
658 String mTopAction;
659 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700660 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 boolean mSystemReady = false;
662 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700663 boolean mWaitingUpdate = false;
664 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700665 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700666 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667
668 Context mContext;
669
670 int mFactoryTest;
671
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700672 boolean mCheckedForSetup;
673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700675 * The time at which we will allow normal application switches again,
676 * after a call to {@link #stopAppSwitches()}.
677 */
678 long mAppSwitchesAllowedTime;
679
680 /**
681 * This is set to true after the first switch after mAppSwitchesAllowedTime
682 * is set; any switches after that will clear the time.
683 */
684 boolean mDidAppSwitch;
685
686 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700687 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700688 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700689 long mLastPowerCheckRealtime;
690
691 /**
692 * Last time (in uptime) at which we checked for power usage.
693 */
694 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700695
696 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 * Set while we are wanting to sleep, to prevent any
698 * activities from being started/resumed.
699 */
700 boolean mSleeping = false;
701
702 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700703 * State of external calls telling us if the device is asleep.
704 */
705 boolean mWentToSleep = false;
706
707 /**
708 * State of external call telling us if the lock screen is shown.
709 */
710 boolean mLockScreenShown = false;
711
712 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700713 * Set if we are shutting down the system, similar to sleeping.
714 */
715 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716
717 /**
718 * Task identifier that activities are currently being started
719 * in. Incremented each time a new task is created.
720 * todo: Replace this with a TokenSpace class that generates non-repeating
721 * integers that won't wrap.
722 */
723 int mCurTask = 1;
724
725 /**
726 * Current sequence id for oom_adj computation traversal.
727 */
728 int mAdjSeq = 0;
729
730 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700731 * Current sequence id for process LRU updating.
732 */
733 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734
735 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700736 * Keep track of the non-hidden/empty process we last found, to help
737 * determine how to distribute hidden/empty processes next time.
738 */
739 int mNumNonHiddenProcs = 0;
740
741 /**
742 * Keep track of the number of hidden procs, to balance oom adj
743 * distribution between those and empty procs.
744 */
745 int mNumHiddenProcs = 0;
746
747 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700748 * Keep track of the number of service processes we last found, to
749 * determine on the next iteration which should be B services.
750 */
751 int mNumServiceProcs = 0;
752 int mNewNumServiceProcs = 0;
753
754 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 * System monitoring: number of processes that died since the last
756 * N procs were started.
757 */
758 int[] mProcDeaths = new int[20];
759
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700760 /**
761 * This is set if we had to do a delayed dexopt of an app before launching
762 * it, to increasing the ANR timeouts in that case.
763 */
764 boolean mDidDexOpt;
765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 String mDebugApp = null;
767 boolean mWaitForDebugger = false;
768 boolean mDebugTransient = false;
769 String mOrigDebugApp = null;
770 boolean mOrigWaitForDebugger = false;
771 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700772 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700773 String mProfileApp = null;
774 ProcessRecord mProfileProc = null;
775 String mProfileFile;
776 ParcelFileDescriptor mProfileFd;
777 int mProfileType = 0;
778 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800779 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700781 static class ProcessChangeItem {
782 static final int CHANGE_ACTIVITIES = 1<<0;
783 static final int CHANGE_IMPORTANCE= 1<<1;
784 int changes;
785 int uid;
786 int pid;
787 int importance;
788 boolean foregroundActivities;
789 }
790
Jeff Sharkeya4620792011-05-20 15:29:23 -0700791 final RemoteCallbackList<IProcessObserver> mProcessObservers
792 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700793 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
794
795 final ArrayList<ProcessChangeItem> mPendingProcessChanges
796 = new ArrayList<ProcessChangeItem>();
797 final ArrayList<ProcessChangeItem> mAvailProcessChanges
798 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 /**
801 * Callback of last caller to {@link #requestPss}.
802 */
803 Runnable mRequestPssCallback;
804
805 /**
806 * Remaining processes for which we are waiting results from the last
807 * call to {@link #requestPss}.
808 */
809 final ArrayList<ProcessRecord> mRequestPssList
810 = new ArrayList<ProcessRecord>();
811
812 /**
813 * Runtime statistics collection thread. This object's lock is used to
814 * protect all related state.
815 */
816 final Thread mProcessStatsThread;
817
818 /**
819 * Used to collect process stats when showing not responding dialog.
820 * Protected by mProcessStatsThread.
821 */
822 final ProcessStats mProcessStats = new ProcessStats(
823 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700824 final AtomicLong mLastCpuTime = new AtomicLong(0);
825 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 long mLastWriteTime = 0;
828
829 /**
830 * Set to true after the system has finished booting.
831 */
832 boolean mBooted = false;
833
Dianne Hackborn7d608422011-08-07 16:24:18 -0700834 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700835 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836
837 WindowManagerService mWindowManager;
838
839 static ActivityManagerService mSelf;
840 static ActivityThread mSystemThread;
841
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700842 private int mCurrentUserId = 0;
843 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700844 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 private final class AppDeathRecipient implements IBinder.DeathRecipient {
847 final ProcessRecord mApp;
848 final int mPid;
849 final IApplicationThread mAppThread;
850
851 AppDeathRecipient(ProcessRecord app, int pid,
852 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800853 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 TAG, "New death recipient " + this
855 + " for thread " + thread.asBinder());
856 mApp = app;
857 mPid = pid;
858 mAppThread = thread;
859 }
860
861 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800862 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 TAG, "Death received in " + this
864 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 synchronized(ActivityManagerService.this) {
866 appDiedLocked(mApp, mPid, mAppThread);
867 }
868 }
869 }
870
871 static final int SHOW_ERROR_MSG = 1;
872 static final int SHOW_NOT_RESPONDING_MSG = 2;
873 static final int SHOW_FACTORY_ERROR_MSG = 3;
874 static final int UPDATE_CONFIGURATION_MSG = 4;
875 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
876 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 static final int SERVICE_TIMEOUT_MSG = 12;
878 static final int UPDATE_TIME_ZONE = 13;
879 static final int SHOW_UID_ERROR_MSG = 14;
880 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700882 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700883 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800884 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700885 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
886 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700887 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700888 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700889 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700890 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700891 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700892 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700893 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700894 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700895 static final int REPORT_USER_SWITCH_MSG = 34;
896 static final int CONTINUE_USER_SWITCH_MSG = 35;
897 static final int USER_SWITCH_TIMEOUT_MSG = 36;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800899 static final int FIRST_ACTIVITY_STACK_MSG = 100;
900 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
901 static final int FIRST_COMPAT_MODE_MSG = 300;
902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700904 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700905 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906
907 final Handler mHandler = new Handler() {
908 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800909 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 //}
911
912 public void handleMessage(Message msg) {
913 switch (msg.what) {
914 case SHOW_ERROR_MSG: {
915 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700916 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
917 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 synchronized (ActivityManagerService.this) {
919 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700920 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800922 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700923 if (res != null) {
924 res.set(0);
925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 return;
927 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700928 if (!showBackground && UserHandle.getAppId(proc.uid)
929 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
930 && proc.pid != MY_PID) {
931 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
932 if (res != null) {
933 res.set(0);
934 }
935 return;
936 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700937 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700938 Dialog d = new AppErrorDialog(mContext,
939 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 d.show();
941 proc.crashDialog = d;
942 } else {
943 // The device is asleep, so just pretend that the user
944 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700945 if (res != null) {
946 res.set(0);
947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700950
951 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 } break;
953 case SHOW_NOT_RESPONDING_MSG: {
954 synchronized (ActivityManagerService.this) {
955 HashMap data = (HashMap) msg.obj;
956 ProcessRecord proc = (ProcessRecord)data.get("app");
957 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800958 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 return;
960 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800961
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700962 Intent intent = new Intent("android.intent.action.ANR");
963 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800964 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
965 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700966 }
967 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800968 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700969 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800970
Justin Kohbc52ca22012-03-29 15:11:44 -0700971 if (mShowDialogs) {
972 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -0700973 mContext, proc, (ActivityRecord)data.get("activity"),
974 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -0700975 d.show();
976 proc.anrDialog = d;
977 } else {
978 // Just kill the app if there is no dialog to be shown.
979 killAppAtUsersRequest(proc, null);
980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700982
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700983 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700985 case SHOW_STRICT_MODE_VIOLATION_MSG: {
986 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
987 synchronized (ActivityManagerService.this) {
988 ProcessRecord proc = (ProcessRecord) data.get("app");
989 if (proc == null) {
990 Slog.e(TAG, "App not found when showing strict mode dialog.");
991 break;
992 }
993 if (proc.crashDialog != null) {
994 Slog.e(TAG, "App already has strict mode dialog: " + proc);
995 return;
996 }
997 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700998 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700999 Dialog d = new StrictModeViolationDialog(mContext,
1000 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001001 d.show();
1002 proc.crashDialog = d;
1003 } else {
1004 // The device is asleep, so just pretend that the user
1005 // saw a crash dialog and hit "force quit".
1006 res.set(0);
1007 }
1008 }
1009 ensureBootCompleted();
1010 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 case SHOW_FACTORY_ERROR_MSG: {
1012 Dialog d = new FactoryErrorDialog(
1013 mContext, msg.getData().getCharSequence("msg"));
1014 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001015 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 } break;
1017 case UPDATE_CONFIGURATION_MSG: {
1018 final ContentResolver resolver = mContext.getContentResolver();
1019 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1020 } break;
1021 case GC_BACKGROUND_PROCESSES_MSG: {
1022 synchronized (ActivityManagerService.this) {
1023 performAppGcsIfAppropriateLocked();
1024 }
1025 } break;
1026 case WAIT_FOR_DEBUGGER_MSG: {
1027 synchronized (ActivityManagerService.this) {
1028 ProcessRecord app = (ProcessRecord)msg.obj;
1029 if (msg.arg1 != 0) {
1030 if (!app.waitedForDebugger) {
1031 Dialog d = new AppWaitingForDebuggerDialog(
1032 ActivityManagerService.this,
1033 mContext, app);
1034 app.waitDialog = d;
1035 app.waitedForDebugger = true;
1036 d.show();
1037 }
1038 } else {
1039 if (app.waitDialog != null) {
1040 app.waitDialog.dismiss();
1041 app.waitDialog = null;
1042 }
1043 }
1044 }
1045 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001047 if (mDidDexOpt) {
1048 mDidDexOpt = false;
1049 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1050 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001051 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001052 return;
1053 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001054 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 } break;
1056 case UPDATE_TIME_ZONE: {
1057 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001058 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1059 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 if (r.thread != null) {
1061 try {
1062 r.thread.updateTimeZone();
1063 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001064 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
1066 }
1067 }
1068 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001069 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001070 case CLEAR_DNS_CACHE: {
1071 synchronized (ActivityManagerService.this) {
1072 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1073 ProcessRecord r = mLruProcesses.get(i);
1074 if (r.thread != null) {
1075 try {
1076 r.thread.clearDnsCache();
1077 } catch (RemoteException ex) {
1078 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1079 }
1080 }
1081 }
1082 }
1083 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001084 case UPDATE_HTTP_PROXY: {
1085 ProxyProperties proxy = (ProxyProperties)msg.obj;
1086 String host = "";
1087 String port = "";
1088 String exclList = "";
1089 if (proxy != null) {
1090 host = proxy.getHost();
1091 port = Integer.toString(proxy.getPort());
1092 exclList = proxy.getExclusionList();
1093 }
1094 synchronized (ActivityManagerService.this) {
1095 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1096 ProcessRecord r = mLruProcesses.get(i);
1097 if (r.thread != null) {
1098 try {
1099 r.thread.setHttpProxy(host, port, exclList);
1100 } catch (RemoteException ex) {
1101 Slog.w(TAG, "Failed to update http proxy for: " +
1102 r.info.processName);
1103 }
1104 }
1105 }
1106 }
1107 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001109 String title = "System UIDs Inconsistent";
1110 String text = "UIDs on the system are inconsistent, you need to wipe your"
1111 + " data partition or your device will be unstable.";
1112 Log.e(TAG, title + ": " + text);
1113 if (mShowDialogs) {
1114 // XXX This is a temporary dialog, no need to localize.
1115 AlertDialog d = new BaseErrorDialog(mContext);
1116 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1117 d.setCancelable(false);
1118 d.setTitle(title);
1119 d.setMessage(text);
1120 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1121 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1122 mUidAlert = d;
1123 d.show();
1124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 } break;
1126 case IM_FEELING_LUCKY_MSG: {
1127 if (mUidAlert != null) {
1128 mUidAlert.dismiss();
1129 mUidAlert = null;
1130 }
1131 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001133 if (mDidDexOpt) {
1134 mDidDexOpt = false;
1135 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1136 nmsg.obj = msg.obj;
1137 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1138 return;
1139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 ProcessRecord app = (ProcessRecord)msg.obj;
1141 synchronized (ActivityManagerService.this) {
1142 processStartTimedOutLocked(app);
1143 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001144 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001145 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1146 synchronized (ActivityManagerService.this) {
1147 doPendingActivityLaunchesLocked(true);
1148 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001149 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001150 case KILL_APPLICATION_MSG: {
1151 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001152 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001153 boolean restart = (msg.arg2 == 1);
1154 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001155 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1156 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001157 }
1158 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001159 case FINALIZE_PENDING_INTENT_MSG: {
1160 ((PendingIntentRecord)msg.obj).completeFinalize();
1161 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001162 case POST_HEAVY_NOTIFICATION_MSG: {
1163 INotificationManager inm = NotificationManager.getService();
1164 if (inm == null) {
1165 return;
1166 }
1167
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001168 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001169 ProcessRecord process = root.app;
1170 if (process == null) {
1171 return;
1172 }
1173
1174 try {
1175 Context context = mContext.createPackageContext(process.info.packageName, 0);
1176 String text = mContext.getString(R.string.heavy_weight_notification,
1177 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1178 Notification notification = new Notification();
1179 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1180 notification.when = 0;
1181 notification.flags = Notification.FLAG_ONGOING_EVENT;
1182 notification.tickerText = text;
1183 notification.defaults = 0; // please be quiet
1184 notification.sound = null;
1185 notification.vibrate = null;
1186 notification.setLatestEventInfo(context, text,
1187 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001188 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1189 PendingIntent.FLAG_CANCEL_CURRENT, null,
1190 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001191
1192 try {
1193 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001194 inm.enqueueNotificationWithTag("android", null,
1195 R.string.heavy_weight_notification,
1196 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001197 } catch (RuntimeException e) {
1198 Slog.w(ActivityManagerService.TAG,
1199 "Error showing notification for heavy-weight app", e);
1200 } catch (RemoteException e) {
1201 }
1202 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001203 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001204 }
1205 } break;
1206 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1207 INotificationManager inm = NotificationManager.getService();
1208 if (inm == null) {
1209 return;
1210 }
1211 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001212 inm.cancelNotificationWithTag("android", null,
1213 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001214 } catch (RuntimeException e) {
1215 Slog.w(ActivityManagerService.TAG,
1216 "Error canceling notification for service", e);
1217 } catch (RemoteException e) {
1218 }
1219 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001220 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1221 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001222 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001223 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001224 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1225 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001226 }
1227 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001228 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1229 synchronized (ActivityManagerService.this) {
1230 ActivityRecord ar = (ActivityRecord)msg.obj;
1231 if (mCompatModeDialog != null) {
1232 if (mCompatModeDialog.mAppInfo.packageName.equals(
1233 ar.info.applicationInfo.packageName)) {
1234 return;
1235 }
1236 mCompatModeDialog.dismiss();
1237 mCompatModeDialog = null;
1238 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001239 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001240 if (mCompatModePackages.getPackageAskCompatModeLocked(
1241 ar.packageName)) {
1242 int mode = mCompatModePackages.computeCompatModeLocked(
1243 ar.info.applicationInfo);
1244 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1245 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1246 mCompatModeDialog = new CompatModeDialog(
1247 ActivityManagerService.this, mContext,
1248 ar.info.applicationInfo);
1249 mCompatModeDialog.show();
1250 }
1251 }
1252 }
1253 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001254 break;
1255 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001256 case DISPATCH_PROCESSES_CHANGED: {
1257 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001258 break;
1259 }
1260 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001261 final int pid = msg.arg1;
1262 final int uid = msg.arg2;
1263 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001264 break;
1265 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001266 case REPORT_MEM_USAGE: {
1267 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1268 if (!isDebuggable) {
1269 return;
1270 }
1271 synchronized (ActivityManagerService.this) {
1272 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001273 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1274 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001275 // avoid spamming.
1276 return;
1277 }
1278 mLastMemUsageReportTime = now;
1279 }
1280 Thread thread = new Thread() {
1281 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001282 StringBuilder dropBuilder = new StringBuilder(1024);
1283 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001284 StringWriter oomSw = new StringWriter();
1285 PrintWriter oomPw = new PrintWriter(oomSw);
1286 StringWriter catSw = new StringWriter();
1287 PrintWriter catPw = new PrintWriter(catSw);
1288 String[] emptyArgs = new String[] { };
1289 StringBuilder tag = new StringBuilder(128);
1290 StringBuilder stack = new StringBuilder(128);
1291 tag.append("Low on memory -- ");
1292 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1293 tag, stack);
1294 dropBuilder.append(stack);
1295 dropBuilder.append('\n');
1296 dropBuilder.append('\n');
1297 String oomString = oomSw.toString();
1298 dropBuilder.append(oomString);
1299 dropBuilder.append('\n');
1300 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001301 try {
1302 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1303 "procrank", });
1304 final InputStreamReader converter = new InputStreamReader(
1305 proc.getInputStream());
1306 BufferedReader in = new BufferedReader(converter);
1307 String line;
1308 while (true) {
1309 line = in.readLine();
1310 if (line == null) {
1311 break;
1312 }
1313 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001314 logBuilder.append(line);
1315 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001316 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001317 dropBuilder.append(line);
1318 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001319 }
1320 converter.close();
1321 } catch (IOException e) {
1322 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001323 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001324 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001325 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001326 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001327 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1328 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001329 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001330 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001331 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001332 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001333 addErrorToDropBox("lowmem", null, "system_server", null,
1334 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001335 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001336 synchronized (ActivityManagerService.this) {
1337 long now = SystemClock.uptimeMillis();
1338 if (mLastMemUsageReportTime < now) {
1339 mLastMemUsageReportTime = now;
1340 }
1341 }
1342 }
1343 };
1344 thread.start();
1345 break;
1346 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001347 case REPORT_USER_SWITCH_MSG: {
1348 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1349 break;
1350 }
1351 case CONTINUE_USER_SWITCH_MSG: {
1352 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1353 break;
1354 }
1355 case USER_SWITCH_TIMEOUT_MSG: {
1356 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1357 break;
1358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
1360 }
1361 };
1362
1363 public static void setSystemProcess() {
1364 try {
1365 ActivityManagerService m = mSelf;
1366
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001367 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001369 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001370 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 if (MONITOR_CPU_USAGE) {
1372 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 ServiceManager.addService("permission", new PermissionController(m));
1375
1376 ApplicationInfo info =
1377 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001378 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001379 mSystemThread.installSystemApplicationInfo(info);
1380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 synchronized (mSelf) {
1382 ProcessRecord app = mSelf.newProcessRecordLocked(
1383 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001384 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001386 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001387 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001388 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 synchronized (mSelf.mPidsSelfLocked) {
1390 mSelf.mPidsSelfLocked.put(app.pid, app);
1391 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001392 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394 } catch (PackageManager.NameNotFoundException e) {
1395 throw new RuntimeException(
1396 "Unable to find android system package", e);
1397 }
1398 }
1399
1400 public void setWindowManager(WindowManagerService wm) {
1401 mWindowManager = wm;
1402 }
1403
1404 public static final Context main(int factoryTest) {
1405 AThread thr = new AThread();
1406 thr.start();
1407
1408 synchronized (thr) {
1409 while (thr.mService == null) {
1410 try {
1411 thr.wait();
1412 } catch (InterruptedException e) {
1413 }
1414 }
1415 }
1416
1417 ActivityManagerService m = thr.mService;
1418 mSelf = m;
1419 ActivityThread at = ActivityThread.systemMain();
1420 mSystemThread = at;
1421 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001422 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 m.mContext = context;
1424 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001425 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426
1427 m.mBatteryStatsService.publish(context);
1428 m.mUsageStatsService.publish(context);
1429
1430 synchronized (thr) {
1431 thr.mReady = true;
1432 thr.notifyAll();
1433 }
1434
1435 m.startRunning(null, null, null, null);
1436
1437 return context;
1438 }
1439
1440 public static ActivityManagerService self() {
1441 return mSelf;
1442 }
1443
1444 static class AThread extends Thread {
1445 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001446 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 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;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001464 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 notifyAll();
1466 }
1467
1468 synchronized (this) {
1469 while (!mReady) {
1470 try {
1471 wait();
1472 } catch (InterruptedException e) {
1473 }
1474 }
1475 }
1476
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001477 // For debug builds, log event loop stalls to dropbox for analysis.
1478 if (StrictMode.conditionallyEnableDebugLogging()) {
1479 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1480 }
1481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 Looper.loop();
1483 }
1484 }
1485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 static class MemBinder extends Binder {
1487 ActivityManagerService mActivityManagerService;
1488 MemBinder(ActivityManagerService activityManagerService) {
1489 mActivityManagerService = activityManagerService;
1490 }
1491
1492 @Override
1493 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001494 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1495 != PackageManager.PERMISSION_GRANTED) {
1496 pw.println("Permission Denial: can't dump meminfo from from pid="
1497 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1498 + " without permission " + android.Manifest.permission.DUMP);
1499 return;
1500 }
1501
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001502 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001503 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505 }
1506
Chet Haase9c1e23b2011-03-24 10:51:31 -07001507 static class GraphicsBinder extends Binder {
1508 ActivityManagerService mActivityManagerService;
1509 GraphicsBinder(ActivityManagerService activityManagerService) {
1510 mActivityManagerService = activityManagerService;
1511 }
1512
1513 @Override
1514 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001515 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1516 != PackageManager.PERMISSION_GRANTED) {
1517 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1518 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1519 + " without permission " + android.Manifest.permission.DUMP);
1520 return;
1521 }
1522
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001523 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001524 }
1525 }
1526
Jeff Brown6754ba22011-12-14 20:20:01 -08001527 static class DbBinder extends Binder {
1528 ActivityManagerService mActivityManagerService;
1529 DbBinder(ActivityManagerService activityManagerService) {
1530 mActivityManagerService = activityManagerService;
1531 }
1532
1533 @Override
1534 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1535 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1536 != PackageManager.PERMISSION_GRANTED) {
1537 pw.println("Permission Denial: can't dump dbinfo from from pid="
1538 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1539 + " without permission " + android.Manifest.permission.DUMP);
1540 return;
1541 }
1542
1543 mActivityManagerService.dumpDbInfo(fd, pw, args);
1544 }
1545 }
1546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 static class CpuBinder extends Binder {
1548 ActivityManagerService mActivityManagerService;
1549 CpuBinder(ActivityManagerService activityManagerService) {
1550 mActivityManagerService = activityManagerService;
1551 }
1552
1553 @Override
1554 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001555 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1556 != PackageManager.PERMISSION_GRANTED) {
1557 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1558 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1559 + " without permission " + android.Manifest.permission.DUMP);
1560 return;
1561 }
1562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001564 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1565 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1566 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
1568 }
1569 }
1570
1571 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001572 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001573
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001574 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1575 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1576 mBroadcastQueues[0] = mFgBroadcastQueue;
1577 mBroadcastQueues[1] = mBgBroadcastQueue;
1578
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001579 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001580 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 File dataDir = Environment.getDataDirectory();
1583 File systemDir = new File(dataDir, "system");
1584 systemDir.mkdirs();
1585 mBatteryStatsService = new BatteryStatsService(new File(
1586 systemDir, "batterystats.bin").toString());
1587 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001588 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001589 mOnBattery = DEBUG_POWER ? true
1590 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001591 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001593 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001594 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001595 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001597 // User 0 is the first and only user that runs at boot.
1598 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001599 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001600 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001601
Jack Palevichb90d28c2009-07-22 15:35:24 -07001602 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1603 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1604
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001605 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001606 mConfiguration.setLocale(Locale.getDefault());
1607
Dianne Hackborn813075a62011-11-14 17:45:19 -08001608 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 mProcessStats.init();
1610
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001611 mCompatModePackages = new CompatModePackages(this, systemDir);
1612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 // Add ourself to the Watchdog monitors.
1614 Watchdog.getInstance().addMonitor(this);
1615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 mProcessStatsThread = new Thread("ProcessStats") {
1617 public void run() {
1618 while (true) {
1619 try {
1620 try {
1621 synchronized(this) {
1622 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001623 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001625 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 // + ", write delay=" + nextWriteDelay);
1627 if (nextWriteDelay < nextCpuDelay) {
1628 nextCpuDelay = nextWriteDelay;
1629 }
1630 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001631 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 this.wait(nextCpuDelay);
1633 }
1634 }
1635 } catch (InterruptedException e) {
1636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 updateCpuStatsNow();
1638 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001639 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641 }
1642 }
1643 };
1644 mProcessStatsThread.start();
1645 }
1646
1647 @Override
1648 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1649 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001650 if (code == SYSPROPS_TRANSACTION) {
1651 // We need to tell all apps about the system property change.
1652 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1653 synchronized(this) {
1654 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1655 final int NA = apps.size();
1656 for (int ia=0; ia<NA; ia++) {
1657 ProcessRecord app = apps.valueAt(ia);
1658 if (app.thread != null) {
1659 procs.add(app.thread.asBinder());
1660 }
1661 }
1662 }
1663 }
1664
1665 int N = procs.size();
1666 for (int i=0; i<N; i++) {
1667 Parcel data2 = Parcel.obtain();
1668 try {
1669 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1670 } catch (RemoteException e) {
1671 }
1672 data2.recycle();
1673 }
1674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 try {
1676 return super.onTransact(code, data, reply, flags);
1677 } catch (RuntimeException e) {
1678 // The activity manager only throws security exceptions, so let's
1679 // log all others.
1680 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001681 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683 throw e;
1684 }
1685 }
1686
1687 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001688 final long now = SystemClock.uptimeMillis();
1689 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1690 return;
1691 }
1692 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1693 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 mProcessStatsThread.notify();
1695 }
1696 }
1697 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 void updateCpuStatsNow() {
1700 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001701 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 final long now = SystemClock.uptimeMillis();
1703 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001706 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1707 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 haveNewCpuStats = true;
1709 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001710 //Slog.i(TAG, mProcessStats.printCurrentState());
1711 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 // + mProcessStats.getTotalCpuPercent() + "%");
1713
Joe Onorato8a9b2202010-02-26 18:56:32 -08001714 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 if ("true".equals(SystemProperties.get("events.cpu"))) {
1716 int user = mProcessStats.getLastUserTime();
1717 int system = mProcessStats.getLastSystemTime();
1718 int iowait = mProcessStats.getLastIoWaitTime();
1719 int irq = mProcessStats.getLastIrqTime();
1720 int softIrq = mProcessStats.getLastSoftIrqTime();
1721 int idle = mProcessStats.getLastIdleTime();
1722
1723 int total = user + system + iowait + irq + softIrq + idle;
1724 if (total == 0) total = 1;
1725
Doug Zongker2bec3d42009-12-04 12:52:44 -08001726 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 ((user+system+iowait+irq+softIrq) * 100) / total,
1728 (user * 100) / total,
1729 (system * 100) / total,
1730 (iowait * 100) / total,
1731 (irq * 100) / total,
1732 (softIrq * 100) / total);
1733 }
1734 }
1735
Amith Yamasanie43530a2009-08-21 13:11:37 -07001736 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001737 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001738 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 synchronized(mPidsSelfLocked) {
1740 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001741 if (mOnBattery) {
1742 int perc = bstats.startAddingCpuLocked();
1743 int totalUTime = 0;
1744 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001745 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001747 ProcessStats.Stats st = mProcessStats.getStats(i);
1748 if (!st.working) {
1749 continue;
1750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001752 int otherUTime = (st.rel_utime*perc)/100;
1753 int otherSTime = (st.rel_stime*perc)/100;
1754 totalUTime += otherUTime;
1755 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 if (pr != null) {
1757 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001758 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1759 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001760 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001761 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001762 } else {
1763 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001764 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001765 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001766 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1767 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001768 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
1771 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001772 bstats.finishAddingCpuLocked(perc, totalUTime,
1773 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
1775 }
1776 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1779 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001780 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
1782 }
1783 }
1784 }
1785
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001786 @Override
1787 public void batteryNeedsCpuUpdate() {
1788 updateCpuStatsNow();
1789 }
1790
1791 @Override
1792 public void batteryPowerChanged(boolean onBattery) {
1793 // When plugging in, update the CPU stats first before changing
1794 // the plug state.
1795 updateCpuStatsNow();
1796 synchronized (this) {
1797 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001798 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001799 }
1800 }
1801 }
1802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 /**
1804 * Initialize the application bind args. These are passed to each
1805 * process when the bindApplication() IPC is sent to the process. They're
1806 * lazily setup to make sure the services are running when they're asked for.
1807 */
1808 private HashMap<String, IBinder> getCommonServicesLocked() {
1809 if (mAppBindArgs == null) {
1810 mAppBindArgs = new HashMap<String, IBinder>();
1811
1812 // Setup the application init args
1813 mAppBindArgs.put("package", ServiceManager.getService("package"));
1814 mAppBindArgs.put("window", ServiceManager.getService("window"));
1815 mAppBindArgs.put(Context.ALARM_SERVICE,
1816 ServiceManager.getService(Context.ALARM_SERVICE));
1817 }
1818 return mAppBindArgs;
1819 }
1820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (mFocusedActivity != r) {
1823 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001824 if (r != null) {
1825 mWindowManager.setFocusedApp(r.appToken, true);
1826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
1828 }
1829
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001830 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001832 int lrui = mLruProcesses.indexOf(app);
1833 if (lrui >= 0) mLruProcesses.remove(lrui);
1834
1835 int i = mLruProcesses.size()-1;
1836 int skipTop = 0;
1837
Dianne Hackborn906497c2010-05-10 15:57:38 -07001838 app.lruSeq = mLruSeq;
1839
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001840 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001841 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001842 if (app.activities.size() > 0) {
1843 // If this process has activities, we more strongly want to keep
1844 // it around.
1845 app.lruWeight = app.lastActivityTime;
1846 } else if (app.pubProviders.size() > 0) {
1847 // If this process contains content providers, we want to keep
1848 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001849 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001850 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001851 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001852 } else {
1853 // If this process doesn't have activities, we less strongly
1854 // want to keep it around, and generally want to avoid getting
1855 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001856 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001857 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001858 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001859 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001860
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001861 while (i >= 0) {
1862 ProcessRecord p = mLruProcesses.get(i);
1863 // If this app shouldn't be in front of the first N background
1864 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001865 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001866 skipTop--;
1867 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001868 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001869 mLruProcesses.add(i+1, app);
1870 break;
1871 }
1872 i--;
1873 }
1874 if (i < 0) {
1875 mLruProcesses.add(0, app);
1876 }
1877
Dianne Hackborn906497c2010-05-10 15:57:38 -07001878 // If the app is currently using a content provider or service,
1879 // bump those processes as well.
1880 if (app.connections.size() > 0) {
1881 for (ConnectionRecord cr : app.connections) {
1882 if (cr.binding != null && cr.binding.service != null
1883 && cr.binding.service.app != null
1884 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001885 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001886 }
1887 }
1888 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001889 for (int j=app.conProviders.size()-1; j>=0; j--) {
1890 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1891 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001892 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001893 }
1894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
1896
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001897 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001898 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001899 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001900 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001901
1902 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1903 if (oomAdj) {
1904 updateOomAdjLocked();
1905 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001906 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001907
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001908 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001910 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001911 // The system gets to run in any process. If there are multiple
1912 // processes with the same uid, just pick the first (this
1913 // should never happen).
1914 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1915 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001916 if (procs == null) return null;
1917 final int N = procs.size();
1918 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001919 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 }
1922 ProcessRecord proc = mProcessNames.get(processName, uid);
1923 return proc;
1924 }
1925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001926 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001927 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001928 try {
1929 if (pm.performDexOpt(packageName)) {
1930 mDidDexOpt = true;
1931 }
1932 } catch (RemoteException e) {
1933 }
1934 }
1935
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001936 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 int transit = mWindowManager.getPendingAppTransition();
1938 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1939 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1940 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1941 }
1942
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001943 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001945 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1946 boolean isolated) {
1947 ProcessRecord app;
1948 if (!isolated) {
1949 app = getProcessRecordLocked(processName, info.uid);
1950 } else {
1951 // If this is an isolated process, it can't re-use an existing process.
1952 app = null;
1953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 // We don't have to do anything more if:
1955 // (1) There is an existing application record; and
1956 // (2) The caller doesn't think it is dead, OR there is no thread
1957 // object attached to it so we know it couldn't have crashed; and
1958 // (3) There is a pid assigned to it, so it is either starting or
1959 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001960 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 + " app=" + app + " knownToBeDead=" + knownToBeDead
1962 + " thread=" + (app != null ? app.thread : null)
1963 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001964 if (app != null && app.pid > 0) {
1965 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001966 // We already have the app running, or are waiting for it to
1967 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001968 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001969 // If this is a new package in the process, add the package to the list
1970 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001971 return app;
1972 } else {
1973 // An application record is attached to a previous process,
1974 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001975 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001976 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 String hostingNameStr = hostingName != null
1981 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001982
1983 if (!isolated) {
1984 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1985 // If we are in the background, then check to see if this process
1986 // is bad. If so, we will just silently fail.
1987 if (mBadProcesses.get(info.processName, info.uid) != null) {
1988 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1989 + "/" + info.processName);
1990 return null;
1991 }
1992 } else {
1993 // When the user is explicitly starting a process, then clear its
1994 // crash count so that we won't make it bad until they see at
1995 // least one crash dialog again, and make the process good again
1996 // if it had been bad.
1997 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001998 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001999 mProcessCrashTimes.remove(info.processName, info.uid);
2000 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002001 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2002 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002003 info.processName);
2004 mBadProcesses.remove(info.processName, info.uid);
2005 if (app != null) {
2006 app.bad = false;
2007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009 }
2010 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002013 app = newProcessRecordLocked(null, info, processName, isolated);
2014 if (app == null) {
2015 Slog.w(TAG, "Failed making new process record for "
2016 + processName + "/" + info.uid + " isolated=" + isolated);
2017 return null;
2018 }
2019 mProcessNames.put(processName, app.uid, app);
2020 if (isolated) {
2021 mIsolatedProcesses.put(app.uid, app);
2022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 } else {
2024 // If this is a new package in the process, add the package to the list
2025 app.addPackage(info.packageName);
2026 }
2027
2028 // If the system is not ready yet, then hold off on starting this
2029 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002030 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002031 && !isAllowedWhileBooting(info)
2032 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 if (!mProcessesOnHold.contains(app)) {
2034 mProcessesOnHold.add(app);
2035 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002036 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 return app;
2038 }
2039
2040 startProcessLocked(app, hostingType, hostingNameStr);
2041 return (app.pid != 0) ? app : null;
2042 }
2043
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002044 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2045 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2046 }
2047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 private final void startProcessLocked(ProcessRecord app,
2049 String hostingType, String hostingNameStr) {
2050 if (app.pid > 0 && app.pid != MY_PID) {
2051 synchronized (mPidsSelfLocked) {
2052 mPidsSelfLocked.remove(app.pid);
2053 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2054 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002055 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002058 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2059 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 mProcessesOnHold.remove(app);
2061
2062 updateCpuStats();
2063
2064 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2065 mProcDeaths[0] = 0;
2066
2067 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002068 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002071 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002072 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002073 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002074 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002075 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002076 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002077
2078 if (Environment.isExternalStorageEmulated()) {
2079 if (pm.checkPermission(
2080 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2081 app.info.packageName) == PERMISSION_GRANTED) {
2082 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2083 } else {
2084 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2085 }
2086 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002087 } catch (PackageManager.NameNotFoundException e) {
2088 Slog.w(TAG, "Unable to retrieve gids", e);
2089 }
Kenny Roote091f222012-09-11 15:01:26 -07002090
2091 /*
2092 * Add shared application GID so applications can share some
2093 * resources like shared libraries
2094 */
2095 if (permGids == null) {
2096 gids = new int[1];
2097 } else {
2098 gids = new int[permGids.length + 1];
2099 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2100 }
2101 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
2103 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2104 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2105 && mTopComponent != null
2106 && app.processName.equals(mTopComponent.getPackageName())) {
2107 uid = 0;
2108 }
2109 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2110 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2111 uid = 0;
2112 }
2113 }
2114 int debugFlags = 0;
2115 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2116 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002117 // Also turn on CheckJNI for debuggable apps. It's quite
2118 // awkward to turn on otherwise.
2119 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002121 // Run the app in safe mode if its manifest requests so or the
2122 // system is booted in safe mode.
2123 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2124 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002125 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2128 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2129 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002130 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2131 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 if ("1".equals(SystemProperties.get("debug.assert"))) {
2134 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2135 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002136
2137 // Start the process. It will either succeed and return a result containing
2138 // the PID of the new process, or else throw a RuntimeException.
2139 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002140 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002141 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2144 synchronized (bs) {
2145 if (bs.isOnBattery()) {
2146 app.batteryStats.incStartsLocked();
2147 }
2148 }
2149
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002150 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2151 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 app.processName, hostingType,
2153 hostingNameStr != null ? hostingNameStr : "");
2154
2155 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002156 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
2158
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002159 StringBuilder buf = mStringBuilder;
2160 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 buf.append("Start proc ");
2162 buf.append(app.processName);
2163 buf.append(" for ");
2164 buf.append(hostingType);
2165 if (hostingNameStr != null) {
2166 buf.append(" ");
2167 buf.append(hostingNameStr);
2168 }
2169 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002170 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 buf.append(" uid=");
2172 buf.append(uid);
2173 buf.append(" gids={");
2174 if (gids != null) {
2175 for (int gi=0; gi<gids.length; gi++) {
2176 if (gi != 0) buf.append(", ");
2177 buf.append(gids[gi]);
2178
2179 }
2180 }
2181 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002182 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002183 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002184 app.usingWrapper = startResult.usingWrapper;
2185 app.removed = false;
2186 synchronized (mPidsSelfLocked) {
2187 this.mPidsSelfLocked.put(startResult.pid, app);
2188 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2189 msg.obj = app;
2190 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2191 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 }
2193 } catch (RuntimeException e) {
2194 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002195 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002196 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 }
2198 }
2199
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002200 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 if (resumed) {
2202 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2203 } else {
2204 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2205 }
2206 }
2207
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002208 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002209 if (mHeadless) {
2210 // Added because none of the other calls to ensureBootCompleted seem to fire
2211 // when running headless.
2212 ensureBootCompleted();
2213 return false;
2214 }
2215
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002216 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2217 && mTopAction == null) {
2218 // We are running in factory test mode, but unable to find
2219 // the factory test app, so just sit around displaying the
2220 // error message and don't try to start anything.
2221 return false;
2222 }
2223 Intent intent = new Intent(
2224 mTopAction,
2225 mTopData != null ? Uri.parse(mTopData) : null);
2226 intent.setComponent(mTopComponent);
2227 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2228 intent.addCategory(Intent.CATEGORY_HOME);
2229 }
2230 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002231 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002232 if (aInfo != null) {
2233 intent.setComponent(new ComponentName(
2234 aInfo.applicationInfo.packageName, aInfo.name));
2235 // Don't do this if the home app is currently being
2236 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002237 aInfo = new ActivityInfo(aInfo);
2238 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002239 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2240 aInfo.applicationInfo.uid);
2241 if (app == null || app.instrumentationClass == null) {
2242 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002243 mMainStack.startActivityLocked(null, intent, null, aInfo,
2244 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002245 }
2246 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002247
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002248 return true;
2249 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002250
Amith Yamasani259d5e52012-08-31 15:11:01 -07002251 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2252 ActivityInfo ai = null;
2253 ComponentName comp = intent.getComponent();
2254 try {
2255 if (comp != null) {
2256 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2257 } else {
2258 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2259 intent,
2260 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2261 flags, userId);
2262
2263 if (info != null) {
2264 ai = info.activityInfo;
2265 }
2266 }
2267 } catch (RemoteException e) {
2268 // ignore
2269 }
2270
2271 return ai;
2272 }
2273
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002274 /**
2275 * Starts the "new version setup screen" if appropriate.
2276 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002277 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002278 // Only do this once per boot.
2279 if (mCheckedForSetup) {
2280 return;
2281 }
2282
2283 // We will show this screen if the current one is a different
2284 // version than the last one shown, and we are not running in
2285 // low-level factory test mode.
2286 final ContentResolver resolver = mContext.getContentResolver();
2287 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002288 Settings.Global.getInt(resolver,
2289 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002290 mCheckedForSetup = true;
2291
2292 // See if we should be showing the platform update setup UI.
2293 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2294 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2295 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2296
2297 // We don't allow third party apps to replace this.
2298 ResolveInfo ri = null;
2299 for (int i=0; ris != null && i<ris.size(); i++) {
2300 if ((ris.get(i).activityInfo.applicationInfo.flags
2301 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2302 ri = ris.get(i);
2303 break;
2304 }
2305 }
2306
2307 if (ri != null) {
2308 String vers = ri.activityInfo.metaData != null
2309 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2310 : null;
2311 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2312 vers = ri.activityInfo.applicationInfo.metaData.getString(
2313 Intent.METADATA_SETUP_VERSION);
2314 }
2315 String lastVers = Settings.Secure.getString(
2316 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2317 if (vers != null && !vers.equals(lastVers)) {
2318 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2319 intent.setComponent(new ComponentName(
2320 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002321 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2322 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002323 }
2324 }
2325 }
2326 }
2327
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002328 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002329 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002330 }
2331
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002332 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002333 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002334 throw new SecurityException("Isolated process not allowed to call " + caller);
2335 }
2336 }
2337
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002338 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002339 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002340 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002341 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2342 }
2343 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002344
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002345 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002346 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2347 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002348 synchronized (this) {
2349 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2350 }
2351 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002352
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002353 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002354 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002355 synchronized (this) {
2356 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2357 }
2358 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002359
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002360 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002361 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2362 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002363 synchronized (this) {
2364 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002365 }
2366 }
2367
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002368 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002369 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002370 synchronized (this) {
2371 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2372 }
2373 }
2374
2375 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002376 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2377 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002378 synchronized (this) {
2379 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2380 }
2381 }
2382
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002383 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002384 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002385 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002388 private void dispatchProcessesChanged() {
2389 int N;
2390 synchronized (this) {
2391 N = mPendingProcessChanges.size();
2392 if (mActiveProcessChanges.length < N) {
2393 mActiveProcessChanges = new ProcessChangeItem[N];
2394 }
2395 mPendingProcessChanges.toArray(mActiveProcessChanges);
2396 mAvailProcessChanges.addAll(mPendingProcessChanges);
2397 mPendingProcessChanges.clear();
2398 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2399 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002400 int i = mProcessObservers.beginBroadcast();
2401 while (i > 0) {
2402 i--;
2403 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2404 if (observer != null) {
2405 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002406 for (int j=0; j<N; j++) {
2407 ProcessChangeItem item = mActiveProcessChanges[j];
2408 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2409 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2410 + item.pid + " uid=" + item.uid + ": "
2411 + item.foregroundActivities);
2412 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2413 item.foregroundActivities);
2414 }
2415 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2416 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2417 + item.pid + " uid=" + item.uid + ": " + item.importance);
2418 observer.onImportanceChanged(item.pid, item.uid,
2419 item.importance);
2420 }
2421 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002422 } catch (RemoteException e) {
2423 }
2424 }
2425 }
2426 mProcessObservers.finishBroadcast();
2427 }
2428
2429 private void dispatchProcessDied(int pid, int uid) {
2430 int i = mProcessObservers.beginBroadcast();
2431 while (i > 0) {
2432 i--;
2433 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2434 if (observer != null) {
2435 try {
2436 observer.onProcessDied(pid, uid);
2437 } catch (RemoteException e) {
2438 }
2439 }
2440 }
2441 mProcessObservers.finishBroadcast();
2442 }
2443
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002444 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002445 final int N = mPendingActivityLaunches.size();
2446 if (N <= 0) {
2447 return;
2448 }
2449 for (int i=0; i<N; i++) {
2450 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002451 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002452 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002453 }
2454 mPendingActivityLaunches.clear();
2455 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002456
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002457 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002458 Intent intent, String resolvedType, IBinder resultTo,
2459 String resultWho, int requestCode, int startFlags,
2460 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002461 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002462 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002463 }
2464
2465 public final int startActivityAsUser(IApplicationThread caller,
2466 Intent intent, String resolvedType, IBinder resultTo,
2467 String resultWho, int requestCode, int startFlags,
2468 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002469 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002470 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002471 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002472 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002473 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2474 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002475 }
2476
2477 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002478 Intent intent, String resolvedType, IBinder resultTo,
2479 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002480 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002481 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002482 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002483 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002484 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002485 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002486 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002487 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002488 return res;
2489 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002490
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002491 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002492 Intent intent, String resolvedType, IBinder resultTo,
2493 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002494 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002495 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002496 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002497 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002498 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002499 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002500 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002502 }
2503
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002504 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002505 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002506 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002507 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002508 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002509 // Refuse possible leaked file descriptors
2510 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2511 throw new IllegalArgumentException("File descriptors passed in Intent");
2512 }
2513
2514 IIntentSender sender = intent.getTarget();
2515 if (!(sender instanceof PendingIntentRecord)) {
2516 throw new IllegalArgumentException("Bad PendingIntent object");
2517 }
2518
2519 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002520
2521 synchronized (this) {
2522 // If this is coming from the currently resumed activity, it is
2523 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002524 if (mMainStack.mResumedActivity != null
2525 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002526 Binder.getCallingUid()) {
2527 mAppSwitchesAllowedTime = 0;
2528 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002529 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002530 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2531 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002532 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002533 }
2534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002536 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 // Refuse possible leaked file descriptors
2538 if (intent != null && intent.hasFileDescriptors() == true) {
2539 throw new IllegalArgumentException("File descriptors passed in Intent");
2540 }
2541
2542 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002543 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2544 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002545 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 return false;
2547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 if (r.app == null || r.app.thread == null) {
2549 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002550 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 return false;
2552 }
2553 intent = new Intent(intent);
2554 // The caller is not allowed to change the data.
2555 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2556 // And we are resetting to find the next component...
2557 intent.setComponent(null);
2558
2559 ActivityInfo aInfo = null;
2560 try {
2561 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002562 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002564 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002565 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566
2567 // Look for the original activity in the list...
2568 final int N = resolves != null ? resolves.size() : 0;
2569 for (int i=0; i<N; i++) {
2570 ResolveInfo rInfo = resolves.get(i);
2571 if (rInfo.activityInfo.packageName.equals(r.packageName)
2572 && rInfo.activityInfo.name.equals(r.info.name)) {
2573 // We found the current one... the next matching is
2574 // after it.
2575 i++;
2576 if (i<N) {
2577 aInfo = resolves.get(i).activityInfo;
2578 }
2579 break;
2580 }
2581 }
2582 } catch (RemoteException e) {
2583 }
2584
2585 if (aInfo == null) {
2586 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002587 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 return false;
2589 }
2590
2591 intent.setComponent(new ComponentName(
2592 aInfo.applicationInfo.packageName, aInfo.name));
2593 intent.setFlags(intent.getFlags()&~(
2594 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2595 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2596 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2597 Intent.FLAG_ACTIVITY_NEW_TASK));
2598
2599 // Okay now we need to start the new activity, replacing the
2600 // currently running activity. This is a little tricky because
2601 // we want to start the new one as if the current one is finished,
2602 // but not finish the current one first so that there is no flicker.
2603 // And thus...
2604 final boolean wasFinishing = r.finishing;
2605 r.finishing = true;
2606
2607 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002608 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 final String resultWho = r.resultWho;
2610 final int requestCode = r.requestCode;
2611 r.resultTo = null;
2612 if (resultTo != null) {
2613 resultTo.removeResultsLocked(r, resultWho, requestCode);
2614 }
2615
2616 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002618 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2619 resultWho, requestCode, -1, r.launchedFromUid, 0,
2620 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 Binder.restoreCallingIdentity(origId);
2622
2623 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002624 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 return false;
2626 }
2627 return true;
2628 }
2629 }
2630
Dianne Hackborn41203752012-08-31 14:05:51 -07002631 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002633 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2634
Dianne Hackborn139748f2012-09-24 11:36:57 -07002635 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002636 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637
Amith Yamasani742a6712011-05-04 14:49:28 -07002638 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002639 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002640 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002641 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002642 }
2643
2644 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002645 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2646 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002647 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002648 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002649 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002650 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002651 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002652 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002653 }
2654
Dianne Hackborn41203752012-08-31 14:05:51 -07002655 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002656 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002657 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002658
Dianne Hackborn139748f2012-09-24 11:36:57 -07002659 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002660 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002661 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002662 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002663 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
2665
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002666 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002668 // Quick case: check if the top-most recent task is the same.
2669 if (N > 0 && mRecentTasks.get(0) == task) {
2670 return;
2671 }
2672 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 for (int i=0; i<N; i++) {
2674 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002675 if (task.userId == tr.userId
2676 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2677 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 mRecentTasks.remove(i);
2679 i--;
2680 N--;
2681 if (task.intent == null) {
2682 // If the new recent task we are adding is not fully
2683 // specified, then replace it with the existing recent task.
2684 task = tr;
2685 }
2686 }
2687 }
2688 if (N >= MAX_RECENT_TASKS) {
2689 mRecentTasks.remove(N-1);
2690 }
2691 mRecentTasks.add(0, task);
2692 }
2693
2694 public void setRequestedOrientation(IBinder token,
2695 int requestedOrientation) {
2696 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002697 ActivityRecord r = mMainStack.isInStackLocked(token);
2698 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 return;
2700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002702 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002704 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002705 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 if (config != null) {
2707 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002708 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002709 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 }
2711 }
2712 Binder.restoreCallingIdentity(origId);
2713 }
2714 }
2715
2716 public int getRequestedOrientation(IBinder token) {
2717 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002718 ActivityRecord r = mMainStack.isInStackLocked(token);
2719 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2721 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002722 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
2724 }
2725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 /**
2727 * This is the internal entry point for handling Activity.finish().
2728 *
2729 * @param token The Binder token referencing the Activity we want to finish.
2730 * @param resultCode Result code, if any, from this Activity.
2731 * @param resultData Result data (Intent), if any, from this Activity.
2732 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002733 * @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 -08002734 */
2735 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2736 // Refuse possible leaked file descriptors
2737 if (resultData != null && resultData.hasFileDescriptors() == true) {
2738 throw new IllegalArgumentException("File descriptors passed in Intent");
2739 }
2740
2741 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002742 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002744 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 if (next != null) {
2746 // ask watcher if this is allowed
2747 boolean resumeOK = true;
2748 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002749 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002751 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 }
2753
2754 if (!resumeOK) {
2755 return false;
2756 }
2757 }
2758 }
2759 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002761 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 Binder.restoreCallingIdentity(origId);
2763 return res;
2764 }
2765 }
2766
Dianne Hackborn860755f2010-06-03 18:47:52 -07002767 public final void finishHeavyWeightApp() {
2768 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2769 != PackageManager.PERMISSION_GRANTED) {
2770 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2771 + Binder.getCallingPid()
2772 + ", uid=" + Binder.getCallingUid()
2773 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2774 Slog.w(TAG, msg);
2775 throw new SecurityException(msg);
2776 }
2777
2778 synchronized(this) {
2779 if (mHeavyWeightProcess == null) {
2780 return;
2781 }
2782
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002783 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002784 mHeavyWeightProcess.activities);
2785 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002786 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002787 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002788 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002789 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002790 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002791 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002792 }
2793 }
2794 }
2795
Dianne Hackborn41203752012-08-31 14:05:51 -07002796 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2797 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002798 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002799 }
2800 }
2801
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002802 public void crashApplication(int uid, int initialPid, String packageName,
2803 String message) {
2804 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2805 != PackageManager.PERMISSION_GRANTED) {
2806 String msg = "Permission Denial: crashApplication() from pid="
2807 + Binder.getCallingPid()
2808 + ", uid=" + Binder.getCallingUid()
2809 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2810 Slog.w(TAG, msg);
2811 throw new SecurityException(msg);
2812 }
2813
2814 synchronized(this) {
2815 ProcessRecord proc = null;
2816
2817 // Figure out which process to kill. We don't trust that initialPid
2818 // still has any relation to current pids, so must scan through the
2819 // list.
2820 synchronized (mPidsSelfLocked) {
2821 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2822 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002823 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002824 continue;
2825 }
2826 if (p.pid == initialPid) {
2827 proc = p;
2828 break;
2829 }
2830 for (String str : p.pkgList) {
2831 if (str.equals(packageName)) {
2832 proc = p;
2833 }
2834 }
2835 }
2836 }
2837
2838 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002839 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002840 + " initialPid=" + initialPid
2841 + " packageName=" + packageName);
2842 return;
2843 }
2844
2845 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002846 if (proc.pid == Process.myPid()) {
2847 Log.w(TAG, "crashApplication: trying to crash self!");
2848 return;
2849 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002850 long ident = Binder.clearCallingIdentity();
2851 try {
2852 proc.thread.scheduleCrash(message);
2853 } catch (RemoteException e) {
2854 }
2855 Binder.restoreCallingIdentity(ident);
2856 }
2857 }
2858 }
2859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 public final void finishSubActivity(IBinder token, String resultWho,
2861 int requestCode) {
2862 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002864 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 Binder.restoreCallingIdentity(origId);
2866 }
2867 }
2868
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002869 public boolean finishActivityAffinity(IBinder token) {
2870 synchronized(this) {
2871 final long origId = Binder.clearCallingIdentity();
2872 boolean res = mMainStack.finishActivityAffinityLocked(token);
2873 Binder.restoreCallingIdentity(origId);
2874 return res;
2875 }
2876 }
2877
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002878 public boolean willActivityBeVisible(IBinder token) {
2879 synchronized(this) {
2880 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002881 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2882 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002883 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002884 return true;
2885 }
2886 if (r.fullscreen && !r.finishing) {
2887 return false;
2888 }
2889 }
2890 return true;
2891 }
2892 }
2893
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002894 public void overridePendingTransition(IBinder token, String packageName,
2895 int enterAnim, int exitAnim) {
2896 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002897 ActivityRecord self = mMainStack.isInStackLocked(token);
2898 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002899 return;
2900 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002901
2902 final long origId = Binder.clearCallingIdentity();
2903
2904 if (self.state == ActivityState.RESUMED
2905 || self.state == ActivityState.PAUSING) {
2906 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002907 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002908 }
2909
2910 Binder.restoreCallingIdentity(origId);
2911 }
2912 }
2913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 * Main function for removing an existing process from the activity manager
2916 * as a result of that process going away. Clears out all connections
2917 * to the process.
2918 */
2919 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002920 boolean restarting, boolean allowRestart) {
2921 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002923 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
2925
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002926 if (mProfileProc == app) {
2927 clearProfilerLocked();
2928 }
2929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002931 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002932 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2933 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002934 mMainStack.mPausingActivity = null;
2935 }
2936 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2937 mMainStack.mLastPausedActivity = null;
2938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939
2940 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002941 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942
2943 app.activities.clear();
2944
2945 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002946 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 + " running instrumentation " + app.instrumentationClass);
2948 Bundle info = new Bundle();
2949 info.putString("shortMsg", "Process crashed.");
2950 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2951 }
2952
2953 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002954 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 // If there was nothing to resume, and we are not already
2956 // restarting this process, but there is a visible activity that
2957 // is hosted by the process... then make sure all visible
2958 // activities are running, taking care of restarting this
2959 // process.
2960 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002961 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 }
2963 }
2964 }
2965 }
2966
2967 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2968 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002970 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2971 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2973 return i;
2974 }
2975 }
2976 return -1;
2977 }
2978
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002979 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 IApplicationThread thread) {
2981 if (thread == null) {
2982 return null;
2983 }
2984
2985 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002986 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 }
2988
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002989 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 IApplicationThread thread) {
2991
2992 mProcDeaths[0]++;
2993
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002994 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2995 synchronized (stats) {
2996 stats.noteProcessDiedLocked(app.info.uid, pid);
2997 }
2998
Magnus Edlund7bb25812010-02-24 15:45:06 +01002999 // Clean up already done if the process has been re-started.
3000 if (app.pid == pid && app.thread != null &&
3001 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003002 if (!app.killedBackground) {
3003 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3004 + ") has died.");
3005 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003006 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003007 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 TAG, "Dying app: " + app + ", pid: " + pid
3009 + ", thread: " + thread.asBinder());
3010 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003011 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012
3013 if (doLowMem) {
3014 // If there are no longer any background processes running,
3015 // and the app that died was not running instrumentation,
3016 // then tell everyone we are now low on memory.
3017 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003018 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3019 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003020 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 haveBg = true;
3022 break;
3023 }
3024 }
3025
3026 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003027 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003028 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003029 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3030 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003031 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003032 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3033 // The low memory report is overriding any current
3034 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003035 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003036 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003037 rec.lastRequestedGc = 0;
3038 } else {
3039 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003041 rec.reportLowMemory = true;
3042 rec.lastLowMemory = now;
3043 mProcessesToGc.remove(rec);
3044 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 }
3046 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003047 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003048 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 }
3050 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003051 } else if (app.pid != pid) {
3052 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003053 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003054 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003055 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003056 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003057 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 + thread.asBinder());
3059 }
3060 }
3061
Dan Egnor42471dd2010-01-07 17:25:22 -08003062 /**
3063 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003064 * @param clearTraces causes the dump file to be erased prior to the new
3065 * traces being written, if true; when false, the new traces will be
3066 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003067 * @param firstPids of dalvik VM processes to dump stack traces for first
3068 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003069 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003070 * @return file containing stack traces, or null if no dump file is configured
3071 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003072 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003073 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003074 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3075 if (tracesPath == null || tracesPath.length() == 0) {
3076 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003078
3079 File tracesFile = new File(tracesPath);
3080 try {
3081 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003082 if (!tracesDir.exists()) {
3083 tracesFile.mkdirs();
3084 if (!SELinux.restorecon(tracesDir)) {
3085 return null;
3086 }
3087 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003088 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3089
Christopher Tate6ee412d2010-05-28 12:01:56 -07003090 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003091 tracesFile.createNewFile();
3092 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3093 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003094 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003095 return null;
3096 }
3097
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003098 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003099 return tracesFile;
3100 }
3101
3102 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003103 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003104 // Use a FileObserver to detect when traces finish writing.
3105 // The order of traces is considered important to maintain for legibility.
3106 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3107 public synchronized void onEvent(int event, String path) { notify(); }
3108 };
3109
3110 try {
3111 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003112
3113 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003114 if (firstPids != null) {
3115 try {
3116 int num = firstPids.size();
3117 for (int i = 0; i < num; i++) {
3118 synchronized (observer) {
3119 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3120 observer.wait(200); // Wait for write-close, give up after 200msec
3121 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003122 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003123 } catch (InterruptedException e) {
3124 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003125 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003126 }
3127
3128 // Next measure CPU usage.
3129 if (processStats != null) {
3130 processStats.init();
3131 System.gc();
3132 processStats.update();
3133 try {
3134 synchronized (processStats) {
3135 processStats.wait(500); // measure over 1/2 second.
3136 }
3137 } catch (InterruptedException e) {
3138 }
3139 processStats.update();
3140
3141 // We'll take the stack crawls of just the top apps using CPU.
3142 final int N = processStats.countWorkingStats();
3143 int numProcs = 0;
3144 for (int i=0; i<N && numProcs<5; i++) {
3145 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3146 if (lastPids.indexOfKey(stats.pid) >= 0) {
3147 numProcs++;
3148 try {
3149 synchronized (observer) {
3150 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3151 observer.wait(200); // Wait for write-close, give up after 200msec
3152 }
3153 } catch (InterruptedException e) {
3154 Log.wtf(TAG, e);
3155 }
3156
3157 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003158 }
3159 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003160
Dan Egnor42471dd2010-01-07 17:25:22 -08003161 } finally {
3162 observer.stopWatching();
3163 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003164
3165 if (nativeProcs != null) {
3166 int[] pids = Process.getPidsForCommands(nativeProcs);
3167 if (pids != null) {
3168 for (int pid : pids) {
3169 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3170 }
3171 }
3172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 }
3174
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003175 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003176 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003177 return;
3178 }
3179 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3180 if (tracesPath == null || tracesPath.length() == 0) {
3181 return;
3182 }
3183
3184 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3185 StrictMode.allowThreadDiskWrites();
3186 try {
3187 final File tracesFile = new File(tracesPath);
3188 final File tracesDir = tracesFile.getParentFile();
3189 final File tracesTmp = new File(tracesDir, "__tmp__");
3190 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003191 if (!tracesDir.exists()) {
3192 tracesFile.mkdirs();
3193 if (!SELinux.restorecon(tracesDir.getPath())) {
3194 return;
3195 }
3196 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003197 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3198
3199 if (tracesFile.exists()) {
3200 tracesTmp.delete();
3201 tracesFile.renameTo(tracesTmp);
3202 }
3203 StringBuilder sb = new StringBuilder();
3204 Time tobj = new Time();
3205 tobj.set(System.currentTimeMillis());
3206 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3207 sb.append(": ");
3208 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3209 sb.append(" since ");
3210 sb.append(msg);
3211 FileOutputStream fos = new FileOutputStream(tracesFile);
3212 fos.write(sb.toString().getBytes());
3213 if (app == null) {
3214 fos.write("\n*** No application process!".getBytes());
3215 }
3216 fos.close();
3217 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3218 } catch (IOException e) {
3219 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3220 return;
3221 }
3222
3223 if (app != null) {
3224 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3225 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003226 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003227 }
3228
3229 File lastTracesFile = null;
3230 File curTracesFile = null;
3231 for (int i=9; i>=0; i--) {
3232 String name = String.format("slow%02d.txt", i);
3233 curTracesFile = new File(tracesDir, name);
3234 if (curTracesFile.exists()) {
3235 if (lastTracesFile != null) {
3236 curTracesFile.renameTo(lastTracesFile);
3237 } else {
3238 curTracesFile.delete();
3239 }
3240 }
3241 lastTracesFile = curTracesFile;
3242 }
3243 tracesFile.renameTo(curTracesFile);
3244 if (tracesTmp.exists()) {
3245 tracesTmp.renameTo(tracesFile);
3246 }
3247 } finally {
3248 StrictMode.setThreadPolicy(oldPolicy);
3249 }
3250 }
3251
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003252 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003253 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003254 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3255 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3256
Dianne Hackborn287952c2010-09-22 22:34:31 -07003257 if (mController != null) {
3258 try {
3259 // 0 == continue, -1 = kill process immediately
3260 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3261 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3262 } catch (RemoteException e) {
3263 mController = null;
3264 }
3265 }
3266
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003267 long anrTime = SystemClock.uptimeMillis();
3268 if (MONITOR_CPU_USAGE) {
3269 updateCpuStatsNow();
3270 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003271
3272 synchronized (this) {
3273 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3274 if (mShuttingDown) {
3275 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3276 return;
3277 } else if (app.notResponding) {
3278 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3279 return;
3280 } else if (app.crashing) {
3281 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3282 return;
3283 }
3284
3285 // In case we come through here for the same app before completing
3286 // this one, mark as anring now so we will bail out.
3287 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003288
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003289 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003290 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3291 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003292
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003293 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003294 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003295
3296 int parentPid = app.pid;
3297 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003298 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003299
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003300 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003301
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003302 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3303 ProcessRecord r = mLruProcesses.get(i);
3304 if (r != null && r.thread != null) {
3305 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003306 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3307 if (r.persistent) {
3308 firstPids.add(pid);
3309 } else {
3310 lastPids.put(pid, Boolean.TRUE);
3311 }
3312 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 }
3315 }
3316
Dan Egnor42471dd2010-01-07 17:25:22 -08003317 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003318 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003319 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003320 info.append("ANR in ").append(app.processName);
3321 if (activity != null && activity.shortComponentName != null) {
3322 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003323 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003324 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003326 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003328 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003329 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331
Dianne Hackborn287952c2010-09-22 22:34:31 -07003332 final ProcessStats processStats = new ProcessStats(true);
3333
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003334 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003335
Dan Egnor42471dd2010-01-07 17:25:22 -08003336 String cpuInfo = null;
3337 if (MONITOR_CPU_USAGE) {
3338 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003339 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003340 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003341 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003342 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003343 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 }
3345
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003346 info.append(processStats.printCurrentState(anrTime));
3347
Joe Onorato8a9b2202010-02-26 18:56:32 -08003348 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003349 if (tracesFile == null) {
3350 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3351 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3352 }
3353
Jeff Sharkeya353d262011-10-28 11:12:06 -07003354 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3355 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003356
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003357 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003359 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3360 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003362 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3363 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 }
3365 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003366 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 }
3368 }
3369
Dan Egnor42471dd2010-01-07 17:25:22 -08003370 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3371 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3372 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003373
3374 synchronized (this) {
3375 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003376 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003377 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003378 app.processName, app.setAdj, "background ANR");
3379 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003380 return;
3381 }
3382
3383 // Set the app's notResponding state, and look up the errorReportReceiver
3384 makeAppNotRespondingLocked(app,
3385 activity != null ? activity.shortComponentName : null,
3386 annotation != null ? "ANR " + annotation : "ANR",
3387 info.toString());
3388
3389 // Bring up the infamous App Not Responding dialog
3390 Message msg = Message.obtain();
3391 HashMap map = new HashMap();
3392 msg.what = SHOW_NOT_RESPONDING_MSG;
3393 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003394 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003395 map.put("app", app);
3396 if (activity != null) {
3397 map.put("activity", activity);
3398 }
3399
3400 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 }
3403
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003404 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3405 if (!mLaunchWarningShown) {
3406 mLaunchWarningShown = true;
3407 mHandler.post(new Runnable() {
3408 @Override
3409 public void run() {
3410 synchronized (ActivityManagerService.this) {
3411 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3412 d.show();
3413 mHandler.postDelayed(new Runnable() {
3414 @Override
3415 public void run() {
3416 synchronized (ActivityManagerService.this) {
3417 d.dismiss();
3418 mLaunchWarningShown = false;
3419 }
3420 }
3421 }, 4000);
3422 }
3423 }
3424 });
3425 }
3426 }
3427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003429 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003430 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 int uid = Binder.getCallingUid();
3432 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003433 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003434 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 long callingId = Binder.clearCallingIdentity();
3436 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003437 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 int pkgUid = -1;
3439 synchronized(this) {
3440 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003441 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 } catch (RemoteException e) {
3443 }
3444 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003445 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 return false;
3447 }
3448 if (uid == pkgUid || checkComponentPermission(
3449 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003450 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003452 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 } else {
3454 throw new SecurityException(pid+" does not have permission:"+
3455 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3456 "for process:"+packageName);
3457 }
3458 }
3459
3460 try {
3461 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003462 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3464 Uri.fromParts("package", packageName, null));
3465 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003466 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003467 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 } catch (RemoteException e) {
3469 }
3470 } finally {
3471 Binder.restoreCallingIdentity(callingId);
3472 }
3473 return true;
3474 }
3475
Dianne Hackborn1676c852012-09-10 14:52:30 -07003476 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003477 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3478 != PackageManager.PERMISSION_GRANTED &&
3479 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3480 != PackageManager.PERMISSION_GRANTED) {
3481 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 + Binder.getCallingPid()
3483 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003484 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003485 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 throw new SecurityException(msg);
3487 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003488
Dianne Hackborn139748f2012-09-24 11:36:57 -07003489 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003490 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 long callingId = Binder.clearCallingIdentity();
3492 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003493 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003495 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003497 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 } catch (RemoteException e) {
3499 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003500 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003501 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 return;
3503 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003504 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003505 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3506 }
3507 } finally {
3508 Binder.restoreCallingIdentity(callingId);
3509 }
3510 }
3511
3512 public void killAllBackgroundProcesses() {
3513 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3514 != PackageManager.PERMISSION_GRANTED) {
3515 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3516 + Binder.getCallingPid()
3517 + ", uid=" + Binder.getCallingUid()
3518 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3519 Slog.w(TAG, msg);
3520 throw new SecurityException(msg);
3521 }
3522
3523 long callingId = Binder.clearCallingIdentity();
3524 try {
3525 synchronized(this) {
3526 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3527 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3528 final int NA = apps.size();
3529 for (int ia=0; ia<NA; ia++) {
3530 ProcessRecord app = apps.valueAt(ia);
3531 if (app.persistent) {
3532 // we don't kill persistent processes
3533 continue;
3534 }
3535 if (app.removed) {
3536 procs.add(app);
3537 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3538 app.removed = true;
3539 procs.add(app);
3540 }
3541 }
3542 }
3543
3544 int N = procs.size();
3545 for (int i=0; i<N; i++) {
3546 removeProcessLocked(procs.get(i), false, true, "kill all background");
3547 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003548 }
3549 } finally {
3550 Binder.restoreCallingIdentity(callingId);
3551 }
3552 }
3553
Dianne Hackborn1676c852012-09-10 14:52:30 -07003554 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003555 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3556 != PackageManager.PERMISSION_GRANTED) {
3557 String msg = "Permission Denial: forceStopPackage() from pid="
3558 + Binder.getCallingPid()
3559 + ", uid=" + Binder.getCallingUid()
3560 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003561 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003562 throw new SecurityException(msg);
3563 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003564 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003565 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003566 long callingId = Binder.clearCallingIdentity();
3567 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003568 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003569 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003570 int[] users = userId == UserHandle.USER_ALL
3571 ? getUsersLocked() : new int[] { userId };
3572 for (int user : users) {
3573 int pkgUid = -1;
3574 try {
3575 pkgUid = pm.getPackageUid(packageName, user);
3576 } catch (RemoteException e) {
3577 }
3578 if (pkgUid == -1) {
3579 Slog.w(TAG, "Invalid packageName: " + packageName);
3580 continue;
3581 }
3582 try {
3583 pm.setPackageStoppedState(packageName, true, user);
3584 } catch (RemoteException e) {
3585 } catch (IllegalArgumentException e) {
3586 Slog.w(TAG, "Failed trying to unstop package "
3587 + packageName + ": " + e);
3588 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003589 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003590 forceStopPackageLocked(packageName, pkgUid);
3591 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 }
3594 } finally {
3595 Binder.restoreCallingIdentity(callingId);
3596 }
3597 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003598
3599 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003600 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003601 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003602 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003603 if (pkg == null) {
3604 return;
3605 }
3606 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003607 if (appid < 0) {
3608 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003609 return;
3610 }
3611 int callerUid = Binder.getCallingUid();
3612 // Only the system server can kill an application
3613 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003614 // Post an aysnc message to kill the application
3615 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003616 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003617 msg.arg2 = 0;
3618 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003619 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003620 } else {
3621 throw new SecurityException(callerUid + " cannot kill pkg: " +
3622 pkg);
3623 }
3624 }
3625
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003626 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003627 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003628
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003629 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003630 final int uid = Binder.getCallingUid();
3631 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003632 try {
3633 synchronized (this) {
3634 // Only allow this from foreground processes, so that background
3635 // applications can't abuse it to prevent system UI from being shown.
3636 if (uid >= Process.FIRST_APPLICATION_UID) {
3637 ProcessRecord proc;
3638 synchronized (mPidsSelfLocked) {
3639 proc = mPidsSelfLocked.get(pid);
3640 }
3641 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3642 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3643 + " from background process " + proc);
3644 return;
3645 }
3646 }
3647 closeSystemDialogsLocked(reason);
3648 }
3649 } finally {
3650 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003651 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003652 }
3653
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003654 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003655 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003656 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3657 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003658 if (reason != null) {
3659 intent.putExtra("reason", reason);
3660 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003661 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003662
Dianne Hackborne302a162012-05-15 14:58:32 -07003663 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3664 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003665 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003666 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003667 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003668 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003669 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003670
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003671 broadcastIntentLocked(null, null, intent, null,
3672 null, 0, null, null, null, false, false, -1,
3673 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003674 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003675
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003676 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003677 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003678 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003679 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3680 for (int i=pids.length-1; i>=0; i--) {
3681 infos[i] = new Debug.MemoryInfo();
3682 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003683 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003684 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003685 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003686
Dianne Hackbornb437e092011-08-05 17:50:29 -07003687 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003688 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003689 long[] pss = new long[pids.length];
3690 for (int i=pids.length-1; i>=0; i--) {
3691 pss[i] = Debug.getPss(pids[i]);
3692 }
3693 return pss;
3694 }
3695
Christopher Tate5e1ab332009-09-01 20:32:49 -07003696 public void killApplicationProcess(String processName, int uid) {
3697 if (processName == null) {
3698 return;
3699 }
3700
3701 int callerUid = Binder.getCallingUid();
3702 // Only the system server can kill an application
3703 if (callerUid == Process.SYSTEM_UID) {
3704 synchronized (this) {
3705 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003706 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003707 try {
3708 app.thread.scheduleSuicide();
3709 } catch (RemoteException e) {
3710 // If the other end already died, then our work here is done.
3711 }
3712 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003713 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003714 + processName + " / " + uid);
3715 }
3716 }
3717 } else {
3718 throw new SecurityException(callerUid + " cannot kill app process: " +
3719 processName);
3720 }
3721 }
3722
Dianne Hackborn03abb812010-01-04 18:43:19 -08003723 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003724 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3725 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3727 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003728 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003729 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3730 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003733 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 broadcastIntentLocked(null, null, intent,
3735 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003736 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003737 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003739
3740 private void forceStopUserLocked(int userId) {
3741 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3742 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003743 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3744 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003745 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3746 broadcastIntentLocked(null, null, intent,
3747 null, null, 0, null, null, null,
3748 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003749 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003750 }
3751
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003752 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003753 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3754 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003755 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756
Dianne Hackborn03abb812010-01-04 18:43:19 -08003757 // Remove all processes this package may have touched: all with the
3758 // same UID (except for the system or root user), and all whose name
3759 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003760 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003761 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3762 final int NA = apps.size();
3763 for (int ia=0; ia<NA; ia++) {
3764 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003765 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003766 // we don't kill persistent processes
3767 continue;
3768 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003769 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003770 if (doit) {
3771 procs.add(app);
3772 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003773 continue;
3774 }
3775
3776 // Skip process if it doesn't meet our oom adj requirement.
3777 if (app.setAdj < minOomAdj) {
3778 continue;
3779 }
3780
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003781 // If no package is specified, we call all processes under the
3782 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003783 if (packageName == null) {
3784 if (app.userId != userId) {
3785 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003786 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003787 // Package has been specified, we want to hit all processes
3788 // that match it. We need to qualify this by the processes
3789 // that are running under the specified app and user ID.
3790 } else {
3791 if (UserHandle.getAppId(app.uid) != appId) {
3792 continue;
3793 }
3794 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3795 continue;
3796 }
3797 if (!app.pkgList.contains(packageName)) {
3798 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003799 }
3800 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003801
3802 // Process has passed all conditions, kill it!
3803 if (!doit) {
3804 return true;
3805 }
3806 app.removed = true;
3807 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003808 }
3809 }
3810
3811 int N = procs.size();
3812 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003813 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003814 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003815 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003816 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003817
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003818 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003819 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003820 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003821 int i;
3822 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003824 if (userId == UserHandle.USER_ALL && name == null) {
3825 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3826 }
3827
3828 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003830 appId = UserHandle.getAppId(
3831 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 } catch (RemoteException e) {
3833 }
3834 }
3835
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003836 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003837 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003838 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3839 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003840 } else {
3841 Slog.i(TAG, "Force stopping user " + userId);
3842 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003843
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003844 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3845 while (badApps.hasNext()) {
3846 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003847 for (i=ba.size()-1; i>=0; i--) {
3848 boolean remove = false;
3849 final int entUid = ba.keyAt(i);
3850 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003851 if (userId == UserHandle.USER_ALL) {
3852 if (UserHandle.getAppId(entUid) == appId) {
3853 remove = true;
3854 }
3855 } else {
3856 if (entUid == UserHandle.getUid(userId, appId)) {
3857 remove = true;
3858 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003859 }
3860 } else if (UserHandle.getUserId(entUid) == userId) {
3861 remove = true;
3862 }
3863 if (remove) {
3864 ba.removeAt(i);
3865 }
3866 }
3867 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003868 badApps.remove();
3869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 }
3871 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003872
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003873 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3874 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003875 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003877 TaskRecord lastTask = null;
3878 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003879 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003880 final boolean samePackage = r.packageName.equals(name)
3881 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003882 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003883 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003884 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003885 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003886 if (r.finishing) {
3887 // If this activity is just finishing, then it is not
3888 // interesting as far as something to stop.
3889 continue;
3890 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003891 return true;
3892 }
3893 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003894 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003895 if (samePackage) {
3896 if (r.app != null) {
3897 r.app.removed = true;
3898 }
3899 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003901 lastTask = r.task;
3902 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003903 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003904 i--;
3905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 }
3907 }
3908
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003909 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3910 if (!doit) {
3911 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003913 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003915
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003916 if (name == null) {
3917 // Remove all sticky broadcasts from this user.
3918 mStickyBroadcasts.remove(userId);
3919 }
3920
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003921 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003922 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3923 userId, providers)) {
3924 if (!doit) {
3925 return true;
3926 }
3927 didSomething = true;
3928 }
3929 N = providers.size();
3930 for (i=0; i<N; i++) {
3931 removeDyingProviderLocked(null, providers.get(i), true);
3932 }
3933
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003934 if (name == null) {
3935 // Remove pending intents. For now we only do this when force
3936 // stopping users, because we have some problems when doing this
3937 // for packages -- app widgets are not currently cleaned up for
3938 // such packages, so they can be left with bad pending intents.
3939 if (mIntentSenderRecords.size() > 0) {
3940 Iterator<WeakReference<PendingIntentRecord>> it
3941 = mIntentSenderRecords.values().iterator();
3942 while (it.hasNext()) {
3943 WeakReference<PendingIntentRecord> wpir = it.next();
3944 if (wpir == null) {
3945 it.remove();
3946 continue;
3947 }
3948 PendingIntentRecord pir = wpir.get();
3949 if (pir == null) {
3950 it.remove();
3951 continue;
3952 }
3953 if (name == null) {
3954 // Stopping user, remove all objects for the user.
3955 if (pir.key.userId != userId) {
3956 // Not the same user, skip it.
3957 continue;
3958 }
3959 } else {
3960 if (UserHandle.getAppId(pir.uid) != appId) {
3961 // Different app id, skip it.
3962 continue;
3963 }
3964 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3965 // Different user, skip it.
3966 continue;
3967 }
3968 if (!pir.key.packageName.equals(name)) {
3969 // Different package, skip it.
3970 continue;
3971 }
3972 }
3973 if (!doit) {
3974 return true;
3975 }
3976 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003977 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003978 pir.canceled = true;
3979 if (pir.key.activity != null) {
3980 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003981 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003982 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003983 }
3984 }
3985
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003986 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003987 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003988 AttributeCache ac = AttributeCache.instance();
3989 if (ac != null) {
3990 ac.removePackage(name);
3991 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003992 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003993 if (mBooted) {
3994 mMainStack.resumeTopActivityLocked(null);
3995 mMainStack.scheduleIdleLocked();
3996 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003997 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003998
3999 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 }
4001
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004002 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004003 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004005 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004006 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004007 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 + "/" + uid + ")");
4009
4010 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004011 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004012 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004013 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4014 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004015 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 boolean needRestart = false;
4018 if (app.pid > 0 && app.pid != MY_PID) {
4019 int pid = app.pid;
4020 synchronized (mPidsSelfLocked) {
4021 mPidsSelfLocked.remove(pid);
4022 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4023 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004024 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004025 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004026 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004027 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004029 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004031 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 } else {
4033 needRestart = true;
4034 }
4035 }
4036 } else {
4037 mRemovedProcesses.add(app);
4038 }
4039
4040 return needRestart;
4041 }
4042
4043 private final void processStartTimedOutLocked(ProcessRecord app) {
4044 final int pid = app.pid;
4045 boolean gone = false;
4046 synchronized (mPidsSelfLocked) {
4047 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4048 if (knownApp != null && knownApp.thread == null) {
4049 mPidsSelfLocked.remove(pid);
4050 gone = true;
4051 }
4052 }
4053
4054 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004055 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004056 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4057 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004058 mProcessNames.remove(app.processName, app.uid);
4059 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004060 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004061 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4062 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004063 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004064 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004065 // Take care of any launching providers waiting for this process.
4066 checkAppInLaunchingProvidersLocked(app, true);
4067 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004068 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004069 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004070 app.processName, app.setAdj, "start timeout");
4071 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004072 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004073 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004074 try {
4075 IBackupManager bm = IBackupManager.Stub.asInterface(
4076 ServiceManager.getService(Context.BACKUP_SERVICE));
4077 bm.agentDisconnected(app.info.packageName);
4078 } catch (RemoteException e) {
4079 // Can't happen; the backup manager is local
4080 }
4081 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004082 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004083 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004084 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004087 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 }
4089 }
4090
4091 private final boolean attachApplicationLocked(IApplicationThread thread,
4092 int pid) {
4093
4094 // Find the application record that is being attached... either via
4095 // the pid if we are running in multiple processes, or just pull the
4096 // next app record if we are emulating process with anonymous threads.
4097 ProcessRecord app;
4098 if (pid != MY_PID && pid >= 0) {
4099 synchronized (mPidsSelfLocked) {
4100 app = mPidsSelfLocked.get(pid);
4101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 } else {
4103 app = null;
4104 }
4105
4106 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004107 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004109 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004111 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 } else {
4113 try {
4114 thread.scheduleExit();
4115 } catch (Exception e) {
4116 // Ignore exceptions.
4117 }
4118 }
4119 return false;
4120 }
4121
4122 // If this application record is still attached to a previous
4123 // process, clean it up now.
4124 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004125 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
4127
4128 // Tell the process all about itself.
4129
Joe Onorato8a9b2202010-02-26 18:56:32 -08004130 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 TAG, "Binding process pid " + pid + " to record " + app);
4132
4133 String processName = app.processName;
4134 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004135 AppDeathRecipient adr = new AppDeathRecipient(
4136 app, pid, thread);
4137 thread.asBinder().linkToDeath(adr, 0);
4138 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 } catch (RemoteException e) {
4140 app.resetPackageList();
4141 startProcessLocked(app, "link fail", processName);
4142 return false;
4143 }
4144
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004145 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146
4147 app.thread = thread;
4148 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004149 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4150 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 app.forcingToForeground = null;
4152 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004153 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 app.debugging = false;
4155
4156 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4157
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004158 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004159 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004161 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004162 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004163 }
4164
Joe Onorato8a9b2202010-02-26 18:56:32 -08004165 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 TAG, "New app record " + app
4167 + " thread=" + thread.asBinder() + " pid=" + pid);
4168 try {
4169 int testMode = IApplicationThread.DEBUG_OFF;
4170 if (mDebugApp != null && mDebugApp.equals(processName)) {
4171 testMode = mWaitForDebugger
4172 ? IApplicationThread.DEBUG_WAIT
4173 : IApplicationThread.DEBUG_ON;
4174 app.debugging = true;
4175 if (mDebugTransient) {
4176 mDebugApp = mOrigDebugApp;
4177 mWaitForDebugger = mOrigWaitForDebugger;
4178 }
4179 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004180 String profileFile = app.instrumentationProfileFile;
4181 ParcelFileDescriptor profileFd = null;
4182 boolean profileAutoStop = false;
4183 if (mProfileApp != null && mProfileApp.equals(processName)) {
4184 mProfileProc = app;
4185 profileFile = mProfileFile;
4186 profileFd = mProfileFd;
4187 profileAutoStop = mAutoStopProfiler;
4188 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004189 boolean enableOpenGlTrace = false;
4190 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4191 enableOpenGlTrace = true;
4192 mOpenGlTraceApp = null;
4193 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004194
Christopher Tate181fafa2009-05-14 11:12:14 -07004195 // If the app is being launched for restore or full backup, set it up specially
4196 boolean isRestrictedBackupMode = false;
4197 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4198 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004199 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004200 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4201 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004202
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004203 ensurePackageDexOpt(app.instrumentationInfo != null
4204 ? app.instrumentationInfo.packageName
4205 : app.info.packageName);
4206 if (app.instrumentationClass != null) {
4207 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004208 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004209 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004210 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004211 ApplicationInfo appInfo = app.instrumentationInfo != null
4212 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004213 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004214 if (profileFd != null) {
4215 profileFd = profileFd.dup();
4216 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004217 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004218 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004219 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4220 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004221 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004222 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004223 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004224 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 } catch (Exception e) {
4226 // todo: Yikes! What should we do? For now we will try to
4227 // start another process, but that could easily get us in
4228 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004229 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230
4231 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004232 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 startProcessLocked(app, "bind fail", processName);
4234 return false;
4235 }
4236
4237 // Remove this record from the list of starting applications.
4238 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004239 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4240 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 mProcessesOnHold.remove(app);
4242
4243 boolean badApp = false;
4244 boolean didSomething = false;
4245
4246 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004247 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004248 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004249 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 && processName.equals(hr.processName)) {
4251 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004252 if (mHeadless) {
4253 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4254 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 didSomething = true;
4256 }
4257 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004258 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 + hr.intent.getComponent().flattenToShortString(), e);
4260 badApp = true;
4261 }
4262 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004263 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 }
4265 }
4266
4267 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004268 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004270 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 badApp = true;
4273 }
4274 }
4275
Christopher Tatef46723b2012-01-26 14:19:24 -08004276 // Check if a next-broadcast receiver is in this process...
4277 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004279 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004281 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 }
4284 }
4285
Christopher Tate181fafa2009-05-14 11:12:14 -07004286 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004287 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004288 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004289 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004290 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004291 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4292 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4293 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004294 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004295 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004296 e.printStackTrace();
4297 }
4298 }
4299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 if (badApp) {
4301 // todo: Also need to kill application to deal with all
4302 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004303 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 return false;
4305 }
4306
4307 if (!didSomething) {
4308 updateOomAdjLocked();
4309 }
4310
4311 return true;
4312 }
4313
4314 public final void attachApplication(IApplicationThread thread) {
4315 synchronized (this) {
4316 int callingPid = Binder.getCallingPid();
4317 final long origId = Binder.clearCallingIdentity();
4318 attachApplicationLocked(thread, callingPid);
4319 Binder.restoreCallingIdentity(origId);
4320 }
4321 }
4322
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004323 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004325 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4326 if (stopProfiling) {
4327 synchronized (this) {
4328 if (mProfileProc == r.app) {
4329 if (mProfileFd != null) {
4330 try {
4331 mProfileFd.close();
4332 } catch (IOException e) {
4333 }
4334 clearProfilerLocked();
4335 }
4336 }
4337 }
4338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 Binder.restoreCallingIdentity(origId);
4340 }
4341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004343 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004344 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004346
4347 synchronized (this) {
4348 updateEventDispatchingLocked();
4349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 }
4351
Dianne Hackborn661cd522011-08-22 00:26:20 -07004352 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004353 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004354 mWindowManager.showBootMessage(msg, always);
4355 }
4356
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004357 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004358 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004359 final long token = Binder.clearCallingIdentity();
4360 try {
4361 synchronized (this) {
4362 if (mLockScreenShown) {
4363 mLockScreenShown = false;
4364 comeOutOfSleepIfNeededLocked();
4365 }
4366 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004367 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004368 } finally {
4369 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004370 }
4371 }
4372
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004373 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004374 IntentFilter pkgFilter = new IntentFilter();
4375 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4376 pkgFilter.addDataScheme("package");
4377 mContext.registerReceiver(new BroadcastReceiver() {
4378 @Override
4379 public void onReceive(Context context, Intent intent) {
4380 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4381 if (pkgs != null) {
4382 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004383 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004384 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4385 setResultCode(Activity.RESULT_OK);
4386 return;
4387 }
4388 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004389 }
4390 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004391 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004392 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004393
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004394 synchronized (this) {
4395 // Ensure that any processes we had put on hold are now started
4396 // up.
4397 final int NP = mProcessesOnHold.size();
4398 if (NP > 0) {
4399 ArrayList<ProcessRecord> procs =
4400 new ArrayList<ProcessRecord>(mProcessesOnHold);
4401 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004402 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4403 + procs.get(ip));
4404 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004405 }
4406 }
4407
4408 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004409 // Start looking for apps that are abusing wake locks.
4410 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004411 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004412 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004413 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004414 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004415 for (int i=0; i<mStartedUsers.size(); i++) {
4416 UserStartedState uss = mStartedUsers.valueAt(i);
4417 if (uss.mState == UserStartedState.STATE_BOOTING) {
4418 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004419 final int userId = mStartedUsers.keyAt(i);
4420 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4421 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4422 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004423 null, null, 0, null, null,
4424 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004425 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004426 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004427 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004428 }
4429 }
4430 }
4431
4432 final void ensureBootCompleted() {
4433 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004434 boolean enableScreen;
4435 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004436 booting = mBooting;
4437 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004438 enableScreen = !mBooted;
4439 mBooted = true;
4440 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004441
4442 if (booting) {
4443 finishBooting();
4444 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004445
4446 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004447 enableScreenAfterBoot();
4448 }
4449 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004450
4451 public final void activityResumed(IBinder token) {
4452 final long origId = Binder.clearCallingIdentity();
4453 mMainStack.activityResumed(token);
4454 Binder.restoreCallingIdentity(origId);
4455 }
4456
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004457 public final void activityPaused(IBinder token) {
4458 final long origId = Binder.clearCallingIdentity();
4459 mMainStack.activityPaused(token, false);
4460 Binder.restoreCallingIdentity(origId);
4461 }
4462
4463 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4464 CharSequence description) {
4465 if (localLOGV) Slog.v(
4466 TAG, "Activity stopped: token=" + token);
4467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 // Refuse possible leaked file descriptors
4469 if (icicle != null && icicle.hasFileDescriptors()) {
4470 throw new IllegalArgumentException("File descriptors passed in Bundle");
4471 }
4472
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004473 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474
4475 final long origId = Binder.clearCallingIdentity();
4476
4477 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004478 r = mMainStack.isInStackLocked(token);
4479 if (r != null) {
4480 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 }
4482 }
4483
4484 if (r != null) {
4485 sendPendingThumbnail(r, null, null, null, false);
4486 }
4487
4488 trimApplications();
4489
4490 Binder.restoreCallingIdentity(origId);
4491 }
4492
4493 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004494 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004495 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 }
4497
4498 public String getCallingPackage(IBinder token) {
4499 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004500 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004501 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 }
4503 }
4504
4505 public ComponentName getCallingActivity(IBinder token) {
4506 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004507 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 return r != null ? r.intent.getComponent() : null;
4509 }
4510 }
4511
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004512 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004513 ActivityRecord r = mMainStack.isInStackLocked(token);
4514 if (r == null) {
4515 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004517 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 }
4519
4520 public ComponentName getActivityClassForToken(IBinder token) {
4521 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004522 ActivityRecord r = mMainStack.isInStackLocked(token);
4523 if (r == null) {
4524 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004526 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 }
4528 }
4529
4530 public String getPackageForToken(IBinder token) {
4531 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004532 ActivityRecord r = mMainStack.isInStackLocked(token);
4533 if (r == null) {
4534 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004536 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 }
4538 }
4539
4540 public IIntentSender getIntentSender(int type,
4541 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004542 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004543 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004544 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004546 if (intents != null) {
4547 if (intents.length < 1) {
4548 throw new IllegalArgumentException("Intents array length must be >= 1");
4549 }
4550 for (int i=0; i<intents.length; i++) {
4551 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004552 if (intent != null) {
4553 if (intent.hasFileDescriptors()) {
4554 throw new IllegalArgumentException("File descriptors passed in Intent");
4555 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004556 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004557 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4558 throw new IllegalArgumentException(
4559 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4560 }
4561 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004562 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004563 }
4564 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004565 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004566 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004567 }
4568 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004569 if (options != null) {
4570 if (options.hasFileDescriptors()) {
4571 throw new IllegalArgumentException("File descriptors passed in options");
4572 }
4573 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 synchronized(this) {
4576 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004577 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004578 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004579 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004580 "getIntentSender", null);
4581 if (origUserId == UserHandle.USER_CURRENT) {
4582 // We don't want to evaluate this until the pending intent is
4583 // actually executed. However, we do want to always do the
4584 // security checking for it above.
4585 userId = UserHandle.USER_CURRENT;
4586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004588 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004589 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004590 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4591 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 String msg = "Permission Denial: getIntentSender() from pid="
4593 + Binder.getCallingPid()
4594 + ", uid=" + Binder.getCallingUid()
4595 + ", (need uid=" + uid + ")"
4596 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004597 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 throw new SecurityException(msg);
4599 }
4600 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004601
4602 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004603 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 } catch (RemoteException e) {
4606 throw new SecurityException(e);
4607 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004608 }
4609 }
4610
Dianne Hackborn41203752012-08-31 14:05:51 -07004611 IIntentSender getIntentSenderLocked(int type, String packageName,
4612 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004613 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4614 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004615 if (DEBUG_MU)
4616 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004617 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004618 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004619 activity = mMainStack.isInStackLocked(token);
4620 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004621 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004623 if (activity.finishing) {
4624 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004626 }
4627
4628 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4629 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4630 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4631 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4632 |PendingIntent.FLAG_UPDATE_CURRENT);
4633
4634 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4635 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004636 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004637 WeakReference<PendingIntentRecord> ref;
4638 ref = mIntentSenderRecords.get(key);
4639 PendingIntentRecord rec = ref != null ? ref.get() : null;
4640 if (rec != null) {
4641 if (!cancelCurrent) {
4642 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004643 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004644 rec.key.requestIntent.replaceExtras(intents != null ?
4645 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004646 }
4647 if (intents != null) {
4648 intents[intents.length-1] = rec.key.requestIntent;
4649 rec.key.allIntents = intents;
4650 rec.key.allResolvedTypes = resolvedTypes;
4651 } else {
4652 rec.key.allIntents = null;
4653 rec.key.allResolvedTypes = null;
4654 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 return rec;
4657 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004658 rec.canceled = true;
4659 mIntentSenderRecords.remove(key);
4660 }
4661 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 return rec;
4663 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004664 rec = new PendingIntentRecord(this, key, callingUid);
4665 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004666 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004667 if (activity.pendingResults == null) {
4668 activity.pendingResults
4669 = new HashSet<WeakReference<PendingIntentRecord>>();
4670 }
4671 activity.pendingResults.add(rec.ref);
4672 }
4673 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 }
4675
4676 public void cancelIntentSender(IIntentSender sender) {
4677 if (!(sender instanceof PendingIntentRecord)) {
4678 return;
4679 }
4680 synchronized(this) {
4681 PendingIntentRecord rec = (PendingIntentRecord)sender;
4682 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004683 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004684 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4685 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 String msg = "Permission Denial: cancelIntentSender() from pid="
4687 + Binder.getCallingPid()
4688 + ", uid=" + Binder.getCallingUid()
4689 + " is not allowed to cancel packges "
4690 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004691 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 throw new SecurityException(msg);
4693 }
4694 } catch (RemoteException e) {
4695 throw new SecurityException(e);
4696 }
4697 cancelIntentSenderLocked(rec, true);
4698 }
4699 }
4700
4701 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4702 rec.canceled = true;
4703 mIntentSenderRecords.remove(rec.key);
4704 if (cleanActivity && rec.key.activity != null) {
4705 rec.key.activity.pendingResults.remove(rec.ref);
4706 }
4707 }
4708
4709 public String getPackageForIntentSender(IIntentSender pendingResult) {
4710 if (!(pendingResult instanceof PendingIntentRecord)) {
4711 return null;
4712 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004713 try {
4714 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4715 return res.key.packageName;
4716 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 }
4718 return null;
4719 }
4720
Christopher Tatec4a07d12012-04-06 14:19:13 -07004721 public int getUidForIntentSender(IIntentSender sender) {
4722 if (sender instanceof PendingIntentRecord) {
4723 try {
4724 PendingIntentRecord res = (PendingIntentRecord)sender;
4725 return res.uid;
4726 } catch (ClassCastException e) {
4727 }
4728 }
4729 return -1;
4730 }
4731
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004732 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4733 if (!(pendingResult instanceof PendingIntentRecord)) {
4734 return false;
4735 }
4736 try {
4737 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4738 if (res.key.allIntents == null) {
4739 return false;
4740 }
4741 for (int i=0; i<res.key.allIntents.length; i++) {
4742 Intent intent = res.key.allIntents[i];
4743 if (intent.getPackage() != null && intent.getComponent() != null) {
4744 return false;
4745 }
4746 }
4747 return true;
4748 } catch (ClassCastException e) {
4749 }
4750 return false;
4751 }
4752
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004753 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4754 if (!(pendingResult instanceof PendingIntentRecord)) {
4755 return false;
4756 }
4757 try {
4758 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4759 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4760 return true;
4761 }
4762 return false;
4763 } catch (ClassCastException e) {
4764 }
4765 return false;
4766 }
4767
Dianne Hackborn81038902012-11-26 17:04:09 -08004768 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4769 if (!(pendingResult instanceof PendingIntentRecord)) {
4770 return null;
4771 }
4772 try {
4773 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4774 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4775 } catch (ClassCastException e) {
4776 }
4777 return null;
4778 }
4779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 public void setProcessLimit(int max) {
4781 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4782 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004783 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004784 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004785 mProcessLimitOverride = max;
4786 }
4787 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 }
4789
4790 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004791 synchronized (this) {
4792 return mProcessLimitOverride;
4793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 }
4795
4796 void foregroundTokenDied(ForegroundToken token) {
4797 synchronized (ActivityManagerService.this) {
4798 synchronized (mPidsSelfLocked) {
4799 ForegroundToken cur
4800 = mForegroundProcesses.get(token.pid);
4801 if (cur != token) {
4802 return;
4803 }
4804 mForegroundProcesses.remove(token.pid);
4805 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4806 if (pr == null) {
4807 return;
4808 }
4809 pr.forcingToForeground = null;
4810 pr.foregroundServices = false;
4811 }
4812 updateOomAdjLocked();
4813 }
4814 }
4815
4816 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4817 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4818 "setProcessForeground()");
4819 synchronized(this) {
4820 boolean changed = false;
4821
4822 synchronized (mPidsSelfLocked) {
4823 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004824 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004825 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 return;
4827 }
4828 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4829 if (oldToken != null) {
4830 oldToken.token.unlinkToDeath(oldToken, 0);
4831 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004832 if (pr != null) {
4833 pr.forcingToForeground = null;
4834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 changed = true;
4836 }
4837 if (isForeground && token != null) {
4838 ForegroundToken newToken = new ForegroundToken() {
4839 public void binderDied() {
4840 foregroundTokenDied(this);
4841 }
4842 };
4843 newToken.pid = pid;
4844 newToken.token = token;
4845 try {
4846 token.linkToDeath(newToken, 0);
4847 mForegroundProcesses.put(pid, newToken);
4848 pr.forcingToForeground = token;
4849 changed = true;
4850 } catch (RemoteException e) {
4851 // If the process died while doing this, we will later
4852 // do the cleanup with the process death link.
4853 }
4854 }
4855 }
4856
4857 if (changed) {
4858 updateOomAdjLocked();
4859 }
4860 }
4861 }
4862
4863 // =========================================================
4864 // PERMISSIONS
4865 // =========================================================
4866
4867 static class PermissionController extends IPermissionController.Stub {
4868 ActivityManagerService mActivityManagerService;
4869 PermissionController(ActivityManagerService activityManagerService) {
4870 mActivityManagerService = activityManagerService;
4871 }
4872
4873 public boolean checkPermission(String permission, int pid, int uid) {
4874 return mActivityManagerService.checkPermission(permission, pid,
4875 uid) == PackageManager.PERMISSION_GRANTED;
4876 }
4877 }
4878
4879 /**
4880 * This can be called with or without the global lock held.
4881 */
4882 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004883 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 // We might be performing an operation on behalf of an indirect binder
4885 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4886 // client identity accordingly before proceeding.
4887 Identity tlsIdentity = sCallerIdentity.get();
4888 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004889 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4891 uid = tlsIdentity.uid;
4892 pid = tlsIdentity.pid;
4893 }
4894
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004895 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 return PackageManager.PERMISSION_GRANTED;
4897 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004898
4899 return ActivityManager.checkComponentPermission(permission, uid,
4900 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 }
4902
4903 /**
4904 * As the only public entry point for permissions checking, this method
4905 * can enforce the semantic that requesting a check on a null global
4906 * permission is automatically denied. (Internally a null permission
4907 * string is used when calling {@link #checkComponentPermission} in cases
4908 * when only uid-based security is needed.)
4909 *
4910 * This can be called with or without the global lock held.
4911 */
4912 public int checkPermission(String permission, int pid, int uid) {
4913 if (permission == null) {
4914 return PackageManager.PERMISSION_DENIED;
4915 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004916 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917 }
4918
4919 /**
4920 * Binder IPC calls go through the public entry point.
4921 * This can be called with or without the global lock held.
4922 */
4923 int checkCallingPermission(String permission) {
4924 return checkPermission(permission,
4925 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004926 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 }
4928
4929 /**
4930 * This can be called with or without the global lock held.
4931 */
4932 void enforceCallingPermission(String permission, String func) {
4933 if (checkCallingPermission(permission)
4934 == PackageManager.PERMISSION_GRANTED) {
4935 return;
4936 }
4937
4938 String msg = "Permission Denial: " + func + " from pid="
4939 + Binder.getCallingPid()
4940 + ", uid=" + Binder.getCallingUid()
4941 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004942 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 throw new SecurityException(msg);
4944 }
4945
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004946 /**
4947 * Determine if UID is holding permissions required to access {@link Uri} in
4948 * the given {@link ProviderInfo}. Final permission checking is always done
4949 * in {@link ContentProvider}.
4950 */
4951 private final boolean checkHoldingPermissionsLocked(
4952 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004953 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4954 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004955
4956 if (pi.applicationInfo.uid == uid) {
4957 return true;
4958 } else if (!pi.exported) {
4959 return false;
4960 }
4961
4962 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4963 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004965 // check if target holds top-level <provider> permissions
4966 if (!readMet && pi.readPermission != null
4967 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4968 readMet = true;
4969 }
4970 if (!writeMet && pi.writePermission != null
4971 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4972 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004974
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004975 // track if unprotected read/write is allowed; any denied
4976 // <path-permission> below removes this ability
4977 boolean allowDefaultRead = pi.readPermission == null;
4978 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004979
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004980 // check if target holds any <path-permission> that match uri
4981 final PathPermission[] pps = pi.pathPermissions;
4982 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004983 final String path = uri.getPath();
4984 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004985 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004986 i--;
4987 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004988 if (pp.match(path)) {
4989 if (!readMet) {
4990 final String pprperm = pp.getReadPermission();
4991 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4992 + pprperm + " for " + pp.getPath()
4993 + ": match=" + pp.match(path)
4994 + " check=" + pm.checkUidPermission(pprperm, uid));
4995 if (pprperm != null) {
4996 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4997 readMet = true;
4998 } else {
4999 allowDefaultRead = false;
5000 }
5001 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005002 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005003 if (!writeMet) {
5004 final String ppwperm = pp.getWritePermission();
5005 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5006 + ppwperm + " for " + pp.getPath()
5007 + ": match=" + pp.match(path)
5008 + " check=" + pm.checkUidPermission(ppwperm, uid));
5009 if (ppwperm != null) {
5010 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5011 writeMet = true;
5012 } else {
5013 allowDefaultWrite = false;
5014 }
5015 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005016 }
5017 }
5018 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005019 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005020
5021 // grant unprotected <provider> read/write, if not blocked by
5022 // <path-permission> above
5023 if (allowDefaultRead) readMet = true;
5024 if (allowDefaultWrite) writeMet = true;
5025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 } catch (RemoteException e) {
5027 return false;
5028 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005029
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005030 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 }
5032
5033 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5034 int modeFlags) {
5035 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005036 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 return true;
5038 }
5039 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5040 if (perms == null) return false;
5041 UriPermission perm = perms.get(uri);
5042 if (perm == null) return false;
5043 return (modeFlags&perm.modeFlags) == modeFlags;
5044 }
5045
5046 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005047 enforceNotIsolatedCaller("checkUriPermission");
5048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 // Another redirected-binder-call permissions check as in
5050 // {@link checkComponentPermission}.
5051 Identity tlsIdentity = sCallerIdentity.get();
5052 if (tlsIdentity != null) {
5053 uid = tlsIdentity.uid;
5054 pid = tlsIdentity.pid;
5055 }
5056
5057 // Our own process gets to do everything.
5058 if (pid == MY_PID) {
5059 return PackageManager.PERMISSION_GRANTED;
5060 }
5061 synchronized(this) {
5062 return checkUriPermissionLocked(uri, uid, modeFlags)
5063 ? PackageManager.PERMISSION_GRANTED
5064 : PackageManager.PERMISSION_DENIED;
5065 }
5066 }
5067
Dianne Hackborn39792d22010-08-19 18:01:52 -07005068 /**
5069 * Check if the targetPkg can be granted permission to access uri by
5070 * the callingUid using the given modeFlags. Throws a security exception
5071 * if callingUid is not allowed to do this. Returns the uid of the target
5072 * if the URI permission grant should be performed; returns -1 if it is not
5073 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005074 * If you already know the uid of the target, you can supply it in
5075 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005076 */
5077 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005078 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5080 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5081 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005082 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 }
5084
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005085 if (targetPkg != null) {
5086 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5087 "Checking grant " + targetPkg + " permission to " + uri);
5088 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005089
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005090 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091
5092 // If this is not a content: uri, we can't do anything with it.
5093 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005094 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005095 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005096 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 }
5098
5099 String name = uri.getAuthority();
5100 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005101 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005102 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103 if (cpr != null) {
5104 pi = cpr.info;
5105 } else {
5106 try {
5107 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005108 PackageManager.GET_URI_PERMISSION_PATTERNS,
5109 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 } catch (RemoteException ex) {
5111 }
5112 }
5113 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005114 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005115 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 }
5117
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005118 int targetUid = lastTargetUid;
5119 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005120 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005121 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005122 if (targetUid < 0) {
5123 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5124 "Can't grant URI permission no uid for: " + targetPkg);
5125 return -1;
5126 }
5127 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005128 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 }
5131
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005132 if (targetUid >= 0) {
5133 // First... does the target actually need this permission?
5134 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5135 // No need to grant the target this permission.
5136 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5137 "Target " + targetPkg + " already has full permission to " + uri);
5138 return -1;
5139 }
5140 } else {
5141 // First... there is no target package, so can anyone access it?
5142 boolean allowed = pi.exported;
5143 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5144 if (pi.readPermission != null) {
5145 allowed = false;
5146 }
5147 }
5148 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5149 if (pi.writePermission != null) {
5150 allowed = false;
5151 }
5152 }
5153 if (allowed) {
5154 return -1;
5155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 }
5157
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005158 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 if (!pi.grantUriPermissions) {
5160 throw new SecurityException("Provider " + pi.packageName
5161 + "/" + pi.name
5162 + " does not allow granting of Uri permissions (uri "
5163 + uri + ")");
5164 }
5165 if (pi.uriPermissionPatterns != null) {
5166 final int N = pi.uriPermissionPatterns.length;
5167 boolean allowed = false;
5168 for (int i=0; i<N; i++) {
5169 if (pi.uriPermissionPatterns[i] != null
5170 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5171 allowed = true;
5172 break;
5173 }
5174 }
5175 if (!allowed) {
5176 throw new SecurityException("Provider " + pi.packageName
5177 + "/" + pi.name
5178 + " does not allow granting of permission to path of Uri "
5179 + uri);
5180 }
5181 }
5182
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005183 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005185 if (callingUid != Process.myUid()) {
5186 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5187 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5188 throw new SecurityException("Uid " + callingUid
5189 + " does not have permission to uri " + uri);
5190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 }
5192 }
5193
Dianne Hackborn39792d22010-08-19 18:01:52 -07005194 return targetUid;
5195 }
5196
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005197 public int checkGrantUriPermission(int callingUid, String targetPkg,
5198 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005199 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005200 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005201 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005202 }
5203 }
5204
Dianne Hackborn39792d22010-08-19 18:01:52 -07005205 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5206 Uri uri, int modeFlags, UriPermissionOwner owner) {
5207 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5208 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5209 if (modeFlags == 0) {
5210 return;
5211 }
5212
5213 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005214 // to the uri, and the target doesn't. Let's now give this to
5215 // the target.
5216
Joe Onorato8a9b2202010-02-26 18:56:32 -08005217 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005218 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 HashMap<Uri, UriPermission> targetUris
5221 = mGrantedUriPermissions.get(targetUid);
5222 if (targetUris == null) {
5223 targetUris = new HashMap<Uri, UriPermission>();
5224 mGrantedUriPermissions.put(targetUid, targetUris);
5225 }
5226
5227 UriPermission perm = targetUris.get(uri);
5228 if (perm == null) {
5229 perm = new UriPermission(targetUid, uri);
5230 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005231 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005234 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005236 } else {
5237 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5238 perm.readOwners.add(owner);
5239 owner.addReadPermission(perm);
5240 }
5241 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5242 perm.writeOwners.add(owner);
5243 owner.addWritePermission(perm);
5244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 }
5246 }
5247
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005248 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5249 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005250 if (targetPkg == null) {
5251 throw new NullPointerException("targetPkg");
5252 }
5253
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005254 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005255 if (targetUid < 0) {
5256 return;
5257 }
5258
5259 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5260 }
5261
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005262 static class NeededUriGrants extends ArrayList<Uri> {
5263 final String targetPkg;
5264 final int targetUid;
5265 final int flags;
5266
5267 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5268 targetPkg = _targetPkg;
5269 targetUid = _targetUid;
5270 flags = _flags;
5271 }
5272 }
5273
Dianne Hackborn39792d22010-08-19 18:01:52 -07005274 /**
5275 * Like checkGrantUriPermissionLocked, but takes an Intent.
5276 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005277 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5278 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005279 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005280 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5281 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005282 + " from " + intent + "; flags=0x"
5283 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5284
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005285 if (targetPkg == null) {
5286 throw new NullPointerException("targetPkg");
5287 }
5288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005290 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 }
5292 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005293 ClipData clip = intent.getClipData();
5294 if (data == null && clip == null) {
5295 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005296 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005297 if (data != null) {
5298 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5299 mode, needed != null ? needed.targetUid : -1);
5300 if (target > 0) {
5301 if (needed == null) {
5302 needed = new NeededUriGrants(targetPkg, target, mode);
5303 }
5304 needed.add(data);
5305 }
5306 }
5307 if (clip != null) {
5308 for (int i=0; i<clip.getItemCount(); i++) {
5309 Uri uri = clip.getItemAt(i).getUri();
5310 if (uri != null) {
5311 int target = -1;
5312 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5313 mode, needed != null ? needed.targetUid : -1);
5314 if (target > 0) {
5315 if (needed == null) {
5316 needed = new NeededUriGrants(targetPkg, target, mode);
5317 }
5318 needed.add(uri);
5319 }
5320 } else {
5321 Intent clipIntent = clip.getItemAt(i).getIntent();
5322 if (clipIntent != null) {
5323 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5324 callingUid, targetPkg, clipIntent, mode, needed);
5325 if (newNeeded != null) {
5326 needed = newNeeded;
5327 }
5328 }
5329 }
5330 }
5331 }
5332
5333 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005334 }
5335
5336 /**
5337 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5338 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005339 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5340 UriPermissionOwner owner) {
5341 if (needed != null) {
5342 for (int i=0; i<needed.size(); i++) {
5343 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5344 needed.get(i), needed.flags, owner);
5345 }
5346 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005347 }
5348
5349 void grantUriPermissionFromIntentLocked(int callingUid,
5350 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005351 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005352 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005353 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 return;
5355 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005356
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005357 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 }
5359
5360 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5361 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005362 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 synchronized(this) {
5364 final ProcessRecord r = getRecordForAppLocked(caller);
5365 if (r == null) {
5366 throw new SecurityException("Unable to find app for caller "
5367 + caller
5368 + " when granting permission to uri " + uri);
5369 }
5370 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005371 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 }
5373 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005374 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005375 }
5376
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005377 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 null);
5379 }
5380 }
5381
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005382 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5384 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5385 HashMap<Uri, UriPermission> perms
5386 = mGrantedUriPermissions.get(perm.uid);
5387 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005388 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005389 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 perms.remove(perm.uri);
5391 if (perms.size() == 0) {
5392 mGrantedUriPermissions.remove(perm.uid);
5393 }
5394 }
5395 }
5396 }
5397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5399 int modeFlags) {
5400 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5401 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5402 if (modeFlags == 0) {
5403 return;
5404 }
5405
Joe Onorato8a9b2202010-02-26 18:56:32 -08005406 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005407 "Revoking all granted permissions to " + uri);
5408
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005409 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410
5411 final String authority = uri.getAuthority();
5412 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005413 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005414 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 if (cpr != null) {
5416 pi = cpr.info;
5417 } else {
5418 try {
5419 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005420 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 } catch (RemoteException ex) {
5422 }
5423 }
5424 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005425 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 return;
5427 }
5428
5429 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005430 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 // Right now, if you are not the original owner of the permission,
5432 // you are not allowed to revoke it.
5433 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5434 throw new SecurityException("Uid " + callingUid
5435 + " does not have permission to uri " + uri);
5436 //}
5437 }
5438
5439 // Go through all of the permissions and remove any that match.
5440 final List<String> SEGMENTS = uri.getPathSegments();
5441 if (SEGMENTS != null) {
5442 final int NS = SEGMENTS.size();
5443 int N = mGrantedUriPermissions.size();
5444 for (int i=0; i<N; i++) {
5445 HashMap<Uri, UriPermission> perms
5446 = mGrantedUriPermissions.valueAt(i);
5447 Iterator<UriPermission> it = perms.values().iterator();
5448 toploop:
5449 while (it.hasNext()) {
5450 UriPermission perm = it.next();
5451 Uri targetUri = perm.uri;
5452 if (!authority.equals(targetUri.getAuthority())) {
5453 continue;
5454 }
5455 List<String> targetSegments = targetUri.getPathSegments();
5456 if (targetSegments == null) {
5457 continue;
5458 }
5459 if (targetSegments.size() < NS) {
5460 continue;
5461 }
5462 for (int j=0; j<NS; j++) {
5463 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5464 continue toploop;
5465 }
5466 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005467 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005468 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 perm.clearModes(modeFlags);
5470 if (perm.modeFlags == 0) {
5471 it.remove();
5472 }
5473 }
5474 if (perms.size() == 0) {
5475 mGrantedUriPermissions.remove(
5476 mGrantedUriPermissions.keyAt(i));
5477 N--;
5478 i--;
5479 }
5480 }
5481 }
5482 }
5483
5484 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5485 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005486 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 synchronized(this) {
5488 final ProcessRecord r = getRecordForAppLocked(caller);
5489 if (r == null) {
5490 throw new SecurityException("Unable to find app for caller "
5491 + caller
5492 + " when revoking permission to uri " + uri);
5493 }
5494 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005495 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 return;
5497 }
5498
5499 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5500 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5501 if (modeFlags == 0) {
5502 return;
5503 }
5504
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005505 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506
5507 final String authority = uri.getAuthority();
5508 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005509 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 if (cpr != null) {
5511 pi = cpr.info;
5512 } else {
5513 try {
5514 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005515 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 } catch (RemoteException ex) {
5517 }
5518 }
5519 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005520 Slog.w(TAG, "No content provider found for permission revoke: "
5521 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 return;
5523 }
5524
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005525 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 }
5527 }
5528
Dianne Hackborn7e269642010-08-25 19:50:20 -07005529 @Override
5530 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005531 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005532 synchronized(this) {
5533 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5534 return owner.getExternalTokenLocked();
5535 }
5536 }
5537
5538 @Override
5539 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5540 Uri uri, int modeFlags) {
5541 synchronized(this) {
5542 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5543 if (owner == null) {
5544 throw new IllegalArgumentException("Unknown owner: " + token);
5545 }
5546 if (fromUid != Binder.getCallingUid()) {
5547 if (Binder.getCallingUid() != Process.myUid()) {
5548 // Only system code can grant URI permissions on behalf
5549 // of other users.
5550 throw new SecurityException("nice try");
5551 }
5552 }
5553 if (targetPkg == null) {
5554 throw new IllegalArgumentException("null target");
5555 }
5556 if (uri == null) {
5557 throw new IllegalArgumentException("null uri");
5558 }
5559
5560 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5561 }
5562 }
5563
5564 @Override
5565 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5566 synchronized(this) {
5567 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5568 if (owner == null) {
5569 throw new IllegalArgumentException("Unknown owner: " + token);
5570 }
5571
5572 if (uri == null) {
5573 owner.removeUriPermissionsLocked(mode);
5574 } else {
5575 owner.removeUriPermissionLocked(uri, mode);
5576 }
5577 }
5578 }
5579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5581 synchronized (this) {
5582 ProcessRecord app =
5583 who != null ? getRecordForAppLocked(who) : null;
5584 if (app == null) return;
5585
5586 Message msg = Message.obtain();
5587 msg.what = WAIT_FOR_DEBUGGER_MSG;
5588 msg.obj = app;
5589 msg.arg1 = waiting ? 1 : 0;
5590 mHandler.sendMessage(msg);
5591 }
5592 }
5593
5594 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005595 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5596 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005598 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005599 outInfo.threshold = homeAppMem;
5600 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5601 outInfo.hiddenAppThreshold = hiddenAppMem;
5602 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005603 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005604 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5605 ProcessList.VISIBLE_APP_ADJ);
5606 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5607 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 }
5609
5610 // =========================================================
5611 // TASK MANAGEMENT
5612 // =========================================================
5613
5614 public List getTasks(int maxNum, int flags,
5615 IThumbnailReceiver receiver) {
5616 ArrayList list = new ArrayList();
5617
5618 PendingThumbnailsRecord pending = null;
5619 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005620 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621
5622 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005623 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5625 + ", receiver=" + receiver);
5626
5627 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5628 != PackageManager.PERMISSION_GRANTED) {
5629 if (receiver != null) {
5630 // If the caller wants to wait for pending thumbnails,
5631 // it ain't gonna get them.
5632 try {
5633 receiver.finished();
5634 } catch (RemoteException ex) {
5635 }
5636 }
5637 String msg = "Permission Denial: getTasks() from pid="
5638 + Binder.getCallingPid()
5639 + ", uid=" + Binder.getCallingUid()
5640 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005641 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 throw new SecurityException(msg);
5643 }
5644
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005645 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005646 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005647 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005648 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 TaskRecord curTask = null;
5650 int numActivities = 0;
5651 int numRunning = 0;
5652 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005653 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005655 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656
5657 // Initialize state for next task if needed.
5658 if (top == null ||
5659 (top.state == ActivityState.INITIALIZING
5660 && top.task == r.task)) {
5661 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 curTask = r.task;
5663 numActivities = numRunning = 0;
5664 }
5665
5666 // Add 'r' into the current task.
5667 numActivities++;
5668 if (r.app != null && r.app.thread != null) {
5669 numRunning++;
5670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671
Joe Onorato8a9b2202010-02-26 18:56:32 -08005672 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 TAG, r.intent.getComponent().flattenToShortString()
5674 + ": task=" + r.task);
5675
5676 // If the next one is a different task, generate a new
5677 // TaskInfo entry for what we have.
5678 if (next == null || next.task != curTask) {
5679 ActivityManager.RunningTaskInfo ci
5680 = new ActivityManager.RunningTaskInfo();
5681 ci.id = curTask.taskId;
5682 ci.baseActivity = r.intent.getComponent();
5683 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005684 if (top.thumbHolder != null) {
5685 ci.description = top.thumbHolder.lastDescription;
5686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 ci.numActivities = numActivities;
5688 ci.numRunning = numRunning;
5689 //System.out.println(
5690 // "#" + maxNum + ": " + " descr=" + ci.description);
5691 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005692 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 TAG, "State=" + top.state + "Idle=" + top.idle
5694 + " app=" + top.app
5695 + " thr=" + (top.app != null ? top.app.thread : null));
5696 if (top.state == ActivityState.RESUMED
5697 || top.state == ActivityState.PAUSING) {
5698 if (top.idle && top.app != null
5699 && top.app.thread != null) {
5700 topRecord = top;
5701 topThumbnail = top.app.thread;
5702 } else {
5703 top.thumbnailNeeded = true;
5704 }
5705 }
5706 if (pending == null) {
5707 pending = new PendingThumbnailsRecord(receiver);
5708 }
5709 pending.pendingRecords.add(top);
5710 }
5711 list.add(ci);
5712 maxNum--;
5713 top = null;
5714 }
5715 }
5716
5717 if (pending != null) {
5718 mPendingThumbnails.add(pending);
5719 }
5720 }
5721
Joe Onorato8a9b2202010-02-26 18:56:32 -08005722 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723
5724 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005725 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005727 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005729 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005730 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 }
5732 }
5733
5734 if (pending == null && receiver != null) {
5735 // In this case all thumbnails were available and the client
5736 // is being asked to be told when the remaining ones come in...
5737 // which is unusually, since the top-most currently running
5738 // activity should never have a canned thumbnail! Oh well.
5739 try {
5740 receiver.finished();
5741 } catch (RemoteException ex) {
5742 }
5743 }
5744
5745 return list;
5746 }
5747
5748 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005749 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005750 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5751 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 synchronized (this) {
5754 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5755 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005756 final boolean detailed = checkCallingPermission(
5757 android.Manifest.permission.GET_DETAILED_TASKS)
5758 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005760 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 final int N = mRecentTasks.size();
5763 ArrayList<ActivityManager.RecentTaskInfo> res
5764 = new ArrayList<ActivityManager.RecentTaskInfo>(
5765 maxNum < N ? maxNum : N);
5766 for (int i=0; i<N && maxNum > 0; i++) {
5767 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005768 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005769 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005770 // Return the entry if desired by the caller. We always return
5771 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005772 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005773 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5774 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005775
Dianne Hackborn905577f2011-09-07 18:31:28 -07005776 if (i == 0
5777 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 || (tr.intent == null)
5779 || ((tr.intent.getFlags()
5780 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5781 ActivityManager.RecentTaskInfo rti
5782 = new ActivityManager.RecentTaskInfo();
5783 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005784 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 rti.baseIntent = new Intent(
5786 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005787 if (!detailed) {
5788 rti.baseIntent.replaceExtras((Bundle)null);
5789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005791 rti.description = tr.lastDescription;
5792
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005793 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5794 // Check whether this activity is currently available.
5795 try {
5796 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005797 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005798 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005799 continue;
5800 }
5801 } else if (rti.baseIntent != null) {
5802 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005803 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005804 continue;
5805 }
5806 }
5807 } catch (RemoteException e) {
5808 // Will never happen.
5809 }
5810 }
5811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 res.add(rti);
5813 maxNum--;
5814 }
5815 }
5816 return res;
5817 }
5818 }
5819
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005820 private TaskRecord taskForIdLocked(int id) {
5821 final int N = mRecentTasks.size();
5822 for (int i=0; i<N; i++) {
5823 TaskRecord tr = mRecentTasks.get(i);
5824 if (tr.taskId == id) {
5825 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005826 }
5827 }
5828 return null;
5829 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005830
5831 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5832 synchronized (this) {
5833 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5834 "getTaskThumbnails()");
5835 TaskRecord tr = taskForIdLocked(id);
5836 if (tr != null) {
5837 return mMainStack.getTaskThumbnailsLocked(tr);
5838 }
5839 }
5840 return null;
5841 }
5842
Dianne Hackborn15491c62012-09-19 10:59:14 -07005843 public Bitmap getTaskTopThumbnail(int id) {
5844 synchronized (this) {
5845 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5846 "getTaskTopThumbnail()");
5847 TaskRecord tr = taskForIdLocked(id);
5848 if (tr != null) {
5849 return mMainStack.getTaskTopThumbnailLocked(tr);
5850 }
5851 }
5852 return null;
5853 }
5854
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005855 public boolean removeSubTask(int taskId, int subTaskIndex) {
5856 synchronized (this) {
5857 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5858 "removeSubTask()");
5859 long ident = Binder.clearCallingIdentity();
5860 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005861 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5862 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005863 } finally {
5864 Binder.restoreCallingIdentity(ident);
5865 }
5866 }
5867 }
5868
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005869 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5870 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005871 Intent baseIntent = new Intent(
5872 tr.intent != null ? tr.intent : tr.affinityIntent);
5873 ComponentName component = baseIntent.getComponent();
5874 if (component == null) {
5875 Slog.w(TAG, "Now component for base intent of task: " + tr);
5876 return;
5877 }
5878
5879 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005880 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005881
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005882 if (killProcesses) {
5883 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005884 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005885 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005886 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5887 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5888 for (int i=0; i<uids.size(); i++) {
5889 ProcessRecord proc = uids.valueAt(i);
5890 if (proc.userId != tr.userId) {
5891 continue;
5892 }
5893 if (!proc.pkgList.contains(pkg)) {
5894 continue;
5895 }
5896 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005897 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005898 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005899
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005900 // Kill the running processes.
5901 for (int i=0; i<procs.size(); i++) {
5902 ProcessRecord pr = procs.get(i);
5903 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5904 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005905 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005906 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005907 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005908 Process.killProcessQuiet(pr.pid);
5909 } else {
5910 pr.waitingToKill = "remove task";
5911 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005912 }
5913 }
5914 }
5915
5916 public boolean removeTask(int taskId, int flags) {
5917 synchronized (this) {
5918 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5919 "removeTask()");
5920 long ident = Binder.clearCallingIdentity();
5921 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005922 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5923 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005924 if (r != null) {
5925 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005926 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005927 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005928 } else {
5929 TaskRecord tr = null;
5930 int i=0;
5931 while (i < mRecentTasks.size()) {
5932 TaskRecord t = mRecentTasks.get(i);
5933 if (t.taskId == taskId) {
5934 tr = t;
5935 break;
5936 }
5937 i++;
5938 }
5939 if (tr != null) {
5940 if (tr.numActivities <= 0) {
5941 // Caller is just removing a recent task that is
5942 // not actively running. That is easy!
5943 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005944 cleanUpRemovedTaskLocked(tr, flags);
5945 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005946 } else {
5947 Slog.w(TAG, "removeTask: task " + taskId
5948 + " does not have activities to remove, "
5949 + " but numActivities=" + tr.numActivities
5950 + ": " + tr);
5951 }
5952 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005953 }
5954 } finally {
5955 Binder.restoreCallingIdentity(ident);
5956 }
5957 }
5958 return false;
5959 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5962 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005963 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 TaskRecord jt = startTask;
5965
5966 // First look backwards
5967 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005968 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 if (r.task != jt) {
5970 jt = r.task;
5971 if (affinity.equals(jt.affinity)) {
5972 return j;
5973 }
5974 }
5975 }
5976
5977 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005978 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 jt = startTask;
5980 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005981 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 if (r.task != jt) {
5983 if (affinity.equals(jt.affinity)) {
5984 return j;
5985 }
5986 jt = r.task;
5987 }
5988 }
5989
5990 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005991 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 return N-1;
5993 }
5994
5995 return -1;
5996 }
5997
5998 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005999 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006001 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6003 "moveTaskToFront()");
6004
6005 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006006 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6007 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006008 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006009 return;
6010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 final long origId = Binder.clearCallingIdentity();
6012 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006013 TaskRecord tr = taskForIdLocked(task);
6014 if (tr != null) {
6015 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6016 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006018 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6019 // Caller wants the home activity moved with it. To accomplish this,
6020 // we'll just move the home task to the top first.
6021 mMainStack.moveHomeToFrontLocked();
6022 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006023 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006024 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006026 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6027 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006029 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6030 mMainStack.mUserLeaving = true;
6031 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006032 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6033 // Caller wants the home activity moved with it. To accomplish this,
6034 // we'll just move the home task to the top first.
6035 mMainStack.moveHomeToFrontLocked();
6036 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006037 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 return;
6039 }
6040 }
6041 } finally {
6042 Binder.restoreCallingIdentity(origId);
6043 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006044 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 }
6046 }
6047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 public void moveTaskToBack(int task) {
6049 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6050 "moveTaskToBack()");
6051
6052 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006053 if (mMainStack.mResumedActivity != null
6054 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006055 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6056 Binder.getCallingUid(), "Task to back")) {
6057 return;
6058 }
6059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006061 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 Binder.restoreCallingIdentity(origId);
6063 }
6064 }
6065
6066 /**
6067 * Moves an activity, and all of the other activities within the same task, to the bottom
6068 * of the history stack. The activity's order within the task is unchanged.
6069 *
6070 * @param token A reference to the activity we wish to move
6071 * @param nonRoot If false then this only works if the activity is the root
6072 * of a task; if true it will work for any activity in a task.
6073 * @return Returns true if the move completed, false if not.
6074 */
6075 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006076 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 synchronized(this) {
6078 final long origId = Binder.clearCallingIdentity();
6079 int taskId = getTaskForActivityLocked(token, !nonRoot);
6080 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006081 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 }
6083 Binder.restoreCallingIdentity(origId);
6084 }
6085 return false;
6086 }
6087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 public void moveTaskBackwards(int task) {
6089 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6090 "moveTaskBackwards()");
6091
6092 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006093 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6094 Binder.getCallingUid(), "Task backwards")) {
6095 return;
6096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 final long origId = Binder.clearCallingIdentity();
6098 moveTaskBackwardsLocked(task);
6099 Binder.restoreCallingIdentity(origId);
6100 }
6101 }
6102
6103 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006104 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 }
6106
6107 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6108 synchronized(this) {
6109 return getTaskForActivityLocked(token, onlyRoot);
6110 }
6111 }
6112
6113 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006114 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 TaskRecord lastTask = null;
6116 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006117 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006118 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 if (!onlyRoot || lastTask != r.task) {
6120 return r.task.taskId;
6121 }
6122 return -1;
6123 }
6124 lastTask = r.task;
6125 }
6126
6127 return -1;
6128 }
6129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 // =========================================================
6131 // THUMBNAILS
6132 // =========================================================
6133
6134 public void reportThumbnail(IBinder token,
6135 Bitmap thumbnail, CharSequence description) {
6136 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6137 final long origId = Binder.clearCallingIdentity();
6138 sendPendingThumbnail(null, token, thumbnail, description, true);
6139 Binder.restoreCallingIdentity(origId);
6140 }
6141
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006142 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 Bitmap thumbnail, CharSequence description, boolean always) {
6144 TaskRecord task = null;
6145 ArrayList receivers = null;
6146
6147 //System.out.println("Send pending thumbnail: " + r);
6148
6149 synchronized(this) {
6150 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006151 r = mMainStack.isInStackLocked(token);
6152 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 return;
6154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006156 if (thumbnail == null && r.thumbHolder != null) {
6157 thumbnail = r.thumbHolder.lastThumbnail;
6158 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 }
6160 if (thumbnail == null && !always) {
6161 // If there is no thumbnail, and this entry is not actually
6162 // going away, then abort for now and pick up the next
6163 // thumbnail we get.
6164 return;
6165 }
6166 task = r.task;
6167
6168 int N = mPendingThumbnails.size();
6169 int i=0;
6170 while (i<N) {
6171 PendingThumbnailsRecord pr =
6172 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6173 //System.out.println("Looking in " + pr.pendingRecords);
6174 if (pr.pendingRecords.remove(r)) {
6175 if (receivers == null) {
6176 receivers = new ArrayList();
6177 }
6178 receivers.add(pr);
6179 if (pr.pendingRecords.size() == 0) {
6180 pr.finished = true;
6181 mPendingThumbnails.remove(i);
6182 N--;
6183 continue;
6184 }
6185 }
6186 i++;
6187 }
6188 }
6189
6190 if (receivers != null) {
6191 final int N = receivers.size();
6192 for (int i=0; i<N; i++) {
6193 try {
6194 PendingThumbnailsRecord pr =
6195 (PendingThumbnailsRecord)receivers.get(i);
6196 pr.receiver.newThumbnail(
6197 task != null ? task.taskId : -1, thumbnail, description);
6198 if (pr.finished) {
6199 pr.receiver.finished();
6200 }
6201 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006202 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 }
6204 }
6205 }
6206 }
6207
6208 // =========================================================
6209 // CONTENT PROVIDERS
6210 // =========================================================
6211
Jeff Brown10e89712011-07-08 18:52:57 -07006212 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6213 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006215 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006216 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006217 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 } catch (RemoteException ex) {
6219 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006220 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006221 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6222 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006224 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 for (int i=0; i<N; i++) {
6226 ProviderInfo cpi =
6227 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006228 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6229 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006230 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006231 // This is a singleton provider, but a user besides the
6232 // default user is asking to initialize a process it runs
6233 // in... well, no, it doesn't actually run in this process,
6234 // it runs in the process of the default user. Get rid of it.
6235 providers.remove(i);
6236 N--;
6237 continue;
6238 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006239
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006240 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006241 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006243 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006244 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006246 if (DEBUG_MU)
6247 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 app.pubProviders.put(cpi.name, cpr);
6249 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006250 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 }
6252 }
6253 return providers;
6254 }
6255
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006256 /**
6257 * Check if {@link ProcessRecord} has a possible chance at accessing the
6258 * given {@link ProviderInfo}. Final permission checking is always done
6259 * in {@link ContentProvider}.
6260 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006262 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006264 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006266 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006267 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 return null;
6269 }
6270 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006271 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 == PackageManager.PERMISSION_GRANTED) {
6273 return null;
6274 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006275
6276 PathPermission[] pps = cpi.pathPermissions;
6277 if (pps != null) {
6278 int i = pps.length;
6279 while (i > 0) {
6280 i--;
6281 PathPermission pp = pps[i];
6282 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006283 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006284 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006285 return null;
6286 }
6287 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006288 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006289 == PackageManager.PERMISSION_GRANTED) {
6290 return null;
6291 }
6292 }
6293 }
6294
Dianne Hackbornb424b632010-08-18 15:59:05 -07006295 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6296 if (perms != null) {
6297 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6298 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6299 return null;
6300 }
6301 }
6302 }
6303
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006304 String msg;
6305 if (!cpi.exported) {
6306 msg = "Permission Denial: opening provider " + cpi.name
6307 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6308 + ", uid=" + callingUid + ") that is not exported from uid "
6309 + cpi.applicationInfo.uid;
6310 } else {
6311 msg = "Permission Denial: opening provider " + cpi.name
6312 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6313 + ", uid=" + callingUid + ") requires "
6314 + cpi.readPermission + " or " + cpi.writePermission;
6315 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006316 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 return msg;
6318 }
6319
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006320 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6321 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006322 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006323 for (int i=0; i<r.conProviders.size(); i++) {
6324 ContentProviderConnection conn = r.conProviders.get(i);
6325 if (conn.provider == cpr) {
6326 if (DEBUG_PROVIDER) Slog.v(TAG,
6327 "Adding provider requested by "
6328 + r.processName + " from process "
6329 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6330 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6331 if (stable) {
6332 conn.stableCount++;
6333 conn.numStableIncs++;
6334 } else {
6335 conn.unstableCount++;
6336 conn.numUnstableIncs++;
6337 }
6338 return conn;
6339 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006340 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006341 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6342 if (stable) {
6343 conn.stableCount = 1;
6344 conn.numStableIncs = 1;
6345 } else {
6346 conn.unstableCount = 1;
6347 conn.numUnstableIncs = 1;
6348 }
6349 cpr.connections.add(conn);
6350 r.conProviders.add(conn);
6351 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006352 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006353 cpr.addExternalProcessHandleLocked(externalProcessToken);
6354 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006355 }
6356
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006357 boolean decProviderCountLocked(ContentProviderConnection conn,
6358 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6359 if (conn != null) {
6360 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006361 if (DEBUG_PROVIDER) Slog.v(TAG,
6362 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006363 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006364 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006365 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6366 if (stable) {
6367 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006368 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006369 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006370 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006371 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6372 cpr.connections.remove(conn);
6373 conn.client.conProviders.remove(conn);
6374 return true;
6375 }
6376 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006377 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006378 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006379 return false;
6380 }
6381
Amith Yamasani742a6712011-05-04 14:49:28 -07006382 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006383 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006385 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 ProviderInfo cpi = null;
6387
6388 synchronized(this) {
6389 ProcessRecord r = null;
6390 if (caller != null) {
6391 r = getRecordForAppLocked(caller);
6392 if (r == null) {
6393 throw new SecurityException(
6394 "Unable to find app for caller " + caller
6395 + " (pid=" + Binder.getCallingPid()
6396 + ") when getting content provider " + name);
6397 }
6398 }
6399
6400 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006401 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006402 boolean providerRunning = cpr != null;
6403 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006405 String msg;
6406 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6407 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 }
6409
6410 if (r != null && cpr.canRunHere(r)) {
6411 // This provider has been published or is in the process
6412 // of being published... but it is also allowed to run
6413 // in the caller's process, so don't make a connection
6414 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006415 ContentProviderHolder holder = cpr.newHolder(null);
6416 // don't give caller the provider object, it needs
6417 // to make its own.
6418 holder.provider = null;
6419 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 }
6421
6422 final long origId = Binder.clearCallingIdentity();
6423
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006424 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006426 conn = incProviderCountLocked(r, cpr, token, stable);
6427 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006428 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006429 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006430 // make sure to count it as being accessed and thus
6431 // back up on the LRU list. This is good because
6432 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006433 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006434 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006435 }
6436
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006437 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006438 if (false) {
6439 if (cpr.name.flattenToShortString().equals(
6440 "com.android.providers.calendar/.CalendarProvider2")) {
6441 Slog.v(TAG, "****************** KILLING "
6442 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006443 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006444 }
6445 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006446 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006447 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6448 // NOTE: there is still a race here where a signal could be
6449 // pending on the process even though we managed to update its
6450 // adj level. Not sure what to do about this, but at least
6451 // the race is now smaller.
6452 if (!success) {
6453 // Uh oh... it looks like the provider's process
6454 // has been killed on us. We need to wait for a new
6455 // process to be started, and make sure its death
6456 // doesn't kill our process.
6457 Slog.i(TAG,
6458 "Existing provider " + cpr.name.flattenToShortString()
6459 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006460 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006461 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006462 if (!lastRef) {
6463 // This wasn't the last ref our process had on
6464 // the provider... we have now been killed, bail.
6465 return null;
6466 }
6467 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006468 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 }
6471
6472 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006475 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006476 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006478 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006479 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006480 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 } catch (RemoteException ex) {
6482 }
6483 if (cpi == null) {
6484 return null;
6485 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006486 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6487 cpi.name, cpi.flags);
6488 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006489 userId = 0;
6490 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006491 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006492
Dianne Hackbornb424b632010-08-18 15:59:05 -07006493 String msg;
6494 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6495 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
6497
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006498 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006499 && !cpi.processName.equals("system")) {
6500 // If this content provider does not run in the system
6501 // process, and the system is not yet ready to run other
6502 // processes, then fail fast instead of hanging.
6503 throw new IllegalArgumentException(
6504 "Attempt to launch content provider before system ready");
6505 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006506
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006507 // Make sure that the user who owns this provider is started. If not,
6508 // we don't want to allow it to run.
6509 if (mStartedUsers.get(userId) == null) {
6510 Slog.w(TAG, "Unable to launch app "
6511 + cpi.applicationInfo.packageName + "/"
6512 + cpi.applicationInfo.uid + " for provider "
6513 + name + ": user " + userId + " is stopped");
6514 return null;
6515 }
6516
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006517 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006518 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 final boolean firstClass = cpr == null;
6520 if (firstClass) {
6521 try {
6522 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006523 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 getApplicationInfo(
6525 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006526 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006528 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 + cpi.name);
6530 return null;
6531 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006532 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006533 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 } catch (RemoteException ex) {
6535 // pm is in same process, this will never happen.
6536 }
6537 }
6538
6539 if (r != null && cpr.canRunHere(r)) {
6540 // If this is a multiprocess provider, then just return its
6541 // info and allow the caller to instantiate it. Only do
6542 // this if the provider is the same user as the caller's
6543 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006544 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 }
6546
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006547 if (DEBUG_PROVIDER) {
6548 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006549 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006550 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 }
6552
6553 // This is single process, and our app is now connecting to it.
6554 // See if we are already in the process of launching this
6555 // provider.
6556 final int N = mLaunchingProviders.size();
6557 int i;
6558 for (i=0; i<N; i++) {
6559 if (mLaunchingProviders.get(i) == cpr) {
6560 break;
6561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 }
6563
6564 // If the provider is not already being launched, then get it
6565 // started.
6566 if (i >= N) {
6567 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006568
6569 try {
6570 // Content provider is now in use, its package can't be stopped.
6571 try {
6572 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006573 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006574 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006575 } catch (IllegalArgumentException e) {
6576 Slog.w(TAG, "Failed trying to unstop package "
6577 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006578 }
6579
6580 ProcessRecord proc = startProcessLocked(cpi.processName,
6581 cpr.appInfo, false, 0, "content provider",
6582 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006583 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006584 if (proc == null) {
6585 Slog.w(TAG, "Unable to launch app "
6586 + cpi.applicationInfo.packageName + "/"
6587 + cpi.applicationInfo.uid + " for provider "
6588 + name + ": process is bad");
6589 return null;
6590 }
6591 cpr.launchingApp = proc;
6592 mLaunchingProviders.add(cpr);
6593 } finally {
6594 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 }
6597
6598 // Make sure the provider is published (the same provider class
6599 // may be published under multiple names).
6600 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006601 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006603
Amith Yamasani742a6712011-05-04 14:49:28 -07006604 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006605 conn = incProviderCountLocked(r, cpr, token, stable);
6606 if (conn != null) {
6607 conn.waiting = true;
6608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 }
6610 }
6611
6612 // Wait for the provider to be published...
6613 synchronized (cpr) {
6614 while (cpr.provider == null) {
6615 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006616 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 + cpi.applicationInfo.packageName + "/"
6618 + cpi.applicationInfo.uid + " for provider "
6619 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006620 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006621 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 cpi.applicationInfo.packageName,
6623 cpi.applicationInfo.uid, name);
6624 return null;
6625 }
6626 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006627 if (DEBUG_MU) {
6628 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6629 + cpr.launchingApp);
6630 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006631 if (conn != null) {
6632 conn.waiting = true;
6633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 cpr.wait();
6635 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006636 } finally {
6637 if (conn != null) {
6638 conn.waiting = false;
6639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 }
6641 }
6642 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006643 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 }
6645
6646 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006647 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006648 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 if (caller == null) {
6650 String msg = "null IApplicationThread when getting content provider "
6651 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006652 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 throw new SecurityException(msg);
6654 }
6655
Dianne Hackborn139748f2012-09-24 11:36:57 -07006656 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006657 false, true, "getContentProvider", null);
6658 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 }
6660
Jeff Sharkey6d515712012-09-20 16:06:08 -07006661 public ContentProviderHolder getContentProviderExternal(
6662 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006663 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6664 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006665 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006666 false, true, "getContentProvider", null);
6667 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006668 }
6669
Dianne Hackborn41203752012-08-31 14:05:51 -07006670 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6671 IBinder token, int userId) {
6672 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 }
6674
6675 /**
6676 * Drop a content provider from a ProcessRecord's bookkeeping
6677 * @param cpr
6678 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006679 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006680 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006682 ContentProviderConnection conn;
6683 try {
6684 conn = (ContentProviderConnection)connection;
6685 } catch (ClassCastException e) {
6686 String msg ="removeContentProvider: " + connection
6687 + " not a ContentProviderConnection";
6688 Slog.w(TAG, msg);
6689 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006691 if (conn == null) {
6692 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006694 if (decProviderCountLocked(conn, null, null, stable)) {
6695 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 }
6698 }
6699
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006700 public void removeContentProviderExternal(String name, IBinder token) {
6701 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6702 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006703 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006704 }
6705
Dianne Hackborn41203752012-08-31 14:05:51 -07006706 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006708 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 if(cpr == null) {
6710 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006711 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 return;
6713 }
6714
6715 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006716 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006717 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006718 if (localCpr.hasExternalProcessHandles()) {
6719 if (localCpr.removeExternalProcessHandleLocked(token)) {
6720 updateOomAdjLocked();
6721 } else {
6722 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6723 + " with no external reference for token: "
6724 + token + ".");
6725 }
6726 } else {
6727 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6728 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
6731 }
6732
6733 public final void publishContentProviders(IApplicationThread caller,
6734 List<ContentProviderHolder> providers) {
6735 if (providers == null) {
6736 return;
6737 }
6738
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006739 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006740 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006742 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006743 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006744 if (r == null) {
6745 throw new SecurityException(
6746 "Unable to find app for caller " + caller
6747 + " (pid=" + Binder.getCallingPid()
6748 + ") when publishing content providers");
6749 }
6750
6751 final long origId = Binder.clearCallingIdentity();
6752
6753 final int N = providers.size();
6754 for (int i=0; i<N; i++) {
6755 ContentProviderHolder src = providers.get(i);
6756 if (src == null || src.info == null || src.provider == null) {
6757 continue;
6758 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006759 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006760 if (DEBUG_MU)
6761 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006763 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006764 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 String names[] = dst.info.authority.split(";");
6766 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006767 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 }
6769
6770 int NL = mLaunchingProviders.size();
6771 int j;
6772 for (j=0; j<NL; j++) {
6773 if (mLaunchingProviders.get(j) == dst) {
6774 mLaunchingProviders.remove(j);
6775 j--;
6776 NL--;
6777 }
6778 }
6779 synchronized (dst) {
6780 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006781 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 dst.notifyAll();
6783 }
6784 updateOomAdjLocked(r);
6785 }
6786 }
6787
6788 Binder.restoreCallingIdentity(origId);
6789 }
6790 }
6791
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006792 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6793 ContentProviderConnection conn;
6794 try {
6795 conn = (ContentProviderConnection)connection;
6796 } catch (ClassCastException e) {
6797 String msg ="refContentProvider: " + connection
6798 + " not a ContentProviderConnection";
6799 Slog.w(TAG, msg);
6800 throw new IllegalArgumentException(msg);
6801 }
6802 if (conn == null) {
6803 throw new NullPointerException("connection is null");
6804 }
6805
6806 synchronized (this) {
6807 if (stable > 0) {
6808 conn.numStableIncs += stable;
6809 }
6810 stable = conn.stableCount + stable;
6811 if (stable < 0) {
6812 throw new IllegalStateException("stableCount < 0: " + stable);
6813 }
6814
6815 if (unstable > 0) {
6816 conn.numUnstableIncs += unstable;
6817 }
6818 unstable = conn.unstableCount + unstable;
6819 if (unstable < 0) {
6820 throw new IllegalStateException("unstableCount < 0: " + unstable);
6821 }
6822
6823 if ((stable+unstable) <= 0) {
6824 throw new IllegalStateException("ref counts can't go to zero here: stable="
6825 + stable + " unstable=" + unstable);
6826 }
6827 conn.stableCount = stable;
6828 conn.unstableCount = unstable;
6829 return !conn.dead;
6830 }
6831 }
6832
6833 public void unstableProviderDied(IBinder connection) {
6834 ContentProviderConnection conn;
6835 try {
6836 conn = (ContentProviderConnection)connection;
6837 } catch (ClassCastException e) {
6838 String msg ="refContentProvider: " + connection
6839 + " not a ContentProviderConnection";
6840 Slog.w(TAG, msg);
6841 throw new IllegalArgumentException(msg);
6842 }
6843 if (conn == null) {
6844 throw new NullPointerException("connection is null");
6845 }
6846
6847 // Safely retrieve the content provider associated with the connection.
6848 IContentProvider provider;
6849 synchronized (this) {
6850 provider = conn.provider.provider;
6851 }
6852
6853 if (provider == null) {
6854 // Um, yeah, we're way ahead of you.
6855 return;
6856 }
6857
6858 // Make sure the caller is being honest with us.
6859 if (provider.asBinder().pingBinder()) {
6860 // Er, no, still looks good to us.
6861 synchronized (this) {
6862 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6863 + " says " + conn + " died, but we don't agree");
6864 return;
6865 }
6866 }
6867
6868 // Well look at that! It's dead!
6869 synchronized (this) {
6870 if (conn.provider.provider != provider) {
6871 // But something changed... good enough.
6872 return;
6873 }
6874
6875 ProcessRecord proc = conn.provider.proc;
6876 if (proc == null || proc.thread == null) {
6877 // Seems like the process is already cleaned up.
6878 return;
6879 }
6880
6881 // As far as we're concerned, this is just like receiving a
6882 // death notification... just a bit prematurely.
6883 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6884 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006885 final long ident = Binder.clearCallingIdentity();
6886 try {
6887 appDiedLocked(proc, proc.pid, proc.thread);
6888 } finally {
6889 Binder.restoreCallingIdentity(ident);
6890 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006891 }
6892 }
6893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006894 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006895 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006896 synchronized (mSelf) {
6897 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6898 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006899 if (providers != null) {
6900 for (int i=providers.size()-1; i>=0; i--) {
6901 ProviderInfo pi = (ProviderInfo)providers.get(i);
6902 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6903 Slog.w(TAG, "Not installing system proc provider " + pi.name
6904 + ": not system .apk");
6905 providers.remove(i);
6906 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006907 }
6908 }
6909 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006910 if (providers != null) {
6911 mSystemThread.installSystemProviders(providers);
6912 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006913
6914 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006915
6916 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 }
6918
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006919 /**
6920 * Allows app to retrieve the MIME type of a URI without having permission
6921 * to access its content provider.
6922 *
6923 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6924 *
6925 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6926 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6927 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006928 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006929 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006930 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006931 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006932 final String name = uri.getAuthority();
6933 final long ident = Binder.clearCallingIdentity();
6934 ContentProviderHolder holder = null;
6935
6936 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006937 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006938 if (holder != null) {
6939 return holder.provider.getType(uri);
6940 }
6941 } catch (RemoteException e) {
6942 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6943 return null;
6944 } finally {
6945 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006946 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006947 }
6948 Binder.restoreCallingIdentity(ident);
6949 }
6950
6951 return null;
6952 }
6953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 // =========================================================
6955 // GLOBAL MANAGEMENT
6956 // =========================================================
6957
6958 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006959 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 String proc = customProcess != null ? customProcess : info.processName;
6961 BatteryStatsImpl.Uid.Proc ps = null;
6962 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006963 int uid = info.uid;
6964 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006965 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006966 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6967 uid = 0;
6968 while (true) {
6969 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6970 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6971 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6972 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006973 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006974 mNextIsolatedProcessUid++;
6975 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6976 // No process for this uid, use it.
6977 break;
6978 }
6979 stepsLeft--;
6980 if (stepsLeft <= 0) {
6981 return null;
6982 }
6983 }
6984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006985 synchronized (stats) {
6986 ps = stats.getProcessStatsLocked(info.uid, proc);
6987 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006988 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006989 }
6990
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006991 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6992 ProcessRecord app;
6993 if (!isolated) {
6994 app = getProcessRecordLocked(info.processName, info.uid);
6995 } else {
6996 app = null;
6997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998
6999 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007000 app = newProcessRecordLocked(null, info, null, isolated);
7001 mProcessNames.put(info.processName, app.uid, app);
7002 if (isolated) {
7003 mIsolatedProcesses.put(app.uid, app);
7004 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007005 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007006 }
7007
Dianne Hackborne7f97212011-02-24 14:40:20 -08007008 // This package really, really can not be stopped.
7009 try {
7010 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007011 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007012 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007013 } catch (IllegalArgumentException e) {
7014 Slog.w(TAG, "Failed trying to unstop package "
7015 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007016 }
7017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7019 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7020 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007021 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 }
7023 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7024 mPersistentStartingProcesses.add(app);
7025 startProcessLocked(app, "added application", app.processName);
7026 }
7027
7028 return app;
7029 }
7030
7031 public void unhandledBack() {
7032 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7033 "unhandledBack()");
7034
7035 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007036 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007037 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 TAG, "Performing unhandledBack(): stack size = " + count);
7039 if (count > 1) {
7040 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007041 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007042 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 Binder.restoreCallingIdentity(origId);
7044 }
7045 }
7046 }
7047
7048 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007049 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007050 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007052 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 ParcelFileDescriptor pfd = null;
7054 if (cph != null) {
7055 // We record the binder invoker's uid in thread-local storage before
7056 // going to the content provider to open the file. Later, in the code
7057 // that handles all permissions checks, we look for this uid and use
7058 // that rather than the Activity Manager's own uid. The effect is that
7059 // we do the check against the caller's permissions even though it looks
7060 // to the content provider like the Activity Manager itself is making
7061 // the request.
7062 sCallerIdentity.set(new Identity(
7063 Binder.getCallingPid(), Binder.getCallingUid()));
7064 try {
7065 pfd = cph.provider.openFile(uri, "r");
7066 } catch (FileNotFoundException e) {
7067 // do nothing; pfd will be returned null
7068 } finally {
7069 // Ensure that whatever happens, we clean up the identity state
7070 sCallerIdentity.remove();
7071 }
7072
7073 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007074 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007076 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 }
7078 return pfd;
7079 }
7080
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007081 // Actually is sleeping or shutting down or whatever else in the future
7082 // is an inactive state.
7083 public boolean isSleeping() {
7084 return mSleeping || mShuttingDown;
7085 }
7086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007088 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7089 != PackageManager.PERMISSION_GRANTED) {
7090 throw new SecurityException("Requires permission "
7091 + android.Manifest.permission.DEVICE_POWER);
7092 }
7093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007095 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007096 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007098 if (!mSleeping) {
7099 mSleeping = true;
7100 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007101
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007102 // Initialize the wake times of all processes.
7103 checkExcessivePowerUsageLocked(false);
7104 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7105 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7106 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 }
7109 }
7110
Dianne Hackborn55280a92009-05-07 15:53:46 -07007111 public boolean shutdown(int timeout) {
7112 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7113 != PackageManager.PERMISSION_GRANTED) {
7114 throw new SecurityException("Requires permission "
7115 + android.Manifest.permission.SHUTDOWN);
7116 }
7117
7118 boolean timedout = false;
7119
7120 synchronized(this) {
7121 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007122 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007123
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007124 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007125 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007126 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007127 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007128 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007129 long delay = endTime - System.currentTimeMillis();
7130 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007131 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007132 timedout = true;
7133 break;
7134 }
7135 try {
7136 this.wait();
7137 } catch (InterruptedException e) {
7138 }
7139 }
7140 }
7141 }
7142
7143 mUsageStatsService.shutdown();
7144 mBatteryStatsService.shutdown();
7145
7146 return timedout;
7147 }
7148
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007149 public final void activitySlept(IBinder token) {
7150 if (localLOGV) Slog.v(
7151 TAG, "Activity slept: token=" + token);
7152
7153 ActivityRecord r = null;
7154
7155 final long origId = Binder.clearCallingIdentity();
7156
7157 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007158 r = mMainStack.isInStackLocked(token);
7159 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007160 mMainStack.activitySleptLocked(r);
7161 }
7162 }
7163
7164 Binder.restoreCallingIdentity(origId);
7165 }
7166
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007167 private void comeOutOfSleepIfNeededLocked() {
7168 if (!mWentToSleep && !mLockScreenShown) {
7169 if (mSleeping) {
7170 mSleeping = false;
7171 mMainStack.awakeFromSleepingLocked();
7172 mMainStack.resumeTopActivityLocked(null);
7173 }
7174 }
7175 }
7176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007178 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7179 != PackageManager.PERMISSION_GRANTED) {
7180 throw new SecurityException("Requires permission "
7181 + android.Manifest.permission.DEVICE_POWER);
7182 }
7183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007185 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007186 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007187 comeOutOfSleepIfNeededLocked();
7188 }
7189 }
7190
Jeff Brownc042ee22012-05-08 13:03:42 -07007191 private void updateEventDispatchingLocked() {
7192 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7193 }
7194
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007195 public void setLockScreenShown(boolean shown) {
7196 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7197 != PackageManager.PERMISSION_GRANTED) {
7198 throw new SecurityException("Requires permission "
7199 + android.Manifest.permission.DEVICE_POWER);
7200 }
7201
7202 synchronized(this) {
7203 mLockScreenShown = shown;
7204 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 }
7206 }
7207
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007208 public void stopAppSwitches() {
7209 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7210 != PackageManager.PERMISSION_GRANTED) {
7211 throw new SecurityException("Requires permission "
7212 + android.Manifest.permission.STOP_APP_SWITCHES);
7213 }
7214
7215 synchronized(this) {
7216 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7217 + APP_SWITCH_DELAY_TIME;
7218 mDidAppSwitch = false;
7219 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7220 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7221 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7222 }
7223 }
7224
7225 public void resumeAppSwitches() {
7226 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7227 != PackageManager.PERMISSION_GRANTED) {
7228 throw new SecurityException("Requires permission "
7229 + android.Manifest.permission.STOP_APP_SWITCHES);
7230 }
7231
7232 synchronized(this) {
7233 // Note that we don't execute any pending app switches... we will
7234 // let those wait until either the timeout, or the next start
7235 // activity request.
7236 mAppSwitchesAllowedTime = 0;
7237 }
7238 }
7239
7240 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7241 String name) {
7242 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7243 return true;
7244 }
7245
7246 final int perm = checkComponentPermission(
7247 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007248 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007249 if (perm == PackageManager.PERMISSION_GRANTED) {
7250 return true;
7251 }
7252
Joe Onorato8a9b2202010-02-26 18:56:32 -08007253 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007254 return false;
7255 }
7256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257 public void setDebugApp(String packageName, boolean waitForDebugger,
7258 boolean persistent) {
7259 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7260 "setDebugApp()");
7261
7262 // Note that this is not really thread safe if there are multiple
7263 // callers into it at the same time, but that's not a situation we
7264 // care about.
7265 if (persistent) {
7266 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007267 Settings.Global.putString(
7268 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007269 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007270 Settings.Global.putInt(
7271 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 waitForDebugger ? 1 : 0);
7273 }
7274
7275 synchronized (this) {
7276 if (!persistent) {
7277 mOrigDebugApp = mDebugApp;
7278 mOrigWaitForDebugger = mWaitForDebugger;
7279 }
7280 mDebugApp = packageName;
7281 mWaitForDebugger = waitForDebugger;
7282 mDebugTransient = !persistent;
7283 if (packageName != null) {
7284 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007285 forceStopPackageLocked(packageName, -1, false, false, true, true,
7286 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 Binder.restoreCallingIdentity(origId);
7288 }
7289 }
7290 }
7291
Siva Velusamy92a8b222012-03-09 16:24:04 -08007292 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7293 synchronized (this) {
7294 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7295 if (!isDebuggable) {
7296 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7297 throw new SecurityException("Process not debuggable: " + app.packageName);
7298 }
7299 }
7300
7301 mOpenGlTraceApp = processName;
7302 }
7303 }
7304
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007305 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7306 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7307 synchronized (this) {
7308 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7309 if (!isDebuggable) {
7310 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7311 throw new SecurityException("Process not debuggable: " + app.packageName);
7312 }
7313 }
7314 mProfileApp = processName;
7315 mProfileFile = profileFile;
7316 if (mProfileFd != null) {
7317 try {
7318 mProfileFd.close();
7319 } catch (IOException e) {
7320 }
7321 mProfileFd = null;
7322 }
7323 mProfileFd = profileFd;
7324 mProfileType = 0;
7325 mAutoStopProfiler = autoStopProfiler;
7326 }
7327 }
7328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 public void setAlwaysFinish(boolean enabled) {
7330 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7331 "setAlwaysFinish()");
7332
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007333 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007335 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336
7337 synchronized (this) {
7338 mAlwaysFinishActivities = enabled;
7339 }
7340 }
7341
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007342 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007343 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007344 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007345 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007346 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007347 }
7348 }
7349
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007350 public boolean isUserAMonkey() {
7351 // For now the fact that there is a controller implies
7352 // we have a monkey.
7353 synchronized (this) {
7354 return mController != null;
7355 }
7356 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007357
7358 public void requestBugReport() {
7359 // No permission check because this can't do anything harmful --
7360 // it will just eventually cause the user to be presented with
7361 // a UI to select where the bug report goes.
7362 SystemProperties.set("ctl.start", "bugreport");
7363 }
7364
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007365 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7366 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7367 != PackageManager.PERMISSION_GRANTED) {
7368 throw new SecurityException("Requires permission "
7369 + android.Manifest.permission.FILTER_EVENTS);
7370 }
7371
7372 ProcessRecord proc;
7373
7374 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7375 synchronized (this) {
7376 synchronized (mPidsSelfLocked) {
7377 proc = mPidsSelfLocked.get(pid);
7378 }
7379 if (proc != null) {
7380 if (proc.debugging) {
7381 return -1;
7382 }
7383
7384 if (mDidDexOpt) {
7385 // Give more time since we were dexopting.
7386 mDidDexOpt = false;
7387 return -1;
7388 }
7389
7390 if (proc.instrumentationClass != null) {
7391 Bundle info = new Bundle();
7392 info.putString("shortMsg", "keyDispatchingTimedOut");
7393 info.putString("longMsg", "Timed out while dispatching key event");
7394 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7395 proc = null;
7396 }
7397 }
7398 }
7399
7400 if (proc != null) {
7401 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7402 if (proc.instrumentationClass != null || proc.usingWrapper) {
7403 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7404 }
7405 }
7406
7407 return KEY_DISPATCHING_TIMEOUT;
7408 }
7409
Jeff Sharkeya4620792011-05-20 15:29:23 -07007410 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007411 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7412 "registerProcessObserver()");
7413 synchronized (this) {
7414 mProcessObservers.register(observer);
7415 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007416 }
7417
7418 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007419 synchronized (this) {
7420 mProcessObservers.unregister(observer);
7421 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007422 }
7423
Daniel Sandler69a48172010-06-23 16:29:36 -04007424 public void setImmersive(IBinder token, boolean immersive) {
7425 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007426 ActivityRecord r = mMainStack.isInStackLocked(token);
7427 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007428 throw new IllegalArgumentException();
7429 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007430 r.immersive = immersive;
7431 }
7432 }
7433
7434 public boolean isImmersive(IBinder token) {
7435 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007436 ActivityRecord r = mMainStack.isInStackLocked(token);
7437 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007438 throw new IllegalArgumentException();
7439 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007440 return r.immersive;
7441 }
7442 }
7443
7444 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007445 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007446 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007447 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007448 return (r != null) ? r.immersive : false;
7449 }
7450 }
7451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007452 public final void enterSafeMode() {
7453 synchronized(this) {
7454 // It only makes sense to do this before the system is ready
7455 // and started launching other packages.
7456 if (!mSystemReady) {
7457 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007458 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459 } catch (RemoteException e) {
7460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 }
7462 }
7463 }
7464
Jeff Brownb09abc12011-01-13 21:08:27 -08007465 public final void showSafeModeOverlay() {
7466 View v = LayoutInflater.from(mContext).inflate(
7467 com.android.internal.R.layout.safe_mode, null);
7468 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7469 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7470 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7471 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007472 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007473 lp.format = v.getBackground().getOpacity();
7474 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7475 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007476 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007477 ((WindowManager)mContext.getSystemService(
7478 Context.WINDOW_SERVICE)).addView(v, lp);
7479 }
7480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007481 public void noteWakeupAlarm(IIntentSender sender) {
7482 if (!(sender instanceof PendingIntentRecord)) {
7483 return;
7484 }
7485 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7486 synchronized (stats) {
7487 if (mBatteryStatsService.isOnBattery()) {
7488 mBatteryStatsService.enforceCallingPermission();
7489 PendingIntentRecord rec = (PendingIntentRecord)sender;
7490 int MY_UID = Binder.getCallingUid();
7491 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7492 BatteryStatsImpl.Uid.Pkg pkg =
7493 stats.getPackageStatsLocked(uid, rec.key.packageName);
7494 pkg.incWakeupsLocked();
7495 }
7496 }
7497 }
7498
Dianne Hackborn64825172011-03-02 21:32:58 -08007499 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007501 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007503 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007504 // XXX Note: don't acquire main activity lock here, because the window
7505 // manager calls in with its locks held.
7506
7507 boolean killed = false;
7508 synchronized (mPidsSelfLocked) {
7509 int[] types = new int[pids.length];
7510 int worstType = 0;
7511 for (int i=0; i<pids.length; i++) {
7512 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7513 if (proc != null) {
7514 int type = proc.setAdj;
7515 types[i] = type;
7516 if (type > worstType) {
7517 worstType = type;
7518 }
7519 }
7520 }
7521
Dianne Hackborn64825172011-03-02 21:32:58 -08007522 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007524 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7525 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007526 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007528
7529 // If this is not a secure call, don't let it kill processes that
7530 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007531 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7532 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007533 }
7534
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007535 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 for (int i=0; i<pids.length; i++) {
7537 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7538 if (proc == null) {
7539 continue;
7540 }
7541 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007542 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007543 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007544 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007545 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007547 proc.killedBackground = true;
7548 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 }
7550 }
7551 }
7552 return killed;
7553 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007554
7555 @Override
7556 public boolean killProcessesBelowForeground(String reason) {
7557 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7558 throw new SecurityException("killProcessesBelowForeground() only available to system");
7559 }
7560
7561 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7562 }
7563
7564 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7565 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7566 throw new SecurityException("killProcessesBelowAdj() only available to system");
7567 }
7568
7569 boolean killed = false;
7570 synchronized (mPidsSelfLocked) {
7571 final int size = mPidsSelfLocked.size();
7572 for (int i = 0; i < size; i++) {
7573 final int pid = mPidsSelfLocked.keyAt(i);
7574 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7575 if (proc == null) continue;
7576
7577 final int adj = proc.setAdj;
7578 if (adj > belowAdj && !proc.killedBackground) {
7579 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007580 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7581 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007582 killed = true;
7583 proc.killedBackground = true;
7584 Process.killProcessQuiet(pid);
7585 }
7586 }
7587 }
7588 return killed;
7589 }
7590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 public final void startRunning(String pkg, String cls, String action,
7592 String data) {
7593 synchronized(this) {
7594 if (mStartRunning) {
7595 return;
7596 }
7597 mStartRunning = true;
7598 mTopComponent = pkg != null && cls != null
7599 ? new ComponentName(pkg, cls) : null;
7600 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7601 mTopData = data;
7602 if (!mSystemReady) {
7603 return;
7604 }
7605 }
7606
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007607 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 }
7609
7610 private void retrieveSettings() {
7611 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007612 String debugApp = Settings.Global.getString(
7613 resolver, Settings.Global.DEBUG_APP);
7614 boolean waitForDebugger = Settings.Global.getInt(
7615 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7616 boolean alwaysFinishActivities = Settings.Global.getInt(
7617 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007618
7619 Configuration configuration = new Configuration();
7620 Settings.System.getConfiguration(resolver, configuration);
7621
7622 synchronized (this) {
7623 mDebugApp = mOrigDebugApp = debugApp;
7624 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7625 mAlwaysFinishActivities = alwaysFinishActivities;
7626 // This happens before any activities are started, so we can
7627 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007628 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007629 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 }
7631 }
7632
7633 public boolean testIsSystemReady() {
7634 // no need to synchronize(this) just to read & return the value
7635 return mSystemReady;
7636 }
7637
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007638 private static File getCalledPreBootReceiversFile() {
7639 File dataDir = Environment.getDataDirectory();
7640 File systemDir = new File(dataDir, "system");
7641 File fname = new File(systemDir, "called_pre_boots.dat");
7642 return fname;
7643 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007644
7645 static final int LAST_DONE_VERSION = 10000;
7646
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007647 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7648 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7649 File file = getCalledPreBootReceiversFile();
7650 FileInputStream fis = null;
7651 try {
7652 fis = new FileInputStream(file);
7653 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007654 int fvers = dis.readInt();
7655 if (fvers == LAST_DONE_VERSION) {
7656 String vers = dis.readUTF();
7657 String codename = dis.readUTF();
7658 String build = dis.readUTF();
7659 if (android.os.Build.VERSION.RELEASE.equals(vers)
7660 && android.os.Build.VERSION.CODENAME.equals(codename)
7661 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7662 int num = dis.readInt();
7663 while (num > 0) {
7664 num--;
7665 String pkg = dis.readUTF();
7666 String cls = dis.readUTF();
7667 lastDoneReceivers.add(new ComponentName(pkg, cls));
7668 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007669 }
7670 }
7671 } catch (FileNotFoundException e) {
7672 } catch (IOException e) {
7673 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7674 } finally {
7675 if (fis != null) {
7676 try {
7677 fis.close();
7678 } catch (IOException e) {
7679 }
7680 }
7681 }
7682 return lastDoneReceivers;
7683 }
7684
7685 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7686 File file = getCalledPreBootReceiversFile();
7687 FileOutputStream fos = null;
7688 DataOutputStream dos = null;
7689 try {
7690 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7691 fos = new FileOutputStream(file);
7692 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007693 dos.writeInt(LAST_DONE_VERSION);
7694 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007695 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007696 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007697 dos.writeInt(list.size());
7698 for (int i=0; i<list.size(); i++) {
7699 dos.writeUTF(list.get(i).getPackageName());
7700 dos.writeUTF(list.get(i).getClassName());
7701 }
7702 } catch (IOException e) {
7703 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7704 file.delete();
7705 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007706 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007707 if (dos != null) {
7708 try {
7709 dos.close();
7710 } catch (IOException e) {
7711 // TODO Auto-generated catch block
7712 e.printStackTrace();
7713 }
7714 }
7715 }
7716 }
7717
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007718 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 synchronized(this) {
7720 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007721 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 return;
7723 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007724
7725 // Check to see if there are any update receivers to run.
7726 if (!mDidUpdate) {
7727 if (mWaitingUpdate) {
7728 return;
7729 }
7730 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7731 List<ResolveInfo> ris = null;
7732 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007733 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007734 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007735 } catch (RemoteException e) {
7736 }
7737 if (ris != null) {
7738 for (int i=ris.size()-1; i>=0; i--) {
7739 if ((ris.get(i).activityInfo.applicationInfo.flags
7740 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7741 ris.remove(i);
7742 }
7743 }
7744 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007745
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007746 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007747
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007748 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007749 for (int i=0; i<ris.size(); i++) {
7750 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007751 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7752 if (lastDoneReceivers.contains(comp)) {
7753 ris.remove(i);
7754 i--;
7755 }
7756 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007757
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007758 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007759 for (int i=0; i<ris.size(); i++) {
7760 ActivityInfo ai = ris.get(i).activityInfo;
7761 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7762 doneReceivers.add(comp);
7763 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007764 for (int j=0; j<users.length; j++) {
7765 IIntentReceiver finisher = null;
7766 if (i == ris.size()-1 && j == users.length-1) {
7767 finisher = new IIntentReceiver.Stub() {
7768 public void performReceive(Intent intent, int resultCode,
7769 String data, Bundle extras, boolean ordered,
7770 boolean sticky, int sendingUser) {
7771 // The raw IIntentReceiver interface is called
7772 // with the AM lock held, so redispatch to
7773 // execute our code without the lock.
7774 mHandler.post(new Runnable() {
7775 public void run() {
7776 synchronized (ActivityManagerService.this) {
7777 mDidUpdate = true;
7778 }
7779 writeLastDonePreBootReceivers(doneReceivers);
7780 showBootMessage(mContext.getText(
7781 R.string.android_upgrading_complete),
7782 false);
7783 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007784 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007785 });
7786 }
7787 };
7788 }
7789 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7790 + " for user " + users[j]);
7791 broadcastIntentLocked(null, null, intent, null, finisher,
7792 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7793 users[j]);
7794 if (finisher != null) {
7795 mWaitingUpdate = true;
7796 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007797 }
7798 }
7799 }
7800 if (mWaitingUpdate) {
7801 return;
7802 }
7803 mDidUpdate = true;
7804 }
7805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 mSystemReady = true;
7807 if (!mStartRunning) {
7808 return;
7809 }
7810 }
7811
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007812 ArrayList<ProcessRecord> procsToKill = null;
7813 synchronized(mPidsSelfLocked) {
7814 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7815 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7816 if (!isAllowedWhileBooting(proc.info)){
7817 if (procsToKill == null) {
7818 procsToKill = new ArrayList<ProcessRecord>();
7819 }
7820 procsToKill.add(proc);
7821 }
7822 }
7823 }
7824
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007825 synchronized(this) {
7826 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007827 for (int i=procsToKill.size()-1; i>=0; i--) {
7828 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007829 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007830 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007831 }
7832 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007833
7834 // Now that we have cleaned up any update processes, we
7835 // are ready to start launching real processes and know that
7836 // we won't trample on them any more.
7837 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007838 }
7839
Joe Onorato8a9b2202010-02-26 18:56:32 -08007840 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007841 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 SystemClock.uptimeMillis());
7843
7844 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007845 // Make sure we have no pre-ready processes sitting around.
7846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7848 ResolveInfo ri = mContext.getPackageManager()
7849 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007850 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 CharSequence errorMsg = null;
7852 if (ri != null) {
7853 ActivityInfo ai = ri.activityInfo;
7854 ApplicationInfo app = ai.applicationInfo;
7855 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7856 mTopAction = Intent.ACTION_FACTORY_TEST;
7857 mTopData = null;
7858 mTopComponent = new ComponentName(app.packageName,
7859 ai.name);
7860 } else {
7861 errorMsg = mContext.getResources().getText(
7862 com.android.internal.R.string.factorytest_not_system);
7863 }
7864 } else {
7865 errorMsg = mContext.getResources().getText(
7866 com.android.internal.R.string.factorytest_no_action);
7867 }
7868 if (errorMsg != null) {
7869 mTopAction = null;
7870 mTopData = null;
7871 mTopComponent = null;
7872 Message msg = Message.obtain();
7873 msg.what = SHOW_FACTORY_ERROR_MSG;
7874 msg.getData().putCharSequence("msg", errorMsg);
7875 mHandler.sendMessage(msg);
7876 }
7877 }
7878 }
7879
7880 retrieveSettings();
7881
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007882 if (goingCallback != null) goingCallback.run();
7883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 synchronized (this) {
7885 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7886 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007887 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007888 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 if (apps != null) {
7890 int N = apps.size();
7891 int i;
7892 for (i=0; i<N; i++) {
7893 ApplicationInfo info
7894 = (ApplicationInfo)apps.get(i);
7895 if (info != null &&
7896 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007897 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 }
7899 }
7900 }
7901 } catch (RemoteException ex) {
7902 // pm is in same process, this will never happen.
7903 }
7904 }
7905
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007906 // Start up initial activity.
7907 mBooting = true;
7908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007910 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 Message msg = Message.obtain();
7912 msg.what = SHOW_UID_ERROR_MSG;
7913 mHandler.sendMessage(msg);
7914 }
7915 } catch (RemoteException e) {
7916 }
7917
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007918 long ident = Binder.clearCallingIdentity();
7919 try {
7920 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007921 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7922 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007923 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7924 broadcastIntentLocked(null, null, intent,
7925 null, null, 0, null, null, null,
7926 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07007927 intent = new Intent(Intent.ACTION_USER_STARTING);
7928 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7929 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7930 broadcastIntentLocked(null, null, intent,
7931 null, new IIntentReceiver.Stub() {
7932 @Override
7933 public void performReceive(Intent intent, int resultCode, String data,
7934 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
7935 throws RemoteException {
7936 }
7937 }, 0, null, null,
7938 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08007939 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007940 } finally {
7941 Binder.restoreCallingIdentity(ident);
7942 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007943 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007944 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 }
7946 }
7947
Dan Egnorb7f03672009-12-09 16:22:32 -08007948 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007949 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007951 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007952 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 startAppProblemLocked(app);
7954 app.stopFreezingAllLocked();
7955 return handleAppCrashLocked(app);
7956 }
7957
Dan Egnorb7f03672009-12-09 16:22:32 -08007958 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007959 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007961 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007962 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7963 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 startAppProblemLocked(app);
7965 app.stopFreezingAllLocked();
7966 }
7967
7968 /**
7969 * Generate a process error record, suitable for attachment to a ProcessRecord.
7970 *
7971 * @param app The ProcessRecord in which the error occurred.
7972 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7973 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007974 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 * @param shortMsg Short message describing the crash.
7976 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007977 * @param stackTrace Full crash stack trace, may be null.
7978 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 * @return Returns a fully-formed AppErrorStateInfo record.
7980 */
7981 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007982 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985 report.condition = condition;
7986 report.processName = app.processName;
7987 report.pid = app.pid;
7988 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007989 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 report.shortMsg = shortMsg;
7991 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007992 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007993
7994 return report;
7995 }
7996
Dan Egnor42471dd2010-01-07 17:25:22 -08007997 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 synchronized (this) {
7999 app.crashing = false;
8000 app.crashingReport = null;
8001 app.notResponding = false;
8002 app.notRespondingReport = null;
8003 if (app.anrDialog == fromDialog) {
8004 app.anrDialog = null;
8005 }
8006 if (app.waitDialog == fromDialog) {
8007 app.waitDialog = null;
8008 }
8009 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008010 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008011 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008012 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008013 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008014 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 }
8017 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008018
Dan Egnorb7f03672009-12-09 16:22:32 -08008019 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008020 if (mHeadless) {
8021 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8022 return false;
8023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 long now = SystemClock.uptimeMillis();
8025
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008026 Long crashTime;
8027 if (!app.isolated) {
8028 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8029 } else {
8030 crashTime = null;
8031 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008032 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008034 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008036 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008037 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008038 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8039 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008041 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008043 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8044 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 }
8046 }
8047 if (!app.persistent) {
8048 // We don't want to start this process again until the user
8049 // explicitly does so... but for persistent process, we really
8050 // need to keep it running. If a persistent process is actually
8051 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008052 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008054 if (!app.isolated) {
8055 // XXX We don't have a way to mark isolated processes
8056 // as bad, since they don't have a peristent identity.
8057 mBadProcesses.put(app.info.processName, app.uid, now);
8058 mProcessCrashTimes.remove(app.info.processName, app.uid);
8059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008061 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008062 // Don't let services in this process be restarted and potentially
8063 // annoy the user repeatedly. Unless it is persistent, since those
8064 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008065 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008066 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008067 return false;
8068 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008069 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008070 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008071 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008072 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008073 // If the top running activity is from this crashing
8074 // process, then terminate it to avoid getting in a loop.
8075 Slog.w(TAG, " Force finishing activity "
8076 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008077 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008078 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008079 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008080 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008081 // stopped, to avoid a situation where one will get
8082 // re-start our crashing activity once it gets resumed again.
8083 index--;
8084 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008085 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008086 if (r.state == ActivityState.RESUMED
8087 || r.state == ActivityState.PAUSING
8088 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008089 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008090 Slog.w(TAG, " Force finishing activity "
8091 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008092 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008093 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008094 }
8095 }
8096 }
8097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 }
8099
8100 // Bump up the crash count of any services currently running in the proc.
8101 if (app.services.size() != 0) {
8102 // Any services running in the application need to be placed
8103 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008104 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008106 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 sr.crashCount++;
8108 }
8109 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008110
8111 // If the crashing process is what we consider to be the "home process" and it has been
8112 // replaced by a third-party app, clear the package preferred activities from packages
8113 // with a home activity running in the process to prevent a repeatedly crashing app
8114 // from blocking the user to manually clear the list.
8115 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8116 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8117 Iterator it = mHomeProcess.activities.iterator();
8118 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008119 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008120 if (r.isHomeActivity) {
8121 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8122 try {
8123 ActivityThread.getPackageManager()
8124 .clearPackagePreferredActivities(r.packageName);
8125 } catch (RemoteException c) {
8126 // pm is in same process, this will never happen.
8127 }
8128 }
8129 }
8130 }
8131
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008132 if (!app.isolated) {
8133 // XXX Can't keep track of crash times for isolated processes,
8134 // because they don't have a perisistent identity.
8135 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8136 }
8137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 return true;
8139 }
8140
8141 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008142 if (app.userId == mCurrentUserId) {
8143 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8144 mContext, app.info.packageName, app.info.flags);
8145 } else {
8146 // If this app is not running under the current user, then we
8147 // can't give it a report button because that would require
8148 // launching the report UI under a different user.
8149 app.errorReportReceiver = null;
8150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 skipCurrentReceiverLocked(app);
8152 }
8153
8154 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008155 for (BroadcastQueue queue : mBroadcastQueues) {
8156 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 }
8158 }
8159
Dan Egnor60d87622009-12-16 16:32:58 -08008160 /**
8161 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8162 * The application process will exit immediately after this call returns.
8163 * @param app object of the crashing app, null for the system server
8164 * @param crashInfo describing the exception
8165 */
8166 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008167 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008168 final String processName = app == null ? "system_server"
8169 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008170
8171 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008172 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008173 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008174 crashInfo.exceptionClassName,
8175 crashInfo.exceptionMessage,
8176 crashInfo.throwFileName,
8177 crashInfo.throwLineNumber);
8178
Jeff Sharkeya353d262011-10-28 11:12:06 -07008179 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008180
8181 crashApplication(r, crashInfo);
8182 }
8183
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008184 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008185 IBinder app,
8186 int violationMask,
8187 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008188 ProcessRecord r = findAppProcess(app, "StrictMode");
8189 if (r == null) {
8190 return;
8191 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008192
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008193 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008194 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008195 boolean logIt = true;
8196 synchronized (mAlreadyLoggedViolatedStacks) {
8197 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8198 logIt = false;
8199 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008200 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008201 // the relative pain numbers, without logging all
8202 // the stack traces repeatedly. We'd want to do
8203 // likewise in the client code, which also does
8204 // dup suppression, before the Binder call.
8205 } else {
8206 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8207 mAlreadyLoggedViolatedStacks.clear();
8208 }
8209 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8210 }
8211 }
8212 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008213 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008214 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008215 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008216
8217 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8218 AppErrorResult result = new AppErrorResult();
8219 synchronized (this) {
8220 final long origId = Binder.clearCallingIdentity();
8221
8222 Message msg = Message.obtain();
8223 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8224 HashMap<String, Object> data = new HashMap<String, Object>();
8225 data.put("result", result);
8226 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008227 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008228 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008229 msg.obj = data;
8230 mHandler.sendMessage(msg);
8231
8232 Binder.restoreCallingIdentity(origId);
8233 }
8234 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008235 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008236 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008237 }
8238
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008239 // Depending on the policy in effect, there could be a bunch of
8240 // these in quick succession so we try to batch these together to
8241 // minimize disk writes, number of dropbox entries, and maximize
8242 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008243 private void logStrictModeViolationToDropBox(
8244 ProcessRecord process,
8245 StrictMode.ViolationInfo info) {
8246 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008247 return;
8248 }
8249 final boolean isSystemApp = process == null ||
8250 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8251 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008252 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008253 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8254 final DropBoxManager dbox = (DropBoxManager)
8255 mContext.getSystemService(Context.DROPBOX_SERVICE);
8256
8257 // Exit early if the dropbox isn't configured to accept this report type.
8258 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8259
8260 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008261 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008262 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8263 synchronized (sb) {
8264 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008265 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008266 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8267 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008268 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8269 if (info.violationNumThisLoop != 0) {
8270 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8271 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008272 if (info.numAnimationsRunning != 0) {
8273 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8274 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008275 if (info.broadcastIntentAction != null) {
8276 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8277 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008278 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008279 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008280 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008281 if (info.numInstances != -1) {
8282 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8283 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008284 if (info.tags != null) {
8285 for (String tag : info.tags) {
8286 sb.append("Span-Tag: ").append(tag).append("\n");
8287 }
8288 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008289 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008290 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8291 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008292 }
8293 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008294
8295 // Only buffer up to ~64k. Various logging bits truncate
8296 // things at 128k.
8297 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008298 }
8299
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008300 // Flush immediately if the buffer's grown too large, or this
8301 // is a non-system app. Non-system apps are isolated with a
8302 // different tag & policy and not batched.
8303 //
8304 // Batching is useful during internal testing with
8305 // StrictMode settings turned up high. Without batching,
8306 // thousands of separate files could be created on boot.
8307 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008308 new Thread("Error dump: " + dropboxTag) {
8309 @Override
8310 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008311 String report;
8312 synchronized (sb) {
8313 report = sb.toString();
8314 sb.delete(0, sb.length());
8315 sb.trimToSize();
8316 }
8317 if (report.length() != 0) {
8318 dbox.addText(dropboxTag, report);
8319 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008320 }
8321 }.start();
8322 return;
8323 }
8324
8325 // System app batching:
8326 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008327 // An existing dropbox-writing thread is outstanding, so
8328 // we don't need to start it up. The existing thread will
8329 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008330 return;
8331 }
8332
8333 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8334 // (After this point, we shouldn't access AMS internal data structures.)
8335 new Thread("Error dump: " + dropboxTag) {
8336 @Override
8337 public void run() {
8338 // 5 second sleep to let stacks arrive and be batched together
8339 try {
8340 Thread.sleep(5000); // 5 seconds
8341 } catch (InterruptedException e) {}
8342
8343 String errorReport;
8344 synchronized (mStrictModeBuffer) {
8345 errorReport = mStrictModeBuffer.toString();
8346 if (errorReport.length() == 0) {
8347 return;
8348 }
8349 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8350 mStrictModeBuffer.trimToSize();
8351 }
8352 dbox.addText(dropboxTag, errorReport);
8353 }
8354 }.start();
8355 }
8356
Dan Egnor60d87622009-12-16 16:32:58 -08008357 /**
8358 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8359 * @param app object of the crashing app, null for the system server
8360 * @param tag reported by the caller
8361 * @param crashInfo describing the context of the error
8362 * @return true if the process should exit immediately (WTF is fatal)
8363 */
8364 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008365 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008366 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008367 final String processName = app == null ? "system_server"
8368 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008369
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008370 EventLog.writeEvent(EventLogTags.AM_WTF,
8371 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008372 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008373 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008374 tag, crashInfo.exceptionMessage);
8375
Jeff Sharkeya353d262011-10-28 11:12:06 -07008376 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008377
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008378 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008379 Settings.Global.getInt(mContext.getContentResolver(),
8380 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008381 crashApplication(r, crashInfo);
8382 return true;
8383 } else {
8384 return false;
8385 }
8386 }
8387
8388 /**
8389 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8390 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8391 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008392 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008393 if (app == null) {
8394 return null;
8395 }
8396
8397 synchronized (this) {
8398 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8399 final int NA = apps.size();
8400 for (int ia=0; ia<NA; ia++) {
8401 ProcessRecord p = apps.valueAt(ia);
8402 if (p.thread != null && p.thread.asBinder() == app) {
8403 return p;
8404 }
8405 }
8406 }
8407
Dianne Hackborncb44d962011-03-10 17:02:27 -08008408 Slog.w(TAG, "Can't find mystery application for " + reason
8409 + " from pid=" + Binder.getCallingPid()
8410 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008411 return null;
8412 }
8413 }
8414
8415 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008416 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8417 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008418 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008419 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8420 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008421 // Watchdog thread ends up invoking this function (with
8422 // a null ProcessRecord) to add the stack file to dropbox.
8423 // Do not acquire a lock on this (am) in such cases, as it
8424 // could cause a potential deadlock, if and when watchdog
8425 // is invoked due to unavailability of lock on am and it
8426 // would prevent watchdog from killing system_server.
8427 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008428 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008429 return;
8430 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008431 // Note: ProcessRecord 'process' is guarded by the service
8432 // instance. (notably process.pkgList, which could otherwise change
8433 // concurrently during execution of this method)
8434 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008435 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008436 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008437 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008438 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8439 for (String pkg : process.pkgList) {
8440 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008441 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008442 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008443 if (pi != null) {
8444 sb.append(" v").append(pi.versionCode);
8445 if (pi.versionName != null) {
8446 sb.append(" (").append(pi.versionName).append(")");
8447 }
8448 }
8449 } catch (RemoteException e) {
8450 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008451 }
Dan Egnora455d192010-03-12 08:52:28 -08008452 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008453 }
Dan Egnora455d192010-03-12 08:52:28 -08008454 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008455 }
8456
8457 private static String processClass(ProcessRecord process) {
8458 if (process == null || process.pid == MY_PID) {
8459 return "system_server";
8460 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8461 return "system_app";
8462 } else {
8463 return "data_app";
8464 }
8465 }
8466
8467 /**
8468 * Write a description of an error (crash, WTF, ANR) to the drop box.
8469 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8470 * @param process which caused the error, null means the system server
8471 * @param activity which triggered the error, null if unknown
8472 * @param parent activity related to the error, null if unknown
8473 * @param subject line related to the error, null if absent
8474 * @param report in long form describing the error, null if absent
8475 * @param logFile to include in the report, null if none
8476 * @param crashInfo giving an application stack trace, null if absent
8477 */
8478 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008479 ProcessRecord process, String processName, ActivityRecord activity,
8480 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008481 final String report, final File logFile,
8482 final ApplicationErrorReport.CrashInfo crashInfo) {
8483 // NOTE -- this must never acquire the ActivityManagerService lock,
8484 // otherwise the watchdog may be prevented from resetting the system.
8485
8486 final String dropboxTag = processClass(process) + "_" + eventType;
8487 final DropBoxManager dbox = (DropBoxManager)
8488 mContext.getSystemService(Context.DROPBOX_SERVICE);
8489
8490 // Exit early if the dropbox isn't configured to accept this report type.
8491 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8492
8493 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008494 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008495 if (activity != null) {
8496 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8497 }
8498 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8499 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8500 }
8501 if (parent != null && parent != activity) {
8502 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8503 }
8504 if (subject != null) {
8505 sb.append("Subject: ").append(subject).append("\n");
8506 }
8507 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008508 if (Debug.isDebuggerConnected()) {
8509 sb.append("Debugger: Connected\n");
8510 }
Dan Egnora455d192010-03-12 08:52:28 -08008511 sb.append("\n");
8512
8513 // Do the rest in a worker thread to avoid blocking the caller on I/O
8514 // (After this point, we shouldn't access AMS internal data structures.)
8515 Thread worker = new Thread("Error dump: " + dropboxTag) {
8516 @Override
8517 public void run() {
8518 if (report != null) {
8519 sb.append(report);
8520 }
8521 if (logFile != null) {
8522 try {
8523 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8524 } catch (IOException e) {
8525 Slog.e(TAG, "Error reading " + logFile, e);
8526 }
8527 }
8528 if (crashInfo != null && crashInfo.stackTrace != null) {
8529 sb.append(crashInfo.stackTrace);
8530 }
8531
Jeff Sharkey625239a2012-09-26 22:03:49 -07008532 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8533 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008534 if (lines > 0) {
8535 sb.append("\n");
8536
8537 // Merge several logcat streams, and take the last N lines
8538 InputStreamReader input = null;
8539 try {
8540 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8541 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8542 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8543
8544 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8545 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8546 input = new InputStreamReader(logcat.getInputStream());
8547
8548 int num;
8549 char[] buf = new char[8192];
8550 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8551 } catch (IOException e) {
8552 Slog.e(TAG, "Error running logcat", e);
8553 } finally {
8554 if (input != null) try { input.close(); } catch (IOException e) {}
8555 }
8556 }
8557
8558 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008559 }
Dan Egnora455d192010-03-12 08:52:28 -08008560 };
8561
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008562 if (process == null) {
8563 // If process is null, we are being called from some internal code
8564 // and may be about to die -- run this synchronously.
8565 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008566 } else {
8567 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008568 }
8569 }
8570
8571 /**
8572 * Bring up the "unexpected error" dialog box for a crashing app.
8573 * Deal with edge cases (intercepts from instrumented applications,
8574 * ActivityController, error intent receivers, that sort of thing).
8575 * @param r the application crashing
8576 * @param crashInfo describing the failure
8577 */
8578 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008579 long timeMillis = System.currentTimeMillis();
8580 String shortMsg = crashInfo.exceptionClassName;
8581 String longMsg = crashInfo.exceptionMessage;
8582 String stackTrace = crashInfo.stackTrace;
8583 if (shortMsg != null && longMsg != null) {
8584 longMsg = shortMsg + ": " + longMsg;
8585 } else if (shortMsg != null) {
8586 longMsg = shortMsg;
8587 }
8588
Dan Egnor60d87622009-12-16 16:32:58 -08008589 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008591 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 try {
8593 String name = r != null ? r.processName : null;
8594 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008595 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008596 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008597 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598 + " at watcher's request");
8599 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008600 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 }
8602 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008603 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 }
8605 }
8606
8607 final long origId = Binder.clearCallingIdentity();
8608
8609 // If this process is running instrumentation, finish it.
8610 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008611 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008613 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8614 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 Bundle info = new Bundle();
8616 info.putString("shortMsg", shortMsg);
8617 info.putString("longMsg", longMsg);
8618 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8619 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008620 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 }
8622
Dan Egnor60d87622009-12-16 16:32:58 -08008623 // If we can't identify the process or it's already exceeded its crash quota,
8624 // quit right away without showing a crash dialog.
8625 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008627 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 }
8629
8630 Message msg = Message.obtain();
8631 msg.what = SHOW_ERROR_MSG;
8632 HashMap data = new HashMap();
8633 data.put("result", result);
8634 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 msg.obj = data;
8636 mHandler.sendMessage(msg);
8637
8638 Binder.restoreCallingIdentity(origId);
8639 }
8640
8641 int res = result.get();
8642
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008643 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008645 if (r != null && !r.isolated) {
8646 // XXX Can't keep track of crash time for isolated processes,
8647 // since they don't have a persistent identity.
8648 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649 SystemClock.uptimeMillis());
8650 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008651 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008652 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008653 }
8654 }
8655
8656 if (appErrorIntent != null) {
8657 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008658 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008659 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008660 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008664
8665 Intent createAppErrorIntentLocked(ProcessRecord r,
8666 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8667 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008668 if (report == null) {
8669 return null;
8670 }
8671 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8672 result.setComponent(r.errorReportReceiver);
8673 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8674 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8675 return result;
8676 }
8677
Dan Egnorb7f03672009-12-09 16:22:32 -08008678 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8679 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008680 if (r.errorReportReceiver == null) {
8681 return null;
8682 }
8683
8684 if (!r.crashing && !r.notResponding) {
8685 return null;
8686 }
8687
Dan Egnorb7f03672009-12-09 16:22:32 -08008688 ApplicationErrorReport report = new ApplicationErrorReport();
8689 report.packageName = r.info.packageName;
8690 report.installerPackageName = r.errorReportReceiver.getPackageName();
8691 report.processName = r.processName;
8692 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008693 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008694
Dan Egnorb7f03672009-12-09 16:22:32 -08008695 if (r.crashing) {
8696 report.type = ApplicationErrorReport.TYPE_CRASH;
8697 report.crashInfo = crashInfo;
8698 } else if (r.notResponding) {
8699 report.type = ApplicationErrorReport.TYPE_ANR;
8700 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008701
Dan Egnorb7f03672009-12-09 16:22:32 -08008702 report.anrInfo.activity = r.notRespondingReport.tag;
8703 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8704 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008705 }
8706
Dan Egnorb7f03672009-12-09 16:22:32 -08008707 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008708 }
8709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008711 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712 // assume our apps are happy - lazy create the list
8713 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8714
Dianne Hackborn0c380492012-08-20 17:23:30 -07008715 final boolean allUsers = ActivityManager.checkUidPermission(
8716 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8717 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8718 int userId = UserHandle.getUserId(Binder.getCallingUid());
8719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 synchronized (this) {
8721
8722 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008723 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8724 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008725 if (!allUsers && app.userId != userId) {
8726 continue;
8727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8729 // This one's in trouble, so we'll generate a report for it
8730 // crashes are higher priority (in case there's a crash *and* an anr)
8731 ActivityManager.ProcessErrorStateInfo report = null;
8732 if (app.crashing) {
8733 report = app.crashingReport;
8734 } else if (app.notResponding) {
8735 report = app.notRespondingReport;
8736 }
8737
8738 if (report != null) {
8739 if (errList == null) {
8740 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8741 }
8742 errList.add(report);
8743 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008744 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 " crashing = " + app.crashing +
8746 " notResponding = " + app.notResponding);
8747 }
8748 }
8749 }
8750 }
8751
8752 return errList;
8753 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008754
8755 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008756 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008757 if (currApp != null) {
8758 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8759 }
8760 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008761 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8762 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008763 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8764 if (currApp != null) {
8765 currApp.lru = 0;
8766 }
8767 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008768 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008769 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8770 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8771 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8772 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8773 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8774 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8775 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8776 } else {
8777 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8778 }
8779 }
8780
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008781 private void fillInProcMemInfo(ProcessRecord app,
8782 ActivityManager.RunningAppProcessInfo outInfo) {
8783 outInfo.pid = app.pid;
8784 outInfo.uid = app.info.uid;
8785 if (mHeavyWeightProcess == app) {
8786 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8787 }
8788 if (app.persistent) {
8789 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8790 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008791 if (app.hasActivities) {
8792 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8793 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008794 outInfo.lastTrimLevel = app.trimMemoryLevel;
8795 int adj = app.curAdj;
8796 outInfo.importance = oomAdjToImportance(adj, outInfo);
8797 outInfo.importanceReasonCode = app.adjTypeCode;
8798 }
8799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008801 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 // Lazy instantiation of list
8803 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008804 final boolean allUsers = ActivityManager.checkUidPermission(
8805 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8806 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8807 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 synchronized (this) {
8809 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008810 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8811 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008812 if (!allUsers && app.userId != userId) {
8813 continue;
8814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8816 // Generate process state info for running application
8817 ActivityManager.RunningAppProcessInfo currApp =
8818 new ActivityManager.RunningAppProcessInfo(app.processName,
8819 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008820 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008821 if (app.adjSource instanceof ProcessRecord) {
8822 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008823 currApp.importanceReasonImportance = oomAdjToImportance(
8824 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008825 } else if (app.adjSource instanceof ActivityRecord) {
8826 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008827 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8828 }
8829 if (app.adjTarget instanceof ComponentName) {
8830 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8831 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008832 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 // + " lru=" + currApp.lru);
8834 if (runList == null) {
8835 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8836 }
8837 runList.add(currApp);
8838 }
8839 }
8840 }
8841 return runList;
8842 }
8843
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008844 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008845 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008846 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8847 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8848 if (runningApps != null && runningApps.size() > 0) {
8849 Set<String> extList = new HashSet<String>();
8850 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8851 if (app.pkgList != null) {
8852 for (String pkg : app.pkgList) {
8853 extList.add(pkg);
8854 }
8855 }
8856 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008857 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008858 for (String pkg : extList) {
8859 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008860 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008861 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8862 retList.add(info);
8863 }
8864 } catch (RemoteException e) {
8865 }
8866 }
8867 }
8868 return retList;
8869 }
8870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008872 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8873 enforceNotIsolatedCaller("getMyMemoryState");
8874 synchronized (this) {
8875 ProcessRecord proc;
8876 synchronized (mPidsSelfLocked) {
8877 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8878 }
8879 fillInProcMemInfo(proc, outInfo);
8880 }
8881 }
8882
8883 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008885 if (checkCallingPermission(android.Manifest.permission.DUMP)
8886 != PackageManager.PERMISSION_GRANTED) {
8887 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8888 + Binder.getCallingPid()
8889 + ", uid=" + Binder.getCallingUid()
8890 + " without permission "
8891 + android.Manifest.permission.DUMP);
8892 return;
8893 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008894
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008895 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008896 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008897 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898
8899 int opti = 0;
8900 while (opti < args.length) {
8901 String opt = args[opti];
8902 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8903 break;
8904 }
8905 opti++;
8906 if ("-a".equals(opt)) {
8907 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008908 } else if ("-c".equals(opt)) {
8909 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 } else if ("-h".equals(opt)) {
8911 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008912 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008913 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008914 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008915 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008916 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8917 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008918 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008919 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008920 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008921 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008922 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008923 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008924 pw.println(" all: dump all activities");
8925 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008926 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008927 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8928 pw.println(" a partial substring in a component name, a");
8929 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008930 pw.println(" -a: include all available server state.");
8931 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008933 } else {
8934 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008936 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008937
8938 long origId = Binder.clearCallingIdentity();
8939 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008940 // Is the caller requesting to dump a particular piece of data?
8941 if (opti < args.length) {
8942 String cmd = args[opti];
8943 opti++;
8944 if ("activities".equals(cmd) || "a".equals(cmd)) {
8945 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008946 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008948 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 String[] newArgs;
8950 String name;
8951 if (opti >= args.length) {
8952 name = null;
8953 newArgs = EMPTY_STRING_ARRAY;
8954 } else {
8955 name = args[opti];
8956 opti++;
8957 newArgs = new String[args.length - opti];
8958 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8959 args.length - opti);
8960 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008961 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008962 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008963 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008964 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008965 String[] newArgs;
8966 String name;
8967 if (opti >= args.length) {
8968 name = null;
8969 newArgs = EMPTY_STRING_ARRAY;
8970 } else {
8971 name = args[opti];
8972 opti++;
8973 newArgs = new String[args.length - opti];
8974 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8975 args.length - opti);
8976 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008977 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008978 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008979 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008980 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008981 String[] newArgs;
8982 String name;
8983 if (opti >= args.length) {
8984 name = null;
8985 newArgs = EMPTY_STRING_ARRAY;
8986 } else {
8987 name = args[opti];
8988 opti++;
8989 newArgs = new String[args.length - opti];
8990 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8991 args.length - opti);
8992 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008993 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008994 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008995 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008996 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8997 synchronized (this) {
8998 dumpOomLocked(fd, pw, args, opti, true);
8999 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009000 } else if ("provider".equals(cmd)) {
9001 String[] newArgs;
9002 String name;
9003 if (opti >= args.length) {
9004 name = null;
9005 newArgs = EMPTY_STRING_ARRAY;
9006 } else {
9007 name = args[opti];
9008 opti++;
9009 newArgs = new String[args.length - opti];
9010 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9011 }
9012 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9013 pw.println("No providers match: " + name);
9014 pw.println("Use -h for help.");
9015 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009016 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9017 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009018 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009019 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009021 String[] newArgs;
9022 String name;
9023 if (opti >= args.length) {
9024 name = null;
9025 newArgs = EMPTY_STRING_ARRAY;
9026 } else {
9027 name = args[opti];
9028 opti++;
9029 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009030 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9031 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009033 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009034 pw.println("No services match: " + name);
9035 pw.println("Use -h for help.");
9036 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009037 } else if ("package".equals(cmd)) {
9038 String[] newArgs;
9039 if (opti >= args.length) {
9040 pw.println("package: no package name specified");
9041 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009042 } else {
9043 dumpPackage = args[opti];
9044 opti++;
9045 newArgs = new String[args.length - opti];
9046 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9047 args.length - opti);
9048 args = newArgs;
9049 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009050 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009052 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9053 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009054 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009056 } else {
9057 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009058 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9059 pw.println("Bad activity command, or no activities match: " + cmd);
9060 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009061 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009062 }
9063 if (!more) {
9064 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009065 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009067 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009068
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009069 // No piece of data specified, dump everything.
9070 synchronized (this) {
9071 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009072 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009073 if (needSep) {
9074 pw.println(" ");
9075 }
9076 if (dumpAll) {
9077 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009078 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009079 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009080 if (needSep) {
9081 pw.println(" ");
9082 }
9083 if (dumpAll) {
9084 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009086 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009087 if (needSep) {
9088 pw.println(" ");
9089 }
9090 if (dumpAll) {
9091 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009092 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009093 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 if (needSep) {
9095 pw.println(" ");
9096 }
9097 if (dumpAll) {
9098 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009099 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009100 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101 if (needSep) {
9102 pw.println(" ");
9103 }
9104 if (dumpAll) {
9105 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009106 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009107 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009108 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009109 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009110 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009111
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009112 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009113 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009114 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9115 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009116 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9117 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009118 pw.println(" ");
9119 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009120 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9121 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009122 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009124 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009125 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009126 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009128 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009130 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009131 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009132 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009133 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009134 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9135 pw.println(" ");
9136 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009137 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009138 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009139 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009140 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009141 pw.println(" ");
9142 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009143 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009144 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009147 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009148 if (mMainStack.mPausingActivity != null) {
9149 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009150 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009151 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009152 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009153 if (dumpAll) {
9154 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9155 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009156 pw.println(" mDismissKeyguardOnNextActivity: "
9157 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009159
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009160 if (mRecentTasks.size() > 0) {
9161 pw.println();
9162 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009163
9164 final int N = mRecentTasks.size();
9165 for (int i=0; i<N; i++) {
9166 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009167 if (dumpPackage != null) {
9168 if (tr.realActivity == null ||
9169 !dumpPackage.equals(tr.realActivity)) {
9170 continue;
9171 }
9172 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009173 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9174 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009175 if (dumpAll) {
9176 mRecentTasks.get(i).dump(pw, " ");
9177 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009178 }
9179 }
9180
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009181 if (dumpAll) {
9182 pw.println(" ");
9183 pw.println(" mCurTask: " + mCurTask);
9184 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009185
9186 return true;
9187 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009188
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009189 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009190 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009191 boolean needSep = false;
9192 int numPers = 0;
9193
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009194 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9195
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009196 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009197 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9198 final int NA = procs.size();
9199 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009200 ProcessRecord r = procs.valueAt(ia);
9201 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9202 continue;
9203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 if (!needSep) {
9205 pw.println(" All known processes:");
9206 needSep = true;
9207 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009208 pw.print(r.persistent ? " *PERS*" : " *APP*");
9209 pw.print(" UID "); pw.print(procs.keyAt(ia));
9210 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211 r.dump(pw, " ");
9212 if (r.persistent) {
9213 numPers++;
9214 }
9215 }
9216 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009217 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009218
9219 if (mIsolatedProcesses.size() > 0) {
9220 if (needSep) pw.println(" ");
9221 needSep = true;
9222 pw.println(" Isolated process list (sorted by uid):");
9223 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9224 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9225 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9226 continue;
9227 }
9228 pw.println(String.format("%sIsolated #%2d: %s",
9229 " ", i, r.toString()));
9230 }
9231 }
9232
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009233 if (mLruProcesses.size() > 0) {
9234 if (needSep) pw.println(" ");
9235 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009236 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009237 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009238 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009239 needSep = true;
9240 }
9241
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009242 if (dumpAll) {
9243 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009244 boolean printed = false;
9245 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9246 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9247 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9248 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009249 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009250 if (!printed) {
9251 if (needSep) pw.println(" ");
9252 needSep = true;
9253 pw.println(" PID mappings:");
9254 printed = true;
9255 }
9256 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9257 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009258 }
9259 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009260 }
9261
9262 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009263 synchronized (mPidsSelfLocked) {
9264 boolean printed = false;
9265 for (int i=0; i<mForegroundProcesses.size(); i++) {
9266 ProcessRecord r = mPidsSelfLocked.get(
9267 mForegroundProcesses.valueAt(i).pid);
9268 if (dumpPackage != null && (r == null
9269 || !dumpPackage.equals(r.info.packageName))) {
9270 continue;
9271 }
9272 if (!printed) {
9273 if (needSep) pw.println(" ");
9274 needSep = true;
9275 pw.println(" Foreground Processes:");
9276 printed = true;
9277 }
9278 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9279 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009282 }
9283
9284 if (mPersistentStartingProcesses.size() > 0) {
9285 if (needSep) pw.println(" ");
9286 needSep = true;
9287 pw.println(" Persisent processes that are starting:");
9288 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009289 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009291
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009292 if (mRemovedProcesses.size() > 0) {
9293 if (needSep) pw.println(" ");
9294 needSep = true;
9295 pw.println(" Processes that are being removed:");
9296 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009297 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009298 }
9299
9300 if (mProcessesOnHold.size() > 0) {
9301 if (needSep) pw.println(" ");
9302 needSep = true;
9303 pw.println(" Processes that are on old until the system is ready:");
9304 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009305 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009308 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309
9310 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009311 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009312 long now = SystemClock.uptimeMillis();
9313 for (Map.Entry<String, SparseArray<Long>> procs
9314 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009315 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316 SparseArray<Long> uids = procs.getValue();
9317 final int N = uids.size();
9318 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009319 int puid = uids.keyAt(i);
9320 ProcessRecord r = mProcessNames.get(pname, puid);
9321 if (dumpPackage != null && (r == null
9322 || !dumpPackage.equals(r.info.packageName))) {
9323 continue;
9324 }
9325 if (!printed) {
9326 if (needSep) pw.println(" ");
9327 needSep = true;
9328 pw.println(" Time since processes crashed:");
9329 printed = true;
9330 }
9331 pw.print(" Process "); pw.print(pname);
9332 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009333 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009334 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9335 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009336 }
9337 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009340 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009341 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009342 for (Map.Entry<String, SparseArray<Long>> procs
9343 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009344 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009345 SparseArray<Long> uids = procs.getValue();
9346 final int N = uids.size();
9347 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009348 int puid = uids.keyAt(i);
9349 ProcessRecord r = mProcessNames.get(pname, puid);
9350 if (dumpPackage != null && (r == null
9351 || !dumpPackage.equals(r.info.packageName))) {
9352 continue;
9353 }
9354 if (!printed) {
9355 if (needSep) pw.println(" ");
9356 needSep = true;
9357 pw.println(" Bad processes:");
9358 }
9359 pw.print(" Bad process "); pw.print(pname);
9360 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009361 pw.print(": crashed at time ");
9362 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 }
9364 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009366
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009367 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009368 pw.println(" mStartedUsers:");
9369 for (int i=0; i<mStartedUsers.size(); i++) {
9370 UserStartedState uss = mStartedUsers.valueAt(i);
9371 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009372 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009373 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009374 pw.print(" mStartedUserArray: [");
9375 for (int i=0; i<mStartedUserArray.length; i++) {
9376 if (i > 0) pw.print(", ");
9377 pw.print(mStartedUserArray[i]);
9378 }
9379 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009380 pw.print(" mUserLru: [");
9381 for (int i=0; i<mUserLru.size(); i++) {
9382 if (i > 0) pw.print(", ");
9383 pw.print(mUserLru.get(i));
9384 }
9385 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009386 if (dumpAll) {
9387 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9388 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009389 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009390 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009391 if (dumpAll) {
9392 StringBuilder sb = new StringBuilder(128);
9393 sb.append(" mPreviousProcessVisibleTime: ");
9394 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9395 pw.println(sb);
9396 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009397 if (mHeavyWeightProcess != null) {
9398 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9399 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009400 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009401 if (dumpAll) {
9402 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009403 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009404 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009405 for (Map.Entry<String, Integer> entry
9406 : mCompatModePackages.getPackages().entrySet()) {
9407 String pkg = entry.getKey();
9408 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009409 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9410 continue;
9411 }
9412 if (!printed) {
9413 pw.println(" mScreenCompatPackages:");
9414 printed = true;
9415 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009416 pw.print(" "); pw.print(pkg); pw.print(": ");
9417 pw.print(mode); pw.println();
9418 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009419 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009420 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009421 if (mSleeping || mWentToSleep || mLockScreenShown) {
9422 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9423 + " mLockScreenShown " + mLockScreenShown);
9424 }
9425 if (mShuttingDown) {
9426 pw.println(" mShuttingDown=" + mShuttingDown);
9427 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009428 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9429 || mOrigWaitForDebugger) {
9430 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9431 + " mDebugTransient=" + mDebugTransient
9432 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9433 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009434 if (mOpenGlTraceApp != null) {
9435 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9436 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009437 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9438 || mProfileFd != null) {
9439 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9440 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9441 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9442 + mAutoStopProfiler);
9443 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009444 if (mAlwaysFinishActivities || mController != null) {
9445 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9446 + " mController=" + mController);
9447 }
9448 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009451 + " mProcessesReady=" + mProcessesReady
9452 + " mSystemReady=" + mSystemReady);
9453 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 + " mBooted=" + mBooted
9455 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009456 pw.print(" mLastPowerCheckRealtime=");
9457 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9458 pw.println("");
9459 pw.print(" mLastPowerCheckUptime=");
9460 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9461 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009462 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9463 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009464 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009465 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9466 + " mNumHiddenProcs=" + mNumHiddenProcs
9467 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009468 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009469 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009470
9471 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472 }
9473
Dianne Hackborn287952c2010-09-22 22:34:31 -07009474 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009475 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009476 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009477 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009478 long now = SystemClock.uptimeMillis();
9479 for (int i=0; i<mProcessesToGc.size(); i++) {
9480 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009481 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9482 continue;
9483 }
9484 if (!printed) {
9485 if (needSep) pw.println(" ");
9486 needSep = true;
9487 pw.println(" Processes that are waiting to GC:");
9488 printed = true;
9489 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009490 pw.print(" Process "); pw.println(proc);
9491 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9492 pw.print(", last gced=");
9493 pw.print(now-proc.lastRequestedGc);
9494 pw.print(" ms ago, last lowMem=");
9495 pw.print(now-proc.lastLowMemory);
9496 pw.println(" ms ago");
9497
9498 }
9499 }
9500 return needSep;
9501 }
9502
9503 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9504 int opti, boolean dumpAll) {
9505 boolean needSep = false;
9506
9507 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009508 if (needSep) pw.println(" ");
9509 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009510 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009511 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009512 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009513 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9514 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9515 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9516 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9517 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009518 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009519 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009520 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009521 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009522 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009523 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009524
9525 if (needSep) pw.println(" ");
9526 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009527 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009528 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009529 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009530 needSep = true;
9531 }
9532
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009533 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009534
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009535 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009536 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009537 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009538 if (mHeavyWeightProcess != null) {
9539 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9540 }
9541
9542 return true;
9543 }
9544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009545 /**
9546 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009547 * - no provider specified: dump all the providers
9548 * - a flattened component name that matched an existing provider was specified as the
9549 * first arg: dump that one provider
9550 * - the first arg isn't the flattened component name of an existing provider:
9551 * dump all providers whose component contains the first arg as a substring
9552 */
9553 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9554 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009555 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009556 }
9557
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009558 static class ItemMatcher {
9559 ArrayList<ComponentName> components;
9560 ArrayList<String> strings;
9561 ArrayList<Integer> objects;
9562 boolean all;
9563
9564 ItemMatcher() {
9565 all = true;
9566 }
9567
9568 void build(String name) {
9569 ComponentName componentName = ComponentName.unflattenFromString(name);
9570 if (componentName != null) {
9571 if (components == null) {
9572 components = new ArrayList<ComponentName>();
9573 }
9574 components.add(componentName);
9575 all = false;
9576 } else {
9577 int objectId = 0;
9578 // Not a '/' separated full component name; maybe an object ID?
9579 try {
9580 objectId = Integer.parseInt(name, 16);
9581 if (objects == null) {
9582 objects = new ArrayList<Integer>();
9583 }
9584 objects.add(objectId);
9585 all = false;
9586 } catch (RuntimeException e) {
9587 // Not an integer; just do string match.
9588 if (strings == null) {
9589 strings = new ArrayList<String>();
9590 }
9591 strings.add(name);
9592 all = false;
9593 }
9594 }
9595 }
9596
9597 int build(String[] args, int opti) {
9598 for (; opti<args.length; opti++) {
9599 String name = args[opti];
9600 if ("--".equals(name)) {
9601 return opti+1;
9602 }
9603 build(name);
9604 }
9605 return opti;
9606 }
9607
9608 boolean match(Object object, ComponentName comp) {
9609 if (all) {
9610 return true;
9611 }
9612 if (components != null) {
9613 for (int i=0; i<components.size(); i++) {
9614 if (components.get(i).equals(comp)) {
9615 return true;
9616 }
9617 }
9618 }
9619 if (objects != null) {
9620 for (int i=0; i<objects.size(); i++) {
9621 if (System.identityHashCode(object) == objects.get(i)) {
9622 return true;
9623 }
9624 }
9625 }
9626 if (strings != null) {
9627 String flat = comp.flattenToString();
9628 for (int i=0; i<strings.size(); i++) {
9629 if (flat.contains(strings.get(i))) {
9630 return true;
9631 }
9632 }
9633 }
9634 return false;
9635 }
9636 }
9637
Dianne Hackborn625ac272010-09-17 18:29:22 -07009638 /**
9639 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009640 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009641 * - the cmd arg isn't the flattened component name of an existing activity:
9642 * dump all activity whose component contains the cmd as a substring
9643 * - A hex number of the ActivityRecord object instance.
9644 */
9645 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9646 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009647 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009648
9649 if ("all".equals(name)) {
9650 synchronized (this) {
9651 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009652 activities.add(r1);
9653 }
9654 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009655 } else if ("top".equals(name)) {
9656 synchronized (this) {
9657 final int N = mMainStack.mHistory.size();
9658 if (N > 0) {
9659 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9660 }
9661 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009662 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009663 ItemMatcher matcher = new ItemMatcher();
9664 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009665
9666 synchronized (this) {
9667 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009668 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009669 activities.add(r1);
9670 }
9671 }
9672 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009673 }
9674
9675 if (activities.size() <= 0) {
9676 return false;
9677 }
9678
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009679 String[] newArgs = new String[args.length - opti];
9680 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9681
Dianne Hackborn30d71892010-12-11 10:37:55 -08009682 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009683 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009684 for (int i=activities.size()-1; i>=0; i--) {
9685 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009686 if (needSep) {
9687 pw.println();
9688 }
9689 needSep = true;
9690 synchronized (this) {
9691 if (lastTask != r.task) {
9692 lastTask = r.task;
9693 pw.print("TASK "); pw.print(lastTask.affinity);
9694 pw.print(" id="); pw.println(lastTask.taskId);
9695 if (dumpAll) {
9696 lastTask.dump(pw, " ");
9697 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009698 }
9699 }
9700 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009701 }
9702 return true;
9703 }
9704
9705 /**
9706 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9707 * there is a thread associated with the activity.
9708 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009709 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009710 final ActivityRecord r, String[] args, boolean dumpAll) {
9711 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009712 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009713 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9714 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9715 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009716 if (r.app != null) pw.println(r.app.pid);
9717 else pw.println("(not running)");
9718 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009719 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009720 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009721 }
9722 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009723 // flush anything that is already in the PrintWriter since the thread is going
9724 // to write to the file descriptor directly
9725 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009726 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009727 TransferPipe tp = new TransferPipe();
9728 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009729 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9730 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009731 tp.go(fd);
9732 } finally {
9733 tp.kill();
9734 }
9735 } catch (IOException e) {
9736 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009737 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009738 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009739 }
9740 }
9741 }
9742
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009743 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009744 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009745 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009746 boolean onlyHistory = false;
9747
9748 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009749 if (opti < args.length && "-s".equals(args[opti])) {
9750 dumpAll = false;
9751 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009752 onlyHistory = true;
9753 dumpPackage = null;
9754 }
9755
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009756 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009757 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009758 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009759 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009760 Iterator it = mRegisteredReceivers.values().iterator();
9761 while (it.hasNext()) {
9762 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009763 if (dumpPackage != null && (r.app == null ||
9764 !dumpPackage.equals(r.app.info.packageName))) {
9765 continue;
9766 }
9767 if (!printed) {
9768 pw.println(" Registered Receivers:");
9769 needSep = true;
9770 printed = true;
9771 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009772 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009773 r.dump(pw, " ");
9774 }
9775 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009776
9777 if (mReceiverResolver.dump(pw, needSep ?
9778 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9779 " ", dumpPackage, false)) {
9780 needSep = true;
9781 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009782 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009783
9784 for (BroadcastQueue q : mBroadcastQueues) {
9785 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009787
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009788 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009789
Dianne Hackborn786b4402012-08-27 15:14:02 -07009790 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009791 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9792 if (needSep) {
9793 pw.println();
9794 }
9795 needSep = true;
9796 pw.print(" Sticky broadcasts for user ");
9797 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9798 StringBuilder sb = new StringBuilder(128);
9799 for (Map.Entry<String, ArrayList<Intent>> ent
9800 : mStickyBroadcasts.valueAt(user).entrySet()) {
9801 pw.print(" * Sticky action "); pw.print(ent.getKey());
9802 if (dumpAll) {
9803 pw.println(":");
9804 ArrayList<Intent> intents = ent.getValue();
9805 final int N = intents.size();
9806 for (int i=0; i<N; i++) {
9807 sb.setLength(0);
9808 sb.append(" Intent: ");
9809 intents.get(i).toShortString(sb, false, true, false, false);
9810 pw.println(sb.toString());
9811 Bundle bundle = intents.get(i).getExtras();
9812 if (bundle != null) {
9813 pw.print(" ");
9814 pw.println(bundle.toString());
9815 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009816 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009817 } else {
9818 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009819 }
9820 }
9821 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009822 }
9823
Dianne Hackborn786b4402012-08-27 15:14:02 -07009824 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009825 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009826 for (BroadcastQueue queue : mBroadcastQueues) {
9827 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9828 + queue.mBroadcastsScheduled);
9829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009830 pw.println(" mHandler:");
9831 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009832 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009833 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009834
9835 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 }
9837
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009838 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009839 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009840 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009842 ItemMatcher matcher = new ItemMatcher();
9843 matcher.build(args, opti);
9844
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009845 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009846
9847 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009848
9849 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009850 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009851 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009852 ContentProviderRecord r = mLaunchingProviders.get(i);
9853 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9854 continue;
9855 }
9856 if (!printed) {
9857 if (needSep) pw.println(" ");
9858 needSep = true;
9859 pw.println(" Launching content providers:");
9860 printed = true;
9861 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009862 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009863 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009864 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009865 }
9866
9867 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009868 if (needSep) pw.println();
9869 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009870 pw.println("Granted Uri Permissions:");
9871 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9872 int uid = mGrantedUriPermissions.keyAt(i);
9873 HashMap<Uri, UriPermission> perms
9874 = mGrantedUriPermissions.valueAt(i);
9875 pw.print(" * UID "); pw.print(uid);
9876 pw.println(" holds:");
9877 for (UriPermission perm : perms.values()) {
9878 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009879 if (dumpAll) {
9880 perm.dump(pw, " ");
9881 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009882 }
9883 }
9884 needSep = true;
9885 }
9886
9887 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009888 }
9889
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009890 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009891 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009892 boolean needSep = false;
9893
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009894 if (mIntentSenderRecords.size() > 0) {
9895 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009896 Iterator<WeakReference<PendingIntentRecord>> it
9897 = mIntentSenderRecords.values().iterator();
9898 while (it.hasNext()) {
9899 WeakReference<PendingIntentRecord> ref = it.next();
9900 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009901 if (dumpPackage != null && (rec == null
9902 || !dumpPackage.equals(rec.key.packageName))) {
9903 continue;
9904 }
9905 if (!printed) {
9906 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9907 printed = true;
9908 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009909 needSep = true;
9910 if (rec != null) {
9911 pw.print(" * "); pw.println(rec);
9912 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009913 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009914 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009915 } else {
9916 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009917 }
9918 }
9919 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009920
9921 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 }
9923
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009924 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009925 String prefix, String label, boolean complete, boolean brief, boolean client,
9926 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009928 boolean needNL = false;
9929 final String innerPrefix = prefix + " ";
9930 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009931 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009932 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009933 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9934 continue;
9935 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009936 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009937 if (needNL) {
9938 pw.println(" ");
9939 needNL = false;
9940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009941 if (lastTask != r.task) {
9942 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009943 pw.print(prefix);
9944 pw.print(full ? "* " : " ");
9945 pw.println(lastTask);
9946 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009947 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009948 } else if (complete) {
9949 // Complete + brief == give a summary. Isn't that obvious?!?
9950 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009951 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009952 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009953 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009956 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9957 pw.print(" #"); pw.print(i); pw.print(": ");
9958 pw.println(r);
9959 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009960 r.dump(pw, innerPrefix);
9961 } else if (complete) {
9962 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009963 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009964 if (r.app != null) {
9965 pw.print(innerPrefix); pw.println(r.app);
9966 }
9967 }
9968 if (client && r.app != null && r.app.thread != null) {
9969 // flush anything that is already in the PrintWriter since the thread is going
9970 // to write to the file descriptor directly
9971 pw.flush();
9972 try {
9973 TransferPipe tp = new TransferPipe();
9974 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009975 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9976 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009977 // Short timeout, since blocking here can
9978 // deadlock with the application.
9979 tp.go(fd, 2000);
9980 } finally {
9981 tp.kill();
9982 }
9983 } catch (IOException e) {
9984 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9985 } catch (RemoteException e) {
9986 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9987 }
9988 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009990 }
9991 }
9992
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009993 private static String buildOomTag(String prefix, String space, int val, int base) {
9994 if (val == base) {
9995 if (space == null) return prefix;
9996 return prefix + " ";
9997 }
9998 return prefix + "+" + Integer.toString(val-base);
9999 }
10000
10001 private static final int dumpProcessList(PrintWriter pw,
10002 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010003 String prefix, String normalLabel, String persistentLabel,
10004 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010005 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010006 final int N = list.size()-1;
10007 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010009 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10010 continue;
10011 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010012 pw.println(String.format("%s%s #%2d: %s",
10013 prefix, (r.persistent ? persistentLabel : normalLabel),
10014 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010015 if (r.persistent) {
10016 numPers++;
10017 }
10018 }
10019 return numPers;
10020 }
10021
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010022 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010023 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010024 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010025 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010026
Dianne Hackborn905577f2011-09-07 18:31:28 -070010027 ArrayList<Pair<ProcessRecord, Integer>> list
10028 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10029 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010030 ProcessRecord r = origList.get(i);
10031 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10032 continue;
10033 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010034 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10035 }
10036
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010037 if (list.size() <= 0) {
10038 return false;
10039 }
10040
Dianne Hackborn905577f2011-09-07 18:31:28 -070010041 Comparator<Pair<ProcessRecord, Integer>> comparator
10042 = new Comparator<Pair<ProcessRecord, Integer>>() {
10043 @Override
10044 public int compare(Pair<ProcessRecord, Integer> object1,
10045 Pair<ProcessRecord, Integer> object2) {
10046 if (object1.first.setAdj != object2.first.setAdj) {
10047 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10048 }
10049 if (object1.second.intValue() != object2.second.intValue()) {
10050 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10051 }
10052 return 0;
10053 }
10054 };
10055
10056 Collections.sort(list, comparator);
10057
Dianne Hackborn287952c2010-09-22 22:34:31 -070010058 final long curRealtime = SystemClock.elapsedRealtime();
10059 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10060 final long curUptime = SystemClock.uptimeMillis();
10061 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10062
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010063 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010064 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010065 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010066 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010067 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010068 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10069 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010070 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10071 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010072 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10073 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010074 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10075 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010076 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010077 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010078 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10079 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10080 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10081 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10082 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10083 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10084 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10085 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010086 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10087 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010088 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10089 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010090 } else {
10091 oomAdj = Integer.toString(r.setAdj);
10092 }
10093 String schedGroup;
10094 switch (r.setSchedGroup) {
10095 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10096 schedGroup = "B";
10097 break;
10098 case Process.THREAD_GROUP_DEFAULT:
10099 schedGroup = "F";
10100 break;
10101 default:
10102 schedGroup = Integer.toString(r.setSchedGroup);
10103 break;
10104 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010105 String foreground;
10106 if (r.foregroundActivities) {
10107 foreground = "A";
10108 } else if (r.foregroundServices) {
10109 foreground = "S";
10110 } else {
10111 foreground = " ";
10112 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010113 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010114 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010115 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10116 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010117 if (r.adjSource != null || r.adjTarget != null) {
10118 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010119 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010120 if (r.adjTarget instanceof ComponentName) {
10121 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10122 } else if (r.adjTarget != null) {
10123 pw.print(r.adjTarget.toString());
10124 } else {
10125 pw.print("{null}");
10126 }
10127 pw.print("<=");
10128 if (r.adjSource instanceof ProcessRecord) {
10129 pw.print("Proc{");
10130 pw.print(((ProcessRecord)r.adjSource).toShortString());
10131 pw.println("}");
10132 } else if (r.adjSource != null) {
10133 pw.println(r.adjSource.toString());
10134 } else {
10135 pw.println("{null}");
10136 }
10137 }
10138 if (inclDetails) {
10139 pw.print(prefix);
10140 pw.print(" ");
10141 pw.print("oom: max="); pw.print(r.maxAdj);
10142 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010143 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010144 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010145 pw.print(" curRaw="); pw.print(r.curRawAdj);
10146 pw.print(" setRaw="); pw.print(r.setRawAdj);
10147 pw.print(" cur="); pw.print(r.curAdj);
10148 pw.print(" set="); pw.println(r.setAdj);
10149 pw.print(prefix);
10150 pw.print(" ");
10151 pw.print("keeping="); pw.print(r.keeping);
10152 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010153 pw.print(" empty="); pw.print(r.empty);
10154 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010155
10156 if (!r.keeping) {
10157 if (r.lastWakeTime != 0) {
10158 long wtime;
10159 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10160 synchronized (stats) {
10161 wtime = stats.getProcessWakeTime(r.info.uid,
10162 r.pid, curRealtime);
10163 }
10164 long timeUsed = wtime - r.lastWakeTime;
10165 pw.print(prefix);
10166 pw.print(" ");
10167 pw.print("keep awake over ");
10168 TimeUtils.formatDuration(realtimeSince, pw);
10169 pw.print(" used ");
10170 TimeUtils.formatDuration(timeUsed, pw);
10171 pw.print(" (");
10172 pw.print((timeUsed*100)/realtimeSince);
10173 pw.println("%)");
10174 }
10175 if (r.lastCpuTime != 0) {
10176 long timeUsed = r.curCpuTime - r.lastCpuTime;
10177 pw.print(prefix);
10178 pw.print(" ");
10179 pw.print("run cpu over ");
10180 TimeUtils.formatDuration(uptimeSince, pw);
10181 pw.print(" used ");
10182 TimeUtils.formatDuration(timeUsed, pw);
10183 pw.print(" (");
10184 pw.print((timeUsed*100)/uptimeSince);
10185 pw.println("%)");
10186 }
10187 }
10188 }
10189 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010190 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010191 }
10192
Dianne Hackbornb437e092011-08-05 17:50:29 -070010193 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010194 ArrayList<ProcessRecord> procs;
10195 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010196 if (args != null && args.length > start
10197 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010198 procs = new ArrayList<ProcessRecord>();
10199 int pid = -1;
10200 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010201 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010202 } catch (NumberFormatException e) {
10203
10204 }
10205 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10206 ProcessRecord proc = mLruProcesses.get(i);
10207 if (proc.pid == pid) {
10208 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010209 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010210 procs.add(proc);
10211 }
10212 }
10213 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010214 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010215 return null;
10216 }
10217 } else {
10218 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10219 }
10220 }
10221 return procs;
10222 }
10223
10224 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10225 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010226 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010227 if (procs == null) {
10228 return;
10229 }
10230
10231 long uptime = SystemClock.uptimeMillis();
10232 long realtime = SystemClock.elapsedRealtime();
10233 pw.println("Applications Graphics Acceleration Info:");
10234 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10235
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010236 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10237 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010238 if (r.thread != null) {
10239 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10240 pw.flush();
10241 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010242 TransferPipe tp = new TransferPipe();
10243 try {
10244 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10245 tp.go(fd);
10246 } finally {
10247 tp.kill();
10248 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010249 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010250 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010251 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010252 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010253 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010254 pw.flush();
10255 }
10256 }
10257 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010258 }
10259
Jeff Brown6754ba22011-12-14 20:20:01 -080010260 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10261 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10262 if (procs == null) {
10263 return;
10264 }
10265
10266 pw.println("Applications Database Info:");
10267
10268 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10269 ProcessRecord r = procs.get(i);
10270 if (r.thread != null) {
10271 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10272 pw.flush();
10273 try {
10274 TransferPipe tp = new TransferPipe();
10275 try {
10276 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10277 tp.go(fd);
10278 } finally {
10279 tp.kill();
10280 }
10281 } catch (IOException e) {
10282 pw.println("Failure while dumping the app: " + r);
10283 pw.flush();
10284 } catch (RemoteException e) {
10285 pw.println("Got a RemoteException while dumping the app " + r);
10286 pw.flush();
10287 }
10288 }
10289 }
10290 }
10291
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010292 final static class MemItem {
10293 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010294 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010295 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010296 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010297 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010298
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010299 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010300 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010301 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010302 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010303 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010304 }
10305 }
10306
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010307 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010308 boolean sort) {
10309 if (sort) {
10310 Collections.sort(items, new Comparator<MemItem>() {
10311 @Override
10312 public int compare(MemItem lhs, MemItem rhs) {
10313 if (lhs.pss < rhs.pss) {
10314 return 1;
10315 } else if (lhs.pss > rhs.pss) {
10316 return -1;
10317 }
10318 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010319 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320 });
10321 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010322
10323 for (int i=0; i<items.size(); i++) {
10324 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010325 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010326 if (mi.subitems != null) {
10327 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10328 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010329 }
10330 }
10331
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010332 // These are in KB.
10333 static final long[] DUMP_MEM_BUCKETS = new long[] {
10334 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10335 120*1024, 160*1024, 200*1024,
10336 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10337 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10338 };
10339
Dianne Hackborn672342c2011-11-29 11:29:02 -080010340 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10341 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010342 int start = label.lastIndexOf('.');
10343 if (start >= 0) start++;
10344 else start = 0;
10345 int end = label.length();
10346 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10347 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10348 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10349 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010350 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010351 out.append(label, start, end);
10352 return;
10353 }
10354 }
10355 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010356 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010357 out.append(label, start, end);
10358 }
10359
10360 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10361 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10362 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10363 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10364 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10365 };
10366 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10367 "System", "Persistent", "Foreground",
10368 "Visible", "Perceptible", "Heavy Weight",
10369 "Backup", "A Services", "Home", "Previous",
10370 "B Services", "Background"
10371 };
10372
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010373 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010374 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010375 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010376 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010377 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010378
10379 int opti = 0;
10380 while (opti < args.length) {
10381 String opt = args[opti];
10382 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10383 break;
10384 }
10385 opti++;
10386 if ("-a".equals(opt)) {
10387 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010388 } else if ("--oom".equals(opt)) {
10389 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010390 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010391 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010392 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010393 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010394 pw.println("If [process] is specified it can be the name or ");
10395 pw.println("pid of a specific process to dump.");
10396 return;
10397 } else {
10398 pw.println("Unknown argument: " + opt + "; use -h for help");
10399 }
10400 }
10401
10402 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010403 if (procs == null) {
10404 return;
10405 }
10406
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010407 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010408 long uptime = SystemClock.uptimeMillis();
10409 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010410
10411 if (procs.size() == 1 || isCheckinRequest) {
10412 dumpAll = true;
10413 }
10414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 if (isCheckinRequest) {
10416 // short checkin version
10417 pw.println(uptime + "," + realtime);
10418 pw.flush();
10419 } else {
10420 pw.println("Applications Memory Usage (kB):");
10421 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10422 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010423
Dianne Hackbornb437e092011-08-05 17:50:29 -070010424 String[] innerArgs = new String[args.length-opti];
10425 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10426
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010427 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10428 long nativePss=0, dalvikPss=0, otherPss=0;
10429 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10430
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010431 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10432 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10433 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010434
10435 long totalPss = 0;
10436
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010437 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10438 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010440 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010441 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10442 pw.flush();
10443 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010444 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010445 if (dumpAll) {
10446 try {
10447 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10448 } catch (RemoteException e) {
10449 if (!isCheckinRequest) {
10450 pw.println("Got RemoteException!");
10451 pw.flush();
10452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010453 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010454 } else {
10455 mi = new Debug.MemoryInfo();
10456 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010458
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010459 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010460 long myTotalPss = mi.getTotalPss();
10461 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010462 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010463 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010464 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010465
10466 nativePss += mi.nativePss;
10467 dalvikPss += mi.dalvikPss;
10468 otherPss += mi.otherPss;
10469 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10470 long mem = mi.getOtherPss(j);
10471 miscPss[j] += mem;
10472 otherPss -= mem;
10473 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010474
10475 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010476 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10477 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010478 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010479 if (oomProcs[oomIndex] == null) {
10480 oomProcs[oomIndex] = new ArrayList<MemItem>();
10481 }
10482 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010483 break;
10484 }
10485 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010487 }
10488 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010489
10490 if (!isCheckinRequest && procs.size() > 1) {
10491 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10492
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010493 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10494 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10495 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010496 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010497 String label = Debug.MemoryInfo.getOtherLabel(j);
10498 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010499 }
10500
Dianne Hackbornb437e092011-08-05 17:50:29 -070010501 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10502 for (int j=0; j<oomPss.length; j++) {
10503 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010504 String label = DUMP_MEM_OOM_LABEL[j];
10505 MemItem item = new MemItem(label, label, oomPss[j],
10506 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010507 item.subitems = oomProcs[j];
10508 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010509 }
10510 }
10511
Dianne Hackborn672342c2011-11-29 11:29:02 -080010512 if (outTag != null || outStack != null) {
10513 if (outTag != null) {
10514 appendMemBucket(outTag, totalPss, "total", false);
10515 }
10516 if (outStack != null) {
10517 appendMemBucket(outStack, totalPss, "total", true);
10518 }
10519 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010520 for (int i=0; i<oomMems.size(); i++) {
10521 MemItem miCat = oomMems.get(i);
10522 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10523 continue;
10524 }
10525 if (miCat.id < ProcessList.SERVICE_ADJ
10526 || miCat.id == ProcessList.HOME_APP_ADJ
10527 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010528 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10529 outTag.append(" / ");
10530 }
10531 if (outStack != null) {
10532 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10533 if (firstLine) {
10534 outStack.append(":");
10535 firstLine = false;
10536 }
10537 outStack.append("\n\t at ");
10538 } else {
10539 outStack.append("$");
10540 }
10541 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010542 for (int j=0; j<miCat.subitems.size(); j++) {
10543 MemItem mi = miCat.subitems.get(j);
10544 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010545 if (outTag != null) {
10546 outTag.append(" ");
10547 }
10548 if (outStack != null) {
10549 outStack.append("$");
10550 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010551 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010552 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10553 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10554 }
10555 if (outStack != null) {
10556 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10557 }
10558 }
10559 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10560 outStack.append("(");
10561 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10562 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10563 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10564 outStack.append(":");
10565 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10566 }
10567 }
10568 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010569 }
10570 }
10571 }
10572 }
10573
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010574 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010575 pw.println();
10576 pw.println("Total PSS by process:");
10577 dumpMemItems(pw, " ", procMems, true);
10578 pw.println();
10579 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010580 pw.println("Total PSS by OOM adjustment:");
10581 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010582 if (!oomOnly) {
10583 PrintWriter out = categoryPw != null ? categoryPw : pw;
10584 out.println();
10585 out.println("Total PSS by category:");
10586 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010587 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010588 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010589 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010590 final int[] SINGLE_LONG_FORMAT = new int[] {
10591 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10592 };
10593 long[] longOut = new long[1];
10594 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10595 SINGLE_LONG_FORMAT, null, longOut, null);
10596 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10597 longOut[0] = 0;
10598 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10599 SINGLE_LONG_FORMAT, null, longOut, null);
10600 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10601 longOut[0] = 0;
10602 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10603 SINGLE_LONG_FORMAT, null, longOut, null);
10604 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10605 longOut[0] = 0;
10606 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10607 SINGLE_LONG_FORMAT, null, longOut, null);
10608 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10609 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10610 pw.print(shared); pw.println(" kB");
10611 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10612 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 }
10615
10616 /**
10617 * Searches array of arguments for the specified string
10618 * @param args array of argument strings
10619 * @param value value to search for
10620 * @return true if the value is contained in the array
10621 */
10622 private static boolean scanArgs(String[] args, String value) {
10623 if (args != null) {
10624 for (String arg : args) {
10625 if (value.equals(arg)) {
10626 return true;
10627 }
10628 }
10629 }
10630 return false;
10631 }
10632
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010633 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10634 ContentProviderRecord cpr, boolean always) {
10635 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10636
10637 if (!inLaunching || always) {
10638 synchronized (cpr) {
10639 cpr.launchingApp = null;
10640 cpr.notifyAll();
10641 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010642 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010643 String names[] = cpr.info.authority.split(";");
10644 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010645 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 }
10647 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010648
10649 for (int i=0; i<cpr.connections.size(); i++) {
10650 ContentProviderConnection conn = cpr.connections.get(i);
10651 if (conn.waiting) {
10652 // If this connection is waiting for the provider, then we don't
10653 // need to mess with its process unless we are always removing
10654 // or for some reason the provider is not currently launching.
10655 if (inLaunching && !always) {
10656 continue;
10657 }
10658 }
10659 ProcessRecord capp = conn.client;
10660 conn.dead = true;
10661 if (conn.stableCount > 0) {
10662 if (!capp.persistent && capp.thread != null
10663 && capp.pid != 0
10664 && capp.pid != MY_PID) {
10665 Slog.i(TAG, "Kill " + capp.processName
10666 + " (pid " + capp.pid + "): provider " + cpr.info.name
10667 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010668 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010669 capp.processName, capp.setAdj, "dying provider "
10670 + cpr.name.toShortString());
10671 Process.killProcessQuiet(capp.pid);
10672 }
10673 } else if (capp.thread != null && conn.provider.provider != null) {
10674 try {
10675 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10676 } catch (RemoteException e) {
10677 }
10678 // In the protocol here, we don't expect the client to correctly
10679 // clean up this connection, we'll just remove it.
10680 cpr.connections.remove(i);
10681 conn.client.conProviders.remove(conn);
10682 }
10683 }
10684
10685 if (inLaunching && always) {
10686 mLaunchingProviders.remove(cpr);
10687 }
10688 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 }
10690
10691 /**
10692 * Main code for cleaning up a process when it has gone away. This is
10693 * called both as a result of the process dying, or directly when stopping
10694 * a process when running in single process mode.
10695 */
10696 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010697 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010698 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010699 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 }
10701
Dianne Hackborn36124872009-10-08 16:22:03 -070010702 mProcessesToGc.remove(app);
10703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010704 // Dismiss any open dialogs.
10705 if (app.crashDialog != null) {
10706 app.crashDialog.dismiss();
10707 app.crashDialog = null;
10708 }
10709 if (app.anrDialog != null) {
10710 app.anrDialog.dismiss();
10711 app.anrDialog = null;
10712 }
10713 if (app.waitDialog != null) {
10714 app.waitDialog.dismiss();
10715 app.waitDialog = null;
10716 }
10717
10718 app.crashing = false;
10719 app.notResponding = false;
10720
10721 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010722 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010723 app.thread = null;
10724 app.forcingToForeground = null;
10725 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010726 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010727 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010728 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010730 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010731
10732 boolean restart = false;
10733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 // Remove published content providers.
10735 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010736 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010737 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010738 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010739
10740 final boolean always = app.bad || !allowRestart;
10741 if (removeDyingProviderLocked(app, cpr, always) || always) {
10742 // We left the provider in the launching list, need to
10743 // restart it.
10744 restart = true;
10745 }
10746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010747 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010748 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 }
10750 app.pubProviders.clear();
10751 }
10752
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010753 // Take care of any launching providers waiting for this process.
10754 if (checkAppInLaunchingProvidersLocked(app, false)) {
10755 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010758 // Unregister from connected content providers.
10759 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010760 for (int i=0; i<app.conProviders.size(); i++) {
10761 ContentProviderConnection conn = app.conProviders.get(i);
10762 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 }
10764 app.conProviders.clear();
10765 }
10766
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010767 // At this point there may be remaining entries in mLaunchingProviders
10768 // where we were the only one waiting, so they are no longer of use.
10769 // Look for these and clean up if found.
10770 // XXX Commented out for now. Trying to figure out a way to reproduce
10771 // the actual situation to identify what is actually going on.
10772 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010773 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010774 ContentProviderRecord cpr = (ContentProviderRecord)
10775 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010776 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010777 synchronized (cpr) {
10778 cpr.launchingApp = null;
10779 cpr.notifyAll();
10780 }
10781 }
10782 }
10783 }
10784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010785 skipCurrentReceiverLocked(app);
10786
10787 // Unregister any receivers.
10788 if (app.receivers.size() > 0) {
10789 Iterator<ReceiverList> it = app.receivers.iterator();
10790 while (it.hasNext()) {
10791 removeReceiverLocked(it.next());
10792 }
10793 app.receivers.clear();
10794 }
10795
Christopher Tate181fafa2009-05-14 11:12:14 -070010796 // If the app is undergoing backup, tell the backup manager about it
10797 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010798 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10799 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010800 try {
10801 IBackupManager bm = IBackupManager.Stub.asInterface(
10802 ServiceManager.getService(Context.BACKUP_SERVICE));
10803 bm.agentDisconnected(app.info.packageName);
10804 } catch (RemoteException e) {
10805 // can't happen; backup manager is local
10806 }
10807 }
10808
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010809 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10810 ProcessChangeItem item = mPendingProcessChanges.get(i);
10811 if (item.pid == app.pid) {
10812 mPendingProcessChanges.remove(i);
10813 mAvailProcessChanges.add(item);
10814 }
10815 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010816 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 // If the caller is restarting this app, then leave it in its
10819 // current lists and let the caller take care of it.
10820 if (restarting) {
10821 return;
10822 }
10823
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010824 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010825 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010827 mProcessNames.remove(app.processName, app.uid);
10828 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010829 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010830 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10831 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010832 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834 } else if (!app.removed) {
10835 // This app is persistent, so we need to keep its record around.
10836 // If it is not already on the pending app list, add it there
10837 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10839 mPersistentStartingProcesses.add(app);
10840 restart = true;
10841 }
10842 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010843 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010844 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 mProcessesOnHold.remove(app);
10846
The Android Open Source Project4df24232009-03-05 14:34:35 -080010847 if (app == mHomeProcess) {
10848 mHomeProcess = null;
10849 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010850 if (app == mPreviousProcess) {
10851 mPreviousProcess = null;
10852 }
10853
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010854 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855 // We have components that still need to be running in the
10856 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010857 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 startProcessLocked(app, "restart", app.processName);
10859 } else if (app.pid > 0 && app.pid != MY_PID) {
10860 // Goodbye!
10861 synchronized (mPidsSelfLocked) {
10862 mPidsSelfLocked.remove(app.pid);
10863 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10864 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010865 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 }
10867 }
10868
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010869 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10870 // Look through the content providers we are waiting to have launched,
10871 // and if any run in this process then either schedule a restart of
10872 // the process or kill the client waiting for it if this process has
10873 // gone bad.
10874 int NL = mLaunchingProviders.size();
10875 boolean restart = false;
10876 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010877 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010878 if (cpr.launchingApp == app) {
10879 if (!alwaysBad && !app.bad) {
10880 restart = true;
10881 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010882 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010883 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010884 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010885 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010886 }
10887 }
10888 }
10889 return restart;
10890 }
10891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 // =========================================================
10893 // SERVICES
10894 // =========================================================
10895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010896 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10897 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010898 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010899 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010900 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 }
10902 }
10903
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010904 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010905 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010906 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010907 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010908 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010909 }
10910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010911 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010912 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010913 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010914 // Refuse possible leaked file descriptors
10915 if (service != null && service.hasFileDescriptors() == true) {
10916 throw new IllegalArgumentException("File descriptors passed in Intent");
10917 }
10918
Amith Yamasani742a6712011-05-04 14:49:28 -070010919 if (DEBUG_SERVICE)
10920 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010921 synchronized(this) {
10922 final int callingPid = Binder.getCallingPid();
10923 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010924 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010925 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010926 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010927 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 Binder.restoreCallingIdentity(origId);
10929 return res;
10930 }
10931 }
10932
10933 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010934 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010935 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010936 if (DEBUG_SERVICE)
10937 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010939 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010940 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941 Binder.restoreCallingIdentity(origId);
10942 return res;
10943 }
10944 }
10945
10946 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010947 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010948 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010949 // Refuse possible leaked file descriptors
10950 if (service != null && service.hasFileDescriptors() == true) {
10951 throw new IllegalArgumentException("File descriptors passed in Intent");
10952 }
10953
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010954 checkValidCaller(Binder.getCallingUid(), userId);
10955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010957 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 }
10960
10961 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010962 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 // Refuse possible leaked file descriptors
10964 if (service != null && service.hasFileDescriptors() == true) {
10965 throw new IllegalArgumentException("File descriptors passed in Intent");
10966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010967 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010968 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 }
10971
10972 public boolean stopServiceToken(ComponentName className, IBinder token,
10973 int startId) {
10974 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010975 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 }
10978
10979 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010980 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010982 mServices.setServiceForegroundLocked(className, token, id, notification,
10983 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 }
10985 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010986
Dianne Hackborn41203752012-08-31 14:05:51 -070010987 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10988 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010989 final int callingUserId = UserHandle.getUserId(callingUid);
10990 if (callingUserId != userId) {
10991 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10992 if ((requireFull || checkComponentPermission(
10993 android.Manifest.permission.INTERACT_ACROSS_USERS,
10994 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10995 && checkComponentPermission(
10996 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10997 callingPid, callingUid, -1, true)
10998 != PackageManager.PERMISSION_GRANTED) {
10999 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11000 // In this case, they would like to just execute as their
11001 // owner user instead of failing.
11002 userId = callingUserId;
11003 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011004 StringBuilder builder = new StringBuilder(128);
11005 builder.append("Permission Denial: ");
11006 builder.append(name);
11007 if (callerPackage != null) {
11008 builder.append(" from ");
11009 builder.append(callerPackage);
11010 }
11011 builder.append(" asks to run as user ");
11012 builder.append(userId);
11013 builder.append(" but is calling from user ");
11014 builder.append(UserHandle.getUserId(callingUid));
11015 builder.append("; this requires ");
11016 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11017 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011018 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011019 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11020 }
11021 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011022 Slog.w(TAG, msg);
11023 throw new SecurityException(msg);
11024 }
11025 }
11026 }
11027 if (userId == UserHandle.USER_CURRENT
11028 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011029 // Note that we may be accessing this outside of a lock...
11030 // shouldn't be a big deal, if this is being called outside
11031 // of a locked context there is intrinsically a race with
11032 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011033 userId = mCurrentUserId;
11034 }
11035 if (!allowAll && userId < 0) {
11036 throw new IllegalArgumentException(
11037 "Call does not support special user #" + userId);
11038 }
11039 }
11040 return userId;
11041 }
11042
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011043 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11044 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011045 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011046 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011047 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11048 if (ActivityManager.checkUidPermission(
11049 android.Manifest.permission.INTERACT_ACROSS_USERS,
11050 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11051 ComponentName comp = new ComponentName(aInfo.packageName, className);
11052 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11053 + " requests FLAG_SINGLE_USER, but app does not hold "
11054 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11055 Slog.w(TAG, msg);
11056 throw new SecurityException(msg);
11057 }
11058 result = true;
11059 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011060 } else if (componentProcessName == aInfo.packageName) {
11061 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11062 } else if ("system".equals(componentProcessName)) {
11063 result = true;
11064 }
11065 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011066 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11067 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011068 }
11069 return result;
11070 }
11071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 public int bindService(IApplicationThread caller, IBinder token,
11073 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011074 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011075 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011076 // Refuse possible leaked file descriptors
11077 if (service != null && service.hasFileDescriptors() == true) {
11078 throw new IllegalArgumentException("File descriptors passed in Intent");
11079 }
11080
11081 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011082 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11083 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 }
11085 }
11086
11087 public boolean unbindService(IServiceConnection connection) {
11088 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011089 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 }
11092
11093 public void publishService(IBinder token, Intent intent, IBinder service) {
11094 // Refuse possible leaked file descriptors
11095 if (intent != null && intent.hasFileDescriptors() == true) {
11096 throw new IllegalArgumentException("File descriptors passed in Intent");
11097 }
11098
11099 synchronized(this) {
11100 if (!(token instanceof ServiceRecord)) {
11101 throw new IllegalArgumentException("Invalid service token");
11102 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011103 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 }
11105 }
11106
11107 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11108 // Refuse possible leaked file descriptors
11109 if (intent != null && intent.hasFileDescriptors() == true) {
11110 throw new IllegalArgumentException("File descriptors passed in Intent");
11111 }
11112
11113 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011114 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011115 }
11116 }
11117
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011118 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011119 synchronized(this) {
11120 if (!(token instanceof ServiceRecord)) {
11121 throw new IllegalArgumentException("Invalid service token");
11122 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011123 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011125 }
11126
11127 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011128 // BACKUP AND RESTORE
11129 // =========================================================
11130
11131 // Cause the target app to be launched if necessary and its backup agent
11132 // instantiated. The backup agent will invoke backupAgentCreated() on the
11133 // activity manager to announce its creation.
11134 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011135 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11136 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011137
11138 synchronized(this) {
11139 // !!! TODO: currently no check here that we're already bound
11140 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11141 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11142 synchronized (stats) {
11143 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11144 }
11145
Dianne Hackborne7f97212011-02-24 14:40:20 -080011146 // Backup agent is now in use, its package can't be stopped.
11147 try {
11148 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011149 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011150 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011151 } catch (IllegalArgumentException e) {
11152 Slog.w(TAG, "Failed trying to unstop package "
11153 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011154 }
11155
Christopher Tate181fafa2009-05-14 11:12:14 -070011156 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011157 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11158 ? new ComponentName(app.packageName, app.backupAgentName)
11159 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011160 // startProcessLocked() returns existing proc's record if it's already running
11161 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011162 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011163 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011164 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011165 return false;
11166 }
11167
11168 r.app = proc;
11169 mBackupTarget = r;
11170 mBackupAppName = app.packageName;
11171
Christopher Tate6fa95972009-06-05 18:43:55 -070011172 // Try not to kill the process during backup
11173 updateOomAdjLocked(proc);
11174
Christopher Tate181fafa2009-05-14 11:12:14 -070011175 // If the process is already attached, schedule the creation of the backup agent now.
11176 // If it is not yet live, this will be done when it attaches to the framework.
11177 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011178 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011179 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011180 proc.thread.scheduleCreateBackupAgent(app,
11181 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011182 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011183 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011184 }
11185 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011186 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011187 }
11188 // Invariants: at this point, the target app process exists and the application
11189 // is either already running or in the process of coming up. mBackupTarget and
11190 // mBackupAppName describe the app, so that when it binds back to the AM we
11191 // know that it's scheduled for a backup-agent operation.
11192 }
11193
11194 return true;
11195 }
11196
Christopher Tate346acb12012-10-15 19:20:25 -070011197 @Override
11198 public void clearPendingBackup() {
11199 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11200 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11201
11202 synchronized (this) {
11203 mBackupTarget = null;
11204 mBackupAppName = null;
11205 }
11206 }
11207
Christopher Tate181fafa2009-05-14 11:12:14 -070011208 // A backup agent has just come up
11209 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011210 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011211 + " = " + agent);
11212
11213 synchronized(this) {
11214 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011215 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011216 return;
11217 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011218 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011219
Dianne Hackborn06740692010-09-22 22:46:21 -070011220 long oldIdent = Binder.clearCallingIdentity();
11221 try {
11222 IBackupManager bm = IBackupManager.Stub.asInterface(
11223 ServiceManager.getService(Context.BACKUP_SERVICE));
11224 bm.agentConnected(agentPackageName, agent);
11225 } catch (RemoteException e) {
11226 // can't happen; the backup manager service is local
11227 } catch (Exception e) {
11228 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11229 e.printStackTrace();
11230 } finally {
11231 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011232 }
11233 }
11234
11235 // done with this agent
11236 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011237 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011238 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011239 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011240 return;
11241 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011242
11243 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011244 try {
11245 if (mBackupAppName == null) {
11246 Slog.w(TAG, "Unbinding backup agent with no active backup");
11247 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011248 }
Christopher Tate346acb12012-10-15 19:20:25 -070011249
11250 if (!mBackupAppName.equals(appInfo.packageName)) {
11251 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11252 return;
11253 }
11254
11255 // Not backing this app up any more; reset its OOM adjustment
11256 final ProcessRecord proc = mBackupTarget.app;
11257 updateOomAdjLocked(proc);
11258
11259 // If the app crashed during backup, 'thread' will be null here
11260 if (proc.thread != null) {
11261 try {
11262 proc.thread.scheduleDestroyBackupAgent(appInfo,
11263 compatibilityInfoForPackageLocked(appInfo));
11264 } catch (Exception e) {
11265 Slog.e(TAG, "Exception when unbinding backup agent:");
11266 e.printStackTrace();
11267 }
11268 }
11269 } finally {
11270 mBackupTarget = null;
11271 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011272 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011273 }
11274 }
11275 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011276 // BROADCASTS
11277 // =========================================================
11278
Josh Bartel7f208742010-02-25 11:01:44 -060011279 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011280 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011281 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011282 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11283 if (stickies == null) {
11284 return cur;
11285 }
11286 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 if (list == null) {
11288 return cur;
11289 }
11290 int N = list.size();
11291 for (int i=0; i<N; i++) {
11292 Intent intent = list.get(i);
11293 if (filter.match(resolver, intent, true, TAG) >= 0) {
11294 if (cur == null) {
11295 cur = new ArrayList<Intent>();
11296 }
11297 cur.add(intent);
11298 }
11299 }
11300 return cur;
11301 }
11302
Christopher Tatef46723b2012-01-26 14:19:24 -080011303 boolean isPendingBroadcastProcessLocked(int pid) {
11304 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11305 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307
Christopher Tatef46723b2012-01-26 14:19:24 -080011308 void skipPendingBroadcastLocked(int pid) {
11309 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11310 for (BroadcastQueue queue : mBroadcastQueues) {
11311 queue.skipPendingBroadcastLocked(pid);
11312 }
11313 }
11314
11315 // The app just attached; send any pending broadcasts that it should receive
11316 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11317 boolean didSomething = false;
11318 for (BroadcastQueue queue : mBroadcastQueues) {
11319 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011321 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 }
11323
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011324 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011325 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011326 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011327 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011328 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 synchronized(this) {
11330 ProcessRecord callerApp = null;
11331 if (caller != null) {
11332 callerApp = getRecordForAppLocked(caller);
11333 if (callerApp == null) {
11334 throw new SecurityException(
11335 "Unable to find app for caller " + caller
11336 + " (pid=" + Binder.getCallingPid()
11337 + ") when registering receiver " + receiver);
11338 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011339 if (callerApp.info.uid != Process.SYSTEM_UID &&
11340 !callerApp.pkgList.contains(callerPackage)) {
11341 throw new SecurityException("Given caller package " + callerPackage
11342 + " is not running in process " + callerApp);
11343 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011344 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011345 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011346 } else {
11347 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011348 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011349 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 }
11351
Dianne Hackborn139748f2012-09-24 11:36:57 -070011352 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011353 true, true, "registerReceiver", callerPackage);
11354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355 List allSticky = null;
11356
11357 // Look for any matching sticky broadcasts...
11358 Iterator actions = filter.actionsIterator();
11359 if (actions != null) {
11360 while (actions.hasNext()) {
11361 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011362 allSticky = getStickiesLocked(action, filter, allSticky,
11363 UserHandle.USER_ALL);
11364 allSticky = getStickiesLocked(action, filter, allSticky,
11365 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011366 }
11367 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011368 allSticky = getStickiesLocked(null, filter, allSticky,
11369 UserHandle.USER_ALL);
11370 allSticky = getStickiesLocked(null, filter, allSticky,
11371 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 }
11373
11374 // The first sticky in the list is returned directly back to
11375 // the client.
11376 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11377
Joe Onorato8a9b2202010-02-26 18:56:32 -080011378 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 + ": " + sticky);
11380
11381 if (receiver == null) {
11382 return sticky;
11383 }
11384
11385 ReceiverList rl
11386 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11387 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011388 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11389 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 if (rl.app != null) {
11391 rl.app.receivers.add(rl);
11392 } else {
11393 try {
11394 receiver.asBinder().linkToDeath(rl, 0);
11395 } catch (RemoteException e) {
11396 return sticky;
11397 }
11398 rl.linkedToDeath = true;
11399 }
11400 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011401 } else if (rl.uid != callingUid) {
11402 throw new IllegalArgumentException(
11403 "Receiver requested to register for uid " + callingUid
11404 + " was previously registered for uid " + rl.uid);
11405 } else if (rl.pid != callingPid) {
11406 throw new IllegalArgumentException(
11407 "Receiver requested to register for pid " + callingPid
11408 + " was previously registered for pid " + rl.pid);
11409 } else if (rl.userId != userId) {
11410 throw new IllegalArgumentException(
11411 "Receiver requested to register for user " + userId
11412 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011414 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011415 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 rl.add(bf);
11417 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011418 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 }
11420 mReceiverResolver.addFilter(bf);
11421
11422 // Enqueue broadcasts for all existing stickies that match
11423 // this filter.
11424 if (allSticky != null) {
11425 ArrayList receivers = new ArrayList();
11426 receivers.add(bf);
11427
11428 int N = allSticky.size();
11429 for (int i=0; i<N; i++) {
11430 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011431 BroadcastQueue queue = broadcastQueueForIntent(intent);
11432 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011433 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011434 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011435 queue.enqueueParallelBroadcastLocked(r);
11436 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 }
11438 }
11439
11440 return sticky;
11441 }
11442 }
11443
11444 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011445 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011446
Christopher Tatef46723b2012-01-26 14:19:24 -080011447 final long origId = Binder.clearCallingIdentity();
11448 try {
11449 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011450
Christopher Tatef46723b2012-01-26 14:19:24 -080011451 synchronized(this) {
11452 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011454 if (rl != null) {
11455 if (rl.curBroadcast != null) {
11456 BroadcastRecord r = rl.curBroadcast;
11457 final boolean doNext = finishReceiverLocked(
11458 receiver.asBinder(), r.resultCode, r.resultData,
11459 r.resultExtras, r.resultAbort, true);
11460 if (doNext) {
11461 doTrim = true;
11462 r.queue.processNextBroadcast(false);
11463 }
11464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465
Christopher Tatef46723b2012-01-26 14:19:24 -080011466 if (rl.app != null) {
11467 rl.app.receivers.remove(rl);
11468 }
11469 removeReceiverLocked(rl);
11470 if (rl.linkedToDeath) {
11471 rl.linkedToDeath = false;
11472 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 }
11475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476
Christopher Tatef46723b2012-01-26 14:19:24 -080011477 // If we actually concluded any broadcasts, we might now be able
11478 // to trim the recipients' apps from our working set
11479 if (doTrim) {
11480 trimApplications();
11481 return;
11482 }
11483
11484 } finally {
11485 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 }
11488
11489 void removeReceiverLocked(ReceiverList rl) {
11490 mRegisteredReceivers.remove(rl.receiver.asBinder());
11491 int N = rl.size();
11492 for (int i=0; i<N; i++) {
11493 mReceiverResolver.removeFilter(rl.get(i));
11494 }
11495 }
11496
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011497 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011498 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11499 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011500 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011501 try {
11502 r.thread.dispatchPackageBroadcast(cmd, packages);
11503 } catch (RemoteException ex) {
11504 }
11505 }
11506 }
11507 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011508
11509 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11510 int[] users) {
11511 List<ResolveInfo> receivers = null;
11512 try {
11513 HashSet<ComponentName> singleUserReceivers = null;
11514 boolean scannedFirstReceivers = false;
11515 for (int user : users) {
11516 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11517 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011518 if (user != 0 && newReceivers != null) {
11519 // If this is not the primary user, we need to check for
11520 // any receivers that should be filtered out.
11521 for (int i=0; i<newReceivers.size(); i++) {
11522 ResolveInfo ri = newReceivers.get(i);
11523 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11524 newReceivers.remove(i);
11525 i--;
11526 }
11527 }
11528 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011529 if (newReceivers != null && newReceivers.size() == 0) {
11530 newReceivers = null;
11531 }
11532 if (receivers == null) {
11533 receivers = newReceivers;
11534 } else if (newReceivers != null) {
11535 // We need to concatenate the additional receivers
11536 // found with what we have do far. This would be easy,
11537 // but we also need to de-dup any receivers that are
11538 // singleUser.
11539 if (!scannedFirstReceivers) {
11540 // Collect any single user receivers we had already retrieved.
11541 scannedFirstReceivers = true;
11542 for (int i=0; i<receivers.size(); i++) {
11543 ResolveInfo ri = receivers.get(i);
11544 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11545 ComponentName cn = new ComponentName(
11546 ri.activityInfo.packageName, ri.activityInfo.name);
11547 if (singleUserReceivers == null) {
11548 singleUserReceivers = new HashSet<ComponentName>();
11549 }
11550 singleUserReceivers.add(cn);
11551 }
11552 }
11553 }
11554 // Add the new results to the existing results, tracking
11555 // and de-dupping single user receivers.
11556 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011557 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011558 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11559 ComponentName cn = new ComponentName(
11560 ri.activityInfo.packageName, ri.activityInfo.name);
11561 if (singleUserReceivers == null) {
11562 singleUserReceivers = new HashSet<ComponentName>();
11563 }
11564 if (!singleUserReceivers.contains(cn)) {
11565 singleUserReceivers.add(cn);
11566 receivers.add(ri);
11567 }
11568 } else {
11569 receivers.add(ri);
11570 }
11571 }
11572 }
11573 }
11574 } catch (RemoteException ex) {
11575 // pm is in same process, this will never happen.
11576 }
11577 return receivers;
11578 }
11579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011580 private final int broadcastIntentLocked(ProcessRecord callerApp,
11581 String callerPackage, Intent intent, String resolvedType,
11582 IIntentReceiver resultTo, int resultCode, String resultData,
11583 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011584 boolean ordered, boolean sticky, int callingPid, int callingUid,
11585 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011586 intent = new Intent(intent);
11587
Dianne Hackborne7f97212011-02-24 14:40:20 -080011588 // By default broadcasts do not go to stopped apps.
11589 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11590
Joe Onorato8a9b2202010-02-26 18:56:32 -080011591 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011593 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011595 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011597
Dianne Hackborn139748f2012-09-24 11:36:57 -070011598 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011599 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011600
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011601 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011602 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011603 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011604 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11605 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11606 Slog.w(TAG, "Skipping broadcast of " + intent
11607 + ": user " + userId + " is stopped");
11608 return ActivityManager.BROADCAST_SUCCESS;
11609 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011610 }
11611
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011612 /*
11613 * Prevent non-system code (defined here to be non-persistent
11614 * processes) from sending protected broadcasts.
11615 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011616 int callingAppId = UserHandle.getAppId(callingUid);
11617 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11618 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011619 callingUid == 0) {
11620 // Always okay.
11621 } else if (callerApp == null || !callerApp.persistent) {
11622 try {
11623 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11624 intent.getAction())) {
11625 String msg = "Permission Denial: not allowed to send broadcast "
11626 + intent.getAction() + " from pid="
11627 + callingPid + ", uid=" + callingUid;
11628 Slog.w(TAG, msg);
11629 throw new SecurityException(msg);
11630 }
11631 } catch (RemoteException e) {
11632 Slog.w(TAG, "Remote exception", e);
11633 return ActivityManager.BROADCAST_SUCCESS;
11634 }
11635 }
11636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011637 // Handle special intents: if this broadcast is from the package
11638 // manager about a package being removed, we need to remove all of
11639 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011640 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011642 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11643 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011644 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011645 || uidRemoved) {
11646 if (checkComponentPermission(
11647 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011648 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011649 == PackageManager.PERMISSION_GRANTED) {
11650 if (uidRemoved) {
11651 final Bundle intentExtras = intent.getExtras();
11652 final int uid = intentExtras != null
11653 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11654 if (uid >= 0) {
11655 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11656 synchronized (bs) {
11657 bs.removeUidStatsLocked(uid);
11658 }
11659 }
11660 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011661 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011662 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011663 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011664 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11665 if (list != null && (list.length > 0)) {
11666 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011667 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011668 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011669 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011670 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011671 }
11672 } else {
11673 Uri data = intent.getData();
11674 String ssp;
11675 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11676 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11677 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011678 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11679 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011680 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011681 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011682 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011683 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011685 }
11686 }
11687 }
11688 } else {
11689 String msg = "Permission Denial: " + intent.getAction()
11690 + " broadcast from " + callerPackage + " (pid=" + callingPid
11691 + ", uid=" + callingUid + ")"
11692 + " requires "
11693 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011694 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 throw new SecurityException(msg);
11696 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011697
11698 // Special case for adding a package: by default turn on compatibility
11699 // mode.
11700 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011701 Uri data = intent.getData();
11702 String ssp;
11703 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11704 mCompatModePackages.handlePackageAddedLocked(ssp,
11705 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011707 }
11708
11709 /*
11710 * If this is the time zone changed action, queue up a message that will reset the timezone
11711 * of all currently running processes. This message will get queued up before the broadcast
11712 * happens.
11713 */
11714 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11715 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11716 }
11717
Robert Greenwalt03595d02010-11-02 14:08:23 -070011718 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11719 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11720 }
11721
Robert Greenwalt434203a2010-10-11 16:00:27 -070011722 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11723 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11724 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11725 }
11726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727 // Add to the sticky list if requested.
11728 if (sticky) {
11729 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11730 callingPid, callingUid)
11731 != PackageManager.PERMISSION_GRANTED) {
11732 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11733 + callingPid + ", uid=" + callingUid
11734 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011735 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011736 throw new SecurityException(msg);
11737 }
11738 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011739 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011741 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011742 }
11743 if (intent.getComponent() != null) {
11744 throw new SecurityException(
11745 "Sticky broadcasts can't target a specific component");
11746 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011747 // We use userId directly here, since the "all" target is maintained
11748 // as a separate set of sticky broadcasts.
11749 if (userId != UserHandle.USER_ALL) {
11750 // But first, if this is not a broadcast to all users, then
11751 // make sure it doesn't conflict with an existing broadcast to
11752 // all users.
11753 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11754 UserHandle.USER_ALL);
11755 if (stickies != null) {
11756 ArrayList<Intent> list = stickies.get(intent.getAction());
11757 if (list != null) {
11758 int N = list.size();
11759 int i;
11760 for (i=0; i<N; i++) {
11761 if (intent.filterEquals(list.get(i))) {
11762 throw new IllegalArgumentException(
11763 "Sticky broadcast " + intent + " for user "
11764 + userId + " conflicts with existing global broadcast");
11765 }
11766 }
11767 }
11768 }
11769 }
11770 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11771 if (stickies == null) {
11772 stickies = new HashMap<String, ArrayList<Intent>>();
11773 mStickyBroadcasts.put(userId, stickies);
11774 }
11775 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 if (list == null) {
11777 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011778 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 }
11780 int N = list.size();
11781 int i;
11782 for (i=0; i<N; i++) {
11783 if (intent.filterEquals(list.get(i))) {
11784 // This sticky already exists, replace it.
11785 list.set(i, new Intent(intent));
11786 break;
11787 }
11788 }
11789 if (i >= N) {
11790 list.add(new Intent(intent));
11791 }
11792 }
11793
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011794 int[] users;
11795 if (userId == UserHandle.USER_ALL) {
11796 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011797 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011798 } else {
11799 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011800 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011801 }
11802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 // Figure out who all will receive this broadcast.
11804 List receivers = null;
11805 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011806 // Need to resolve the intent to interested receivers...
11807 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11808 == 0) {
11809 receivers = collectReceiverComponents(intent, resolvedType, users);
11810 }
11811 if (intent.getComponent() == null) {
11812 registeredReceivers = mReceiverResolver.queryIntent(intent,
11813 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 }
11815
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011816 final boolean replacePending =
11817 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11818
Joe Onorato8a9b2202010-02-26 18:56:32 -080011819 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011820 + " replacePending=" + replacePending);
11821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11823 if (!ordered && NR > 0) {
11824 // If we are not serializing this broadcast, then send the
11825 // registered receivers separately so they don't wait for the
11826 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011827 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11828 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011829 callerPackage, callingPid, callingUid, requiredPermission,
11830 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011831 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011832 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011833 TAG, "Enqueueing parallel broadcast " + r);
11834 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011835 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011836 queue.enqueueParallelBroadcastLocked(r);
11837 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839 registeredReceivers = null;
11840 NR = 0;
11841 }
11842
11843 // Merge into one list.
11844 int ir = 0;
11845 if (receivers != null) {
11846 // A special case for PACKAGE_ADDED: do not allow the package
11847 // being added to see this broadcast. This prevents them from
11848 // using this as a back door to get run as soon as they are
11849 // installed. Maybe in the future we want to have a special install
11850 // broadcast or such for apps, but we'd like to deliberately make
11851 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011852 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011853 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11854 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11855 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011856 Uri data = intent.getData();
11857 if (data != null) {
11858 String pkgName = data.getSchemeSpecificPart();
11859 if (pkgName != null) {
11860 skipPackages = new String[] { pkgName };
11861 }
11862 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011863 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011864 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011865 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011866 if (skipPackages != null && (skipPackages.length > 0)) {
11867 for (String skipPackage : skipPackages) {
11868 if (skipPackage != null) {
11869 int NT = receivers.size();
11870 for (int it=0; it<NT; it++) {
11871 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11872 if (curt.activityInfo.packageName.equals(skipPackage)) {
11873 receivers.remove(it);
11874 it--;
11875 NT--;
11876 }
11877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011878 }
11879 }
11880 }
11881
11882 int NT = receivers != null ? receivers.size() : 0;
11883 int it = 0;
11884 ResolveInfo curt = null;
11885 BroadcastFilter curr = null;
11886 while (it < NT && ir < NR) {
11887 if (curt == null) {
11888 curt = (ResolveInfo)receivers.get(it);
11889 }
11890 if (curr == null) {
11891 curr = registeredReceivers.get(ir);
11892 }
11893 if (curr.getPriority() >= curt.priority) {
11894 // Insert this broadcast record into the final list.
11895 receivers.add(it, curr);
11896 ir++;
11897 curr = null;
11898 it++;
11899 NT++;
11900 } else {
11901 // Skip to the next ResolveInfo in the final list.
11902 it++;
11903 curt = null;
11904 }
11905 }
11906 }
11907 while (ir < NR) {
11908 if (receivers == null) {
11909 receivers = new ArrayList();
11910 }
11911 receivers.add(registeredReceivers.get(ir));
11912 ir++;
11913 }
11914
11915 if ((receivers != null && receivers.size() > 0)
11916 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011917 BroadcastQueue queue = broadcastQueueForIntent(intent);
11918 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011919 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011920 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011921 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011922 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011924 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 if (DEBUG_BROADCAST) {
11926 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011927 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011928 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011929 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011930 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011931 queue.enqueueOrderedBroadcastLocked(r);
11932 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011934 }
11935
Dianne Hackborna4972e92012-03-14 10:38:05 -070011936 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 }
11938
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011939 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 // Refuse possible leaked file descriptors
11941 if (intent != null && intent.hasFileDescriptors() == true) {
11942 throw new IllegalArgumentException("File descriptors passed in Intent");
11943 }
11944
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011945 int flags = intent.getFlags();
11946
11947 if (!mProcessesReady) {
11948 // if the caller really truly claims to know what they're doing, go
11949 // ahead and allow the broadcast without launching any receivers
11950 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11951 intent = new Intent(intent);
11952 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11953 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11954 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11955 + " before boot completion");
11956 throw new IllegalStateException("Cannot broadcast before boot completed");
11957 }
11958 }
11959
11960 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11961 throw new IllegalArgumentException(
11962 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11963 }
11964
11965 return intent;
11966 }
11967
11968 public final int broadcastIntent(IApplicationThread caller,
11969 Intent intent, String resolvedType, IIntentReceiver resultTo,
11970 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011971 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011972 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011973 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011974 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011976 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11977 final int callingPid = Binder.getCallingPid();
11978 final int callingUid = Binder.getCallingUid();
11979 final long origId = Binder.clearCallingIdentity();
11980 int res = broadcastIntentLocked(callerApp,
11981 callerApp != null ? callerApp.info.packageName : null,
11982 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011983 resultCode, resultData, map, requiredPermission, serialized, sticky,
11984 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011985 Binder.restoreCallingIdentity(origId);
11986 return res;
11987 }
11988 }
11989
11990 int broadcastIntentInPackage(String packageName, int uid,
11991 Intent intent, String resolvedType, IIntentReceiver resultTo,
11992 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011993 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011994 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011995 intent = verifyBroadcastLocked(intent);
11996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 final long origId = Binder.clearCallingIdentity();
11998 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11999 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012000 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001 Binder.restoreCallingIdentity(origId);
12002 return res;
12003 }
12004 }
12005
Amith Yamasani742a6712011-05-04 14:49:28 -070012006 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007 // Refuse possible leaked file descriptors
12008 if (intent != null && intent.hasFileDescriptors() == true) {
12009 throw new IllegalArgumentException("File descriptors passed in Intent");
12010 }
12011
Dianne Hackborn139748f2012-09-24 11:36:57 -070012012 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012013 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012015 synchronized(this) {
12016 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12017 != PackageManager.PERMISSION_GRANTED) {
12018 String msg = "Permission Denial: unbroadcastIntent() from pid="
12019 + Binder.getCallingPid()
12020 + ", uid=" + Binder.getCallingUid()
12021 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012022 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012023 throw new SecurityException(msg);
12024 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012025 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12026 if (stickies != null) {
12027 ArrayList<Intent> list = stickies.get(intent.getAction());
12028 if (list != null) {
12029 int N = list.size();
12030 int i;
12031 for (i=0; i<N; i++) {
12032 if (intent.filterEquals(list.get(i))) {
12033 list.remove(i);
12034 break;
12035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012037 if (list.size() <= 0) {
12038 stickies.remove(intent.getAction());
12039 }
12040 }
12041 if (stickies.size() <= 0) {
12042 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043 }
12044 }
12045 }
12046 }
12047
12048 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12049 String resultData, Bundle resultExtras, boolean resultAbort,
12050 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012051 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12052 if (r == null) {
12053 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012054 return false;
12055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056
Christopher Tatef46723b2012-01-26 14:19:24 -080012057 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12058 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012059 }
12060
12061 public void finishReceiver(IBinder who, int resultCode, String resultData,
12062 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012063 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012064
12065 // Refuse possible leaked file descriptors
12066 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12067 throw new IllegalArgumentException("File descriptors passed in Bundle");
12068 }
12069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012071 try {
12072 boolean doNext = false;
12073 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012074
Christopher Tatef46723b2012-01-26 14:19:24 -080012075 synchronized(this) {
12076 r = broadcastRecordForReceiverLocked(who);
12077 if (r != null) {
12078 doNext = r.queue.finishReceiverLocked(r, resultCode,
12079 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012081 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012082
Christopher Tatef46723b2012-01-26 14:19:24 -080012083 if (doNext) {
12084 r.queue.processNextBroadcast(false);
12085 }
12086 trimApplications();
12087 } finally {
12088 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 // =========================================================
12093 // INSTRUMENTATION
12094 // =========================================================
12095
12096 public boolean startInstrumentation(ComponentName className,
12097 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012098 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012099 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012100 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012101 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012102 // Refuse possible leaked file descriptors
12103 if (arguments != null && arguments.hasFileDescriptors()) {
12104 throw new IllegalArgumentException("File descriptors passed in Bundle");
12105 }
12106
12107 synchronized(this) {
12108 InstrumentationInfo ii = null;
12109 ApplicationInfo ai = null;
12110 try {
12111 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012112 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012113 ai = AppGlobals.getPackageManager().getApplicationInfo(
12114 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012116 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 }
12118 if (ii == null) {
12119 reportStartInstrumentationFailure(watcher, className,
12120 "Unable to find instrumentation info for: " + className);
12121 return false;
12122 }
12123 if (ai == null) {
12124 reportStartInstrumentationFailure(watcher, className,
12125 "Unable to find instrumentation target package: " + ii.targetPackage);
12126 return false;
12127 }
12128
12129 int match = mContext.getPackageManager().checkSignatures(
12130 ii.targetPackage, ii.packageName);
12131 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12132 String msg = "Permission Denial: starting instrumentation "
12133 + className + " from pid="
12134 + Binder.getCallingPid()
12135 + ", uid=" + Binder.getCallingPid()
12136 + " not allowed because package " + ii.packageName
12137 + " does not have a signature matching the target "
12138 + ii.targetPackage;
12139 reportStartInstrumentationFailure(watcher, className, msg);
12140 throw new SecurityException(msg);
12141 }
12142
12143 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012144 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012145 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012146 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012147 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012148 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012149 app.instrumentationProfileFile = profileFile;
12150 app.instrumentationArguments = arguments;
12151 app.instrumentationWatcher = watcher;
12152 app.instrumentationResultClass = className;
12153 Binder.restoreCallingIdentity(origId);
12154 }
12155
12156 return true;
12157 }
12158
12159 /**
12160 * Report errors that occur while attempting to start Instrumentation. Always writes the
12161 * error to the logs, but if somebody is watching, send the report there too. This enables
12162 * the "am" command to report errors with more information.
12163 *
12164 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12165 * @param cn The component name of the instrumentation.
12166 * @param report The error report.
12167 */
12168 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12169 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012170 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012171 try {
12172 if (watcher != null) {
12173 Bundle results = new Bundle();
12174 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12175 results.putString("Error", report);
12176 watcher.instrumentationStatus(cn, -1, results);
12177 }
12178 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012179 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012180 }
12181 }
12182
12183 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12184 if (app.instrumentationWatcher != null) {
12185 try {
12186 // NOTE: IInstrumentationWatcher *must* be oneway here
12187 app.instrumentationWatcher.instrumentationFinished(
12188 app.instrumentationClass,
12189 resultCode,
12190 results);
12191 } catch (RemoteException e) {
12192 }
12193 }
12194 app.instrumentationWatcher = null;
12195 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012196 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 app.instrumentationProfileFile = null;
12198 app.instrumentationArguments = null;
12199
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012200 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012201 }
12202
12203 public void finishInstrumentation(IApplicationThread target,
12204 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012205 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012206 // Refuse possible leaked file descriptors
12207 if (results != null && results.hasFileDescriptors()) {
12208 throw new IllegalArgumentException("File descriptors passed in Intent");
12209 }
12210
12211 synchronized(this) {
12212 ProcessRecord app = getRecordForAppLocked(target);
12213 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012214 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 return;
12216 }
12217 final long origId = Binder.clearCallingIdentity();
12218 finishInstrumentationLocked(app, resultCode, results);
12219 Binder.restoreCallingIdentity(origId);
12220 }
12221 }
12222
12223 // =========================================================
12224 // CONFIGURATION
12225 // =========================================================
12226
12227 public ConfigurationInfo getDeviceConfigurationInfo() {
12228 ConfigurationInfo config = new ConfigurationInfo();
12229 synchronized (this) {
12230 config.reqTouchScreen = mConfiguration.touchscreen;
12231 config.reqKeyboardType = mConfiguration.keyboard;
12232 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012233 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12234 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12236 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012237 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12238 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12240 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012241 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012242 }
12243 return config;
12244 }
12245
12246 public Configuration getConfiguration() {
12247 Configuration ci;
12248 synchronized(this) {
12249 ci = new Configuration(mConfiguration);
12250 }
12251 return ci;
12252 }
12253
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012254 public void updatePersistentConfiguration(Configuration values) {
12255 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12256 "updateConfiguration()");
12257 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12258 "updateConfiguration()");
12259 if (values == null) {
12260 throw new NullPointerException("Configuration must not be null");
12261 }
12262
12263 synchronized(this) {
12264 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012265 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012266 Binder.restoreCallingIdentity(origId);
12267 }
12268 }
12269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012270 public void updateConfiguration(Configuration values) {
12271 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12272 "updateConfiguration()");
12273
12274 synchronized(this) {
12275 if (values == null && mWindowManager != null) {
12276 // sentinel: fetch the current configuration from the window manager
12277 values = mWindowManager.computeNewConfiguration();
12278 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012279
12280 if (mWindowManager != null) {
12281 mProcessList.applyDisplaySize(mWindowManager);
12282 }
12283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012285 if (values != null) {
12286 Settings.System.clearConfiguration(values);
12287 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012288 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289 Binder.restoreCallingIdentity(origId);
12290 }
12291 }
12292
12293 /**
12294 * Do either or both things: (1) change the current configuration, and (2)
12295 * make sure the given activity is running with the (now) current
12296 * configuration. Returns true if the activity has been left running, or
12297 * false if <var>starting</var> is being destroyed to match the new
12298 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012299 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012301 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012302 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012303 // do nothing if we are headless
12304 if (mHeadless) return true;
12305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012306 int changes = 0;
12307
12308 boolean kept = true;
12309
12310 if (values != null) {
12311 Configuration newConfig = new Configuration(mConfiguration);
12312 changes = newConfig.updateFrom(values);
12313 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012314 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012315 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012316 }
12317
Doug Zongker2bec3d42009-12-04 12:52:44 -080012318 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012319
Dianne Hackborn813075a62011-11-14 17:45:19 -080012320 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012321 saveLocaleLocked(values.locale,
12322 !values.locale.equals(mConfiguration.locale),
12323 values.userSetLocale);
12324 }
12325
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012326 mConfigurationSeq++;
12327 if (mConfigurationSeq <= 0) {
12328 mConfigurationSeq = 1;
12329 }
12330 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012331 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012332 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012333
12334 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012335
12336 // TODO: If our config changes, should we auto dismiss any currently
12337 // showing dialogs?
12338 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012339
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012340 AttributeCache ac = AttributeCache.instance();
12341 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012342 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012344
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012345 // Make sure all resources in our process are updated
12346 // right now, so that anyone who is going to retrieve
12347 // resource values after we return will be sure to get
12348 // the new ones. This is especially important during
12349 // boot, where the first config change needs to guarantee
12350 // all resources have that config before following boot
12351 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012352 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012353
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012354 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012355 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012356 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012357 mHandler.sendMessage(msg);
12358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012359
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012360 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12361 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012362 try {
12363 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012364 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012365 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012366 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012367 }
12368 } catch (Exception e) {
12369 }
12370 }
12371 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012372 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012373 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12374 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012375 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012376 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012377 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012378 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12379 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12380 broadcastIntentLocked(null, null, intent,
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012381 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012382 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012384 }
12385 }
12386
12387 if (changes != 0 && starting == null) {
12388 // If the configuration changed, and the caller is not already
12389 // in the process of starting an activity, then find the top
12390 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012391 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012392 }
12393
12394 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012395 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012396 // And we need to make sure at this point that all other activities
12397 // are made visible with the correct configuration.
12398 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 }
12400
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012401 if (values != null && mWindowManager != null) {
12402 mWindowManager.setNewConfiguration(mConfiguration);
12403 }
12404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012405 return kept;
12406 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012407
12408 /**
12409 * Decide based on the configuration whether we should shouw the ANR,
12410 * crash, etc dialogs. The idea is that if there is no affordnace to
12411 * press the on-screen buttons, we shouldn't show the dialog.
12412 *
12413 * A thought: SystemUI might also want to get told about this, the Power
12414 * dialog / global actions also might want different behaviors.
12415 */
12416 private static final boolean shouldShowDialogs(Configuration config) {
12417 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12418 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012420
12421 /**
12422 * Save the locale. You must be inside a synchronized (this) block.
12423 */
12424 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12425 if(isDiff) {
12426 SystemProperties.set("user.language", l.getLanguage());
12427 SystemProperties.set("user.region", l.getCountry());
12428 }
12429
12430 if(isPersist) {
12431 SystemProperties.set("persist.sys.language", l.getLanguage());
12432 SystemProperties.set("persist.sys.country", l.getCountry());
12433 SystemProperties.set("persist.sys.localevar", l.getVariant());
12434 }
12435 }
12436
Adam Powelldd8fab22012-03-22 17:47:27 -070012437 @Override
12438 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12439 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012440 return srec != null && srec.task.affinity != null &&
12441 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012442 }
12443
12444 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12445 Intent resultData) {
12446 ComponentName dest = destIntent.getComponent();
12447
12448 synchronized (this) {
12449 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012450 if (srec == null) {
12451 return false;
12452 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012453 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12454 final int start = history.indexOf(srec);
12455 if (start < 0) {
12456 // Current activity is not in history stack; do nothing.
12457 return false;
12458 }
12459 int finishTo = start - 1;
12460 ActivityRecord parent = null;
12461 boolean foundParentInTask = false;
12462 if (dest != null) {
12463 TaskRecord tr = srec.task;
12464 for (int i = start - 1; i >= 0; i--) {
12465 ActivityRecord r = history.get(i);
12466 if (tr != r.task) {
12467 // Couldn't find parent in the same task; stop at the one above this.
12468 // (Root of current task; in-app "home" behavior)
12469 // Always at least finish the current activity.
12470 finishTo = Math.min(start - 1, i + 1);
12471 parent = history.get(finishTo);
12472 break;
12473 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12474 r.info.name.equals(dest.getClassName())) {
12475 finishTo = i;
12476 parent = r;
12477 foundParentInTask = true;
12478 break;
12479 }
12480 }
12481 }
12482
12483 if (mController != null) {
12484 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12485 if (next != null) {
12486 // ask watcher if this is allowed
12487 boolean resumeOK = true;
12488 try {
12489 resumeOK = mController.activityResuming(next.packageName);
12490 } catch (RemoteException e) {
12491 mController = null;
12492 }
12493
12494 if (!resumeOK) {
12495 return false;
12496 }
12497 }
12498 }
12499 final long origId = Binder.clearCallingIdentity();
12500 for (int i = start; i > finishTo; i--) {
12501 ActivityRecord r = history.get(i);
12502 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012503 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012504 // Only return the supplied result for the first activity finished
12505 resultCode = Activity.RESULT_CANCELED;
12506 resultData = null;
12507 }
12508
12509 if (parent != null && foundParentInTask) {
12510 final int parentLaunchMode = parent.info.launchMode;
12511 final int destIntentFlags = destIntent.getFlags();
12512 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12513 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12514 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12515 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012516 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012517 } else {
12518 try {
12519 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012520 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012521 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12522 null, aInfo, parent.appToken, null,
12523 0, -1, parent.launchedFromUid, 0, null, true, null);
12524 foundParentInTask = res == ActivityManager.START_SUCCESS;
12525 } catch (RemoteException e) {
12526 foundParentInTask = false;
12527 }
12528 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012529 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012530 }
12531 }
12532 Binder.restoreCallingIdentity(origId);
12533 return foundParentInTask;
12534 }
12535 }
12536
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012537 public int getLaunchedFromUid(IBinder activityToken) {
12538 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12539 if (srec == null) {
12540 return -1;
12541 }
12542 return srec.launchedFromUid;
12543 }
12544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012545 // =========================================================
12546 // LIFETIME MANAGEMENT
12547 // =========================================================
12548
Christopher Tatef46723b2012-01-26 14:19:24 -080012549 // Returns which broadcast queue the app is the current [or imminent] receiver
12550 // on, or 'null' if the app is not an active broadcast recipient.
12551 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12552 BroadcastRecord r = app.curReceiver;
12553 if (r != null) {
12554 return r.queue;
12555 }
12556
12557 // It's not the current receiver, but it might be starting up to become one
12558 synchronized (this) {
12559 for (BroadcastQueue queue : mBroadcastQueues) {
12560 r = queue.mPendingBroadcast;
12561 if (r != null && r.curApp == app) {
12562 // found it; report which queue it's in
12563 return queue;
12564 }
12565 }
12566 }
12567
12568 return null;
12569 }
12570
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012571 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012572 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012574 // This adjustment has already been computed. If we are calling
12575 // from the top, we may have already computed our adjustment with
12576 // an earlier hidden adjustment that isn't really for us... if
12577 // so, use the new hidden adjustment.
12578 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012579 if (app.hasActivities) {
12580 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12581 } else if (app.hasClientActivities) {
12582 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12583 } else {
12584 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12585 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012586 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012587 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012588 }
12589
12590 if (app.thread == null) {
12591 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012592 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012593 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012594 }
12595
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012596 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12597 app.adjSource = null;
12598 app.adjTarget = null;
12599 app.empty = false;
12600 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012601 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012602
12603 final int activitiesSize = app.activities.size();
12604
Dianne Hackborn7d608422011-08-07 16:24:18 -070012605 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012606 // The max adjustment doesn't allow this app to be anything
12607 // below foreground, so it is not worth doing work for it.
12608 app.adjType = "fixed";
12609 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012610 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012611 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012612 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012613 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012614 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012615 // System process can do UI, and when they do we want to have
12616 // them trim their memory after the user leaves the UI. To
12617 // facilitate this, here we need to determine whether or not it
12618 // is currently showing UI.
12619 app.systemNoUi = true;
12620 if (app == TOP_APP) {
12621 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012622 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012623 } else if (activitiesSize > 0) {
12624 for (int j = 0; j < activitiesSize; j++) {
12625 final ActivityRecord r = app.activities.get(j);
12626 if (r.visible) {
12627 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012628 }
12629 if (r.app == app) {
12630 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012631 }
12632 }
12633 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012634 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012635 }
12636
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012637 app.keeping = false;
12638 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012639 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640
The Android Open Source Project4df24232009-03-05 14:34:35 -080012641 // Determine the importance of the process, starting with most
12642 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012643 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012644 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012645 boolean foregroundActivities = false;
12646 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012647 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012648 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012649 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012650 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012651 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012652 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012653 foregroundActivities = true;
12654 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012655 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012656 } else if (app.instrumentationClass != null) {
12657 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012658 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012659 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012660 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012661 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012662 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012664 // counts as being in the foreground for OOM killer purposes.
12665 // It's placed in a sched group based on the nature of the
12666 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012667 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012668 schedGroup = (queue == mFgBroadcastQueue)
12669 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012670 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012671 } else if (app.executingServices.size() > 0) {
12672 // An app that is currently executing a service callback also
12673 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012674 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012675 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012676 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012677 } else {
12678 // Assume process is hidden (has activities); we will correct
12679 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012681 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012682 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012683 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012685
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012686 boolean hasStoppingActivities = false;
12687
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012688 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012689 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012690 for (int j = 0; j < activitiesSize; j++) {
12691 final ActivityRecord r = app.activities.get(j);
12692 if (r.visible) {
12693 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012694 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12695 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012696 app.adjType = "visible";
12697 }
12698 schedGroup = Process.THREAD_GROUP_DEFAULT;
12699 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012700 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012701 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012702 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012703 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012704 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12705 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012706 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012707 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012708 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012709 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012710 } else if (r.state == ActivityState.STOPPING) {
12711 // We will apply the actual adjustment later, because
12712 // we want to allow this process to immediately go through
12713 // any memory trimming that is in effect.
12714 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012715 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012716 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012717 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012718 if (r.app == app) {
12719 app.hasActivities = true;
12720 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012721 }
12722 }
12723
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012724 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012725 if (app.hasClientActivities) {
12726 adj = clientHiddenAdj;
12727 app.adjType = "bg-client-act";
12728 } else {
12729 // Whoops, this process is completely empty as far as we know
12730 // at this point.
12731 adj = emptyAdj;
12732 app.empty = true;
12733 app.adjType = "bg-empty";
12734 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012735 }
12736
Dianne Hackborn7d608422011-08-07 16:24:18 -070012737 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012738 if (app.foregroundServices) {
12739 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012740 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012741 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012742 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012743 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012744 } else if (app.forcingToForeground != null) {
12745 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012746 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012747 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012748 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012749 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012750 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012751 }
12752 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012753
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012754 if (app.foregroundServices) {
12755 interesting = true;
12756 }
12757
Dianne Hackborn7d608422011-08-07 16:24:18 -070012758 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012759 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012760 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012761 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012762 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012763 app.adjType = "heavy";
12764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012765
Dianne Hackborn7d608422011-08-07 16:24:18 -070012766 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012767 // This process is hosting what we currently consider to be the
12768 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012769 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012770 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012771 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012772 app.adjType = "home";
12773 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012774
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012775 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12776 && app.activities.size() > 0) {
12777 // This was the previous process that showed UI to the user.
12778 // We want to try to keep it around more aggressively, to give
12779 // a good experience around switching between two apps.
12780 adj = ProcessList.PREVIOUS_APP_ADJ;
12781 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12782 app.hidden = false;
12783 app.adjType = "previous";
12784 }
12785
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012786 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12787 + " reason=" + app.adjType);
12788
The Android Open Source Project4df24232009-03-05 14:34:35 -080012789 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012790 // there are applications dependent on our services or providers, but
12791 // this gives us a baseline and makes sure we don't get into an
12792 // infinite recursion.
12793 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012794 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795
Christopher Tate6fa95972009-06-05 18:43:55 -070012796 if (mBackupTarget != null && app == mBackupTarget.app) {
12797 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012798 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012799 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012800 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012801 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012802 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012803 }
12804 }
12805
Dianne Hackborn7d608422011-08-07 16:24:18 -070012806 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012807 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 final long now = SystemClock.uptimeMillis();
12809 // This process is more important if the top activity is
12810 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012811 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012812 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012813 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012814 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012815 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012816 // If this process has shown some UI, let it immediately
12817 // go to the LRU list because it may be pretty heavy with
12818 // UI stuff. We'll tag it with a label just to help
12819 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012820 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012821 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012822 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012823 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012824 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012825 // This service has seen some activity within
12826 // recent memory, so we will keep its process ahead
12827 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012828 if (adj > ProcessList.SERVICE_ADJ) {
12829 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012830 app.adjType = "started-services";
12831 app.hidden = false;
12832 }
12833 }
12834 // If we have let the service slide into the background
12835 // state, still have some text describing what it is doing
12836 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012837 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012838 app.adjType = "started-bg-services";
12839 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012840 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012841 // Don't kill this process because it is doing work; it
12842 // has said it is doing work.
12843 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012844 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012845 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012846 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012847 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012848 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012849 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012850 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012851 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012852 // XXX should compute this based on the max of
12853 // all connected clients.
12854 ConnectionRecord cr = clist.get(i);
12855 if (cr.binding.client == app) {
12856 // Binding to ourself is not interesting.
12857 continue;
12858 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012859 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012860 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012861 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012862 int myHiddenAdj = hiddenAdj;
12863 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012864 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012865 myHiddenAdj = client.hiddenAdj;
12866 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012867 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012868 }
12869 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012870 int myClientHiddenAdj = clientHiddenAdj;
12871 if (myClientHiddenAdj > client.clientHiddenAdj) {
12872 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12873 myClientHiddenAdj = client.clientHiddenAdj;
12874 } else {
12875 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12876 }
12877 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012878 int myEmptyAdj = emptyAdj;
12879 if (myEmptyAdj > client.emptyAdj) {
12880 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12881 myEmptyAdj = client.emptyAdj;
12882 } else {
12883 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12884 }
12885 }
12886 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012887 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012888 String adjType = null;
12889 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12890 // Not doing bind OOM management, so treat
12891 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012892 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012893 // If this process has shown some UI, let it immediately
12894 // go to the LRU list because it may be pretty heavy with
12895 // UI stuff. We'll tag it with a label just to help
12896 // debug and understand what is going on.
12897 if (adj > clientAdj) {
12898 adjType = "bound-bg-ui-services";
12899 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012900 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012901 clientAdj = adj;
12902 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012903 if (now >= (s.lastActivity
12904 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012905 // This service has not seen activity within
12906 // recent memory, so allow it to drop to the
12907 // LRU list if there is no other reason to keep
12908 // it around. We'll also tag it with a label just
12909 // to help debug and undertand what is going on.
12910 if (adj > clientAdj) {
12911 adjType = "bound-bg-services";
12912 }
12913 clientAdj = adj;
12914 }
12915 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012916 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12917 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12918 // If this connection is keeping the service
12919 // created, then we want to try to better follow
12920 // its memory management semantics for activities.
12921 // That is, if it is sitting in the background
12922 // LRU list as a hidden process (with activities),
12923 // we don't want the service it is connected to
12924 // to go into the empty LRU and quickly get killed,
12925 // because I'll we'll do is just end up restarting
12926 // the service.
12927 app.hasClientActivities |= client.hasActivities;
12928 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012929 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012930 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012931 // If this process has recently shown UI, and
12932 // the process that is binding to it is less
12933 // important than being visible, then we don't
12934 // care about the binding as much as we care
12935 // about letting this process get into the LRU
12936 // list to be killed and restarted if needed for
12937 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012938 if (app.hasShownUi && app != mHomeProcess
12939 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012940 adjType = "bound-bg-ui-services";
12941 } else {
12942 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12943 |Context.BIND_IMPORTANT)) != 0) {
12944 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012945 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12946 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12947 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12948 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12949 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012950 adj = clientAdj;
12951 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012952 app.pendingUiClean = true;
12953 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12954 adj = ProcessList.VISIBLE_APP_ADJ;
12955 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012956 }
12957 if (!client.hidden) {
12958 app.hidden = false;
12959 }
12960 if (client.keeping) {
12961 app.keeping = true;
12962 }
12963 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012964 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012965 }
12966 if (adjType != null) {
12967 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012968 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12969 .REASON_SERVICE_IN_USE;
12970 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012971 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012972 app.adjTarget = s.name;
12973 }
12974 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12975 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12976 schedGroup = Process.THREAD_GROUP_DEFAULT;
12977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012978 }
12979 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012980 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012981 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012982 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012983 (a.visible || a.state == ActivityState.RESUMED
12984 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012985 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012986 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12987 schedGroup = Process.THREAD_GROUP_DEFAULT;
12988 }
12989 app.hidden = false;
12990 app.adjType = "service";
12991 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12992 .REASON_SERVICE_IN_USE;
12993 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012994 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012995 app.adjTarget = s.name;
12996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998 }
12999 }
13000 }
13001 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013002
Dianne Hackborn287952c2010-09-22 22:34:31 -070013003 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013004 // would like to avoid killing it unless it would prevent the current
13005 // application from running. By default we put the process in
13006 // with the rest of the background processes; as we scan through
13007 // its services we may bump it up from there.
13008 if (adj > hiddenAdj) {
13009 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013010 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013011 app.adjType = "bg-services";
13012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013013 }
13014
Dianne Hackborn7d608422011-08-07 16:24:18 -070013015 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013016 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013017 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013018 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013019 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013020 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013021 for (int i = cpr.connections.size()-1;
13022 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13023 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13024 i--) {
13025 ContentProviderConnection conn = cpr.connections.get(i);
13026 ProcessRecord client = conn.client;
13027 if (client == app) {
13028 // Being our own client is not interesting.
13029 continue;
13030 }
13031 int myHiddenAdj = hiddenAdj;
13032 if (myHiddenAdj > client.hiddenAdj) {
13033 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13034 myHiddenAdj = client.hiddenAdj;
13035 } else {
13036 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013037 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013038 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013039 int myClientHiddenAdj = clientHiddenAdj;
13040 if (myClientHiddenAdj > client.clientHiddenAdj) {
13041 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13042 myClientHiddenAdj = client.clientHiddenAdj;
13043 } else {
13044 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13045 }
13046 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013047 int myEmptyAdj = emptyAdj;
13048 if (myEmptyAdj > client.emptyAdj) {
13049 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13050 myEmptyAdj = client.emptyAdj;
13051 } else {
13052 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13053 }
13054 }
13055 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013056 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013057 if (adj > clientAdj) {
13058 if (app.hasShownUi && app != mHomeProcess
13059 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13060 app.adjType = "bg-ui-provider";
13061 } else {
13062 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13063 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13064 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013066 if (!client.hidden) {
13067 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013068 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013069 if (client.keeping) {
13070 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013071 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013072 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13073 .REASON_PROVIDER_IN_USE;
13074 app.adjSource = client;
13075 app.adjSourceOom = clientAdj;
13076 app.adjTarget = cpr.name;
13077 }
13078 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13079 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013080 }
13081 }
13082 // If the provider has external (non-framework) process
13083 // dependencies, ensure that its adjustment is at least
13084 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013085 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013086 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13087 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013088 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013089 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013090 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013091 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013092 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013093 }
13094 }
13095 }
13096 }
13097
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013098 if (adj == ProcessList.SERVICE_ADJ) {
13099 if (doingAll) {
13100 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13101 mNewNumServiceProcs++;
13102 }
13103 if (app.serviceb) {
13104 adj = ProcessList.SERVICE_B_ADJ;
13105 }
13106 } else {
13107 app.serviceb = false;
13108 }
13109
13110 app.nonStoppingAdj = adj;
13111
13112 if (hasStoppingActivities) {
13113 // Only upgrade adjustment.
13114 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13115 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13116 app.adjType = "stopping";
13117 }
13118 }
13119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013120 app.curRawAdj = adj;
13121
Joe Onorato8a9b2202010-02-26 18:56:32 -080013122 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013123 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13124 if (adj > app.maxAdj) {
13125 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013126 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013127 schedGroup = Process.THREAD_GROUP_DEFAULT;
13128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013129 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013130 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013131 app.keeping = true;
13132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013133
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013134 if (app.hasAboveClient) {
13135 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13136 // then we need to drop its adjustment to be lower than the service's
13137 // in order to honor the request. We want to drop it by one adjustment
13138 // level... but there is special meaning applied to various levels so
13139 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013140 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013141 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013142 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13143 adj = ProcessList.VISIBLE_APP_ADJ;
13144 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13145 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13146 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13147 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013148 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013149 adj++;
13150 }
13151 }
13152
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013153 int importance = app.memImportance;
13154 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13155 app.curAdj = adj;
13156 app.curSchedGroup = schedGroup;
13157 if (!interesting) {
13158 // For this reporting, if there is not something explicitly
13159 // interesting in this process then we will push it to the
13160 // background importance.
13161 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13162 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13163 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13164 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13165 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13166 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13167 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13168 } else if (adj >= ProcessList.SERVICE_ADJ) {
13169 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13170 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13171 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13172 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13173 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13174 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13175 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13176 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13177 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13178 } else {
13179 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13180 }
13181 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013182
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013183 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13184 if (foregroundActivities != app.foregroundActivities) {
13185 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13186 }
13187 if (changes != 0) {
13188 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13189 app.memImportance = importance;
13190 app.foregroundActivities = foregroundActivities;
13191 int i = mPendingProcessChanges.size()-1;
13192 ProcessChangeItem item = null;
13193 while (i >= 0) {
13194 item = mPendingProcessChanges.get(i);
13195 if (item.pid == app.pid) {
13196 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13197 break;
13198 }
13199 i--;
13200 }
13201 if (i < 0) {
13202 // No existing item in pending changes; need a new one.
13203 final int NA = mAvailProcessChanges.size();
13204 if (NA > 0) {
13205 item = mAvailProcessChanges.remove(NA-1);
13206 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13207 } else {
13208 item = new ProcessChangeItem();
13209 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13210 }
13211 item.changes = 0;
13212 item.pid = app.pid;
13213 item.uid = app.info.uid;
13214 if (mPendingProcessChanges.size() == 0) {
13215 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13216 "*** Enqueueing dispatch processes changed!");
13217 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13218 }
13219 mPendingProcessChanges.add(item);
13220 }
13221 item.changes |= changes;
13222 item.importance = importance;
13223 item.foregroundActivities = foregroundActivities;
13224 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13225 + Integer.toHexString(System.identityHashCode(item))
13226 + " " + app.toShortString() + ": changes=" + item.changes
13227 + " importance=" + item.importance
13228 + " foreground=" + item.foregroundActivities
13229 + " type=" + app.adjType + " source=" + app.adjSource
13230 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013231 }
13232
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013233 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013234 }
13235
13236 /**
13237 * Ask a given process to GC right now.
13238 */
13239 final void performAppGcLocked(ProcessRecord app) {
13240 try {
13241 app.lastRequestedGc = SystemClock.uptimeMillis();
13242 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013243 if (app.reportLowMemory) {
13244 app.reportLowMemory = false;
13245 app.thread.scheduleLowMemory();
13246 } else {
13247 app.thread.processInBackground();
13248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 }
13250 } catch (Exception e) {
13251 // whatever.
13252 }
13253 }
13254
13255 /**
13256 * Returns true if things are idle enough to perform GCs.
13257 */
Josh Bartel7f208742010-02-25 11:01:44 -060013258 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013259 boolean processingBroadcasts = false;
13260 for (BroadcastQueue q : mBroadcastQueues) {
13261 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13262 processingBroadcasts = true;
13263 }
13264 }
13265 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013266 && (mSleeping || (mMainStack.mResumedActivity != null &&
13267 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013268 }
13269
13270 /**
13271 * Perform GCs on all processes that are waiting for it, but only
13272 * if things are idle.
13273 */
13274 final void performAppGcsLocked() {
13275 final int N = mProcessesToGc.size();
13276 if (N <= 0) {
13277 return;
13278 }
Josh Bartel7f208742010-02-25 11:01:44 -060013279 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013280 while (mProcessesToGc.size() > 0) {
13281 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013282 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013283 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13284 <= SystemClock.uptimeMillis()) {
13285 // To avoid spamming the system, we will GC processes one
13286 // at a time, waiting a few seconds between each.
13287 performAppGcLocked(proc);
13288 scheduleAppGcsLocked();
13289 return;
13290 } else {
13291 // It hasn't been long enough since we last GCed this
13292 // process... put it in the list to wait for its time.
13293 addProcessToGcListLocked(proc);
13294 break;
13295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013296 }
13297 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013298
13299 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013300 }
13301 }
13302
13303 /**
13304 * If all looks good, perform GCs on all processes waiting for them.
13305 */
13306 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013307 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 performAppGcsLocked();
13309 return;
13310 }
13311 // Still not idle, wait some more.
13312 scheduleAppGcsLocked();
13313 }
13314
13315 /**
13316 * Schedule the execution of all pending app GCs.
13317 */
13318 final void scheduleAppGcsLocked() {
13319 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013320
13321 if (mProcessesToGc.size() > 0) {
13322 // Schedule a GC for the time to the next process.
13323 ProcessRecord proc = mProcessesToGc.get(0);
13324 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13325
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013326 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013327 long now = SystemClock.uptimeMillis();
13328 if (when < (now+GC_TIMEOUT)) {
13329 when = now + GC_TIMEOUT;
13330 }
13331 mHandler.sendMessageAtTime(msg, when);
13332 }
13333 }
13334
13335 /**
13336 * Add a process to the array of processes waiting to be GCed. Keeps the
13337 * list in sorted order by the last GC time. The process can't already be
13338 * on the list.
13339 */
13340 final void addProcessToGcListLocked(ProcessRecord proc) {
13341 boolean added = false;
13342 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13343 if (mProcessesToGc.get(i).lastRequestedGc <
13344 proc.lastRequestedGc) {
13345 added = true;
13346 mProcessesToGc.add(i+1, proc);
13347 break;
13348 }
13349 }
13350 if (!added) {
13351 mProcessesToGc.add(0, proc);
13352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 }
13354
13355 /**
13356 * Set up to ask a process to GC itself. This will either do it
13357 * immediately, or put it on the list of processes to gc the next
13358 * time things are idle.
13359 */
13360 final void scheduleAppGcLocked(ProcessRecord app) {
13361 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013362 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013363 return;
13364 }
13365 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013366 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367 scheduleAppGcsLocked();
13368 }
13369 }
13370
Dianne Hackborn287952c2010-09-22 22:34:31 -070013371 final void checkExcessivePowerUsageLocked(boolean doKills) {
13372 updateCpuStatsNow();
13373
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013374 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013375 boolean doWakeKills = doKills;
13376 boolean doCpuKills = doKills;
13377 if (mLastPowerCheckRealtime == 0) {
13378 doWakeKills = false;
13379 }
13380 if (mLastPowerCheckUptime == 0) {
13381 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013382 }
13383 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013384 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013385 }
13386 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013387 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13388 final long curUptime = SystemClock.uptimeMillis();
13389 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13390 mLastPowerCheckRealtime = curRealtime;
13391 mLastPowerCheckUptime = curUptime;
13392 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13393 doWakeKills = false;
13394 }
13395 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13396 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013397 }
13398 int i = mLruProcesses.size();
13399 while (i > 0) {
13400 i--;
13401 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013402 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013403 long wtime;
13404 synchronized (stats) {
13405 wtime = stats.getProcessWakeTime(app.info.uid,
13406 app.pid, curRealtime);
13407 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013408 long wtimeUsed = wtime - app.lastWakeTime;
13409 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13410 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013411 StringBuilder sb = new StringBuilder(128);
13412 sb.append("Wake for ");
13413 app.toShortString(sb);
13414 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013415 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013416 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013417 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013418 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013419 sb.append((wtimeUsed*100)/realtimeSince);
13420 sb.append("%)");
13421 Slog.i(TAG, sb.toString());
13422 sb.setLength(0);
13423 sb.append("CPU for ");
13424 app.toShortString(sb);
13425 sb.append(": over ");
13426 TimeUtils.formatDuration(uptimeSince, sb);
13427 sb.append(" used ");
13428 TimeUtils.formatDuration(cputimeUsed, sb);
13429 sb.append(" (");
13430 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013431 sb.append("%)");
13432 Slog.i(TAG, sb.toString());
13433 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013434 // If a process has held a wake lock for more
13435 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013436 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013437 if (doWakeKills && realtimeSince > 0
13438 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13439 synchronized (stats) {
13440 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13441 realtimeSince, wtimeUsed);
13442 }
13443 Slog.w(TAG, "Excessive wake lock in " + app.processName
13444 + " (pid " + app.pid + "): held " + wtimeUsed
13445 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013446 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013447 app.processName, app.setAdj, "excessive wake lock");
13448 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013449 } else if (doCpuKills && uptimeSince > 0
13450 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13451 synchronized (stats) {
13452 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13453 uptimeSince, cputimeUsed);
13454 }
13455 Slog.w(TAG, "Excessive CPU in " + app.processName
13456 + " (pid " + app.pid + "): used " + cputimeUsed
13457 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013458 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013459 app.processName, app.setAdj, "excessive cpu");
13460 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013461 } else {
13462 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013463 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013464 }
13465 }
13466 }
13467 }
13468
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013469 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013470 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013471 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013472 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013473 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474
13475 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013476 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013477 }
13478
Dianne Hackborn287952c2010-09-22 22:34:31 -070013479 final boolean wasKeeping = app.keeping;
13480
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013481 boolean success = true;
13482
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013483 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013484
Jeff Brown10e89712011-07-08 18:52:57 -070013485 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013486 if (wasKeeping && !app.keeping) {
13487 // This app is no longer something we want to keep. Note
13488 // its current wake lock time to later know to kill it if
13489 // it is not behaving well.
13490 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13491 synchronized (stats) {
13492 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13493 app.pid, SystemClock.elapsedRealtime());
13494 }
13495 app.lastCpuTime = app.curCpuTime;
13496 }
13497
13498 app.setRawAdj = app.curRawAdj;
13499 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013500
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013501 if (app.curAdj != app.setAdj) {
13502 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013503 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013504 TAG, "Set " + app.pid + " " + app.processName +
13505 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013506 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013507 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013508 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013509 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013510 }
13511 }
13512 if (app.setSchedGroup != app.curSchedGroup) {
13513 app.setSchedGroup = app.curSchedGroup;
13514 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13515 "Setting process group of " + app.processName
13516 + " to " + app.curSchedGroup);
13517 if (app.waitingToKill != null &&
13518 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13519 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013520 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013521 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013522 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013523 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013524 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013525 } else {
13526 if (true) {
13527 long oldId = Binder.clearCallingIdentity();
13528 try {
13529 Process.setProcessGroup(app.pid, app.curSchedGroup);
13530 } catch (Exception e) {
13531 Slog.w(TAG, "Failed setting process group of " + app.pid
13532 + " to " + app.curSchedGroup);
13533 e.printStackTrace();
13534 } finally {
13535 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013536 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013537 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013538 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013539 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013540 app.thread.setSchedulingGroup(app.curSchedGroup);
13541 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013542 }
13543 }
13544 }
13545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013547 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013548 }
13549
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013550 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013551 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013553 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013554 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013555 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013556 }
13557 }
13558 return resumedActivity;
13559 }
13560
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013561 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013562 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013563 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13564 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013565 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13566 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013567
13568 mAdjSeq++;
13569
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013570 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13571 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013572 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13573 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013574 if (nowHidden != wasHidden) {
13575 // Changed to/from hidden state, so apps after it in the LRU
13576 // list may also be changed.
13577 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013578 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013579 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013580 }
13581
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013582 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013583 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013585 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013586
13587 if (false) {
13588 RuntimeException e = new RuntimeException();
13589 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013590 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013591 }
13592
13593 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013594 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013595
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013596 final int emptyProcessLimit;
13597 final int hiddenProcessLimit;
13598 if (mProcessLimit <= 0) {
13599 emptyProcessLimit = hiddenProcessLimit = 0;
13600 } else if (mProcessLimit == 1) {
13601 emptyProcessLimit = 1;
13602 hiddenProcessLimit = 0;
13603 } else {
13604 emptyProcessLimit = (mProcessLimit*2)/3;
13605 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13606 }
13607
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013608 // Let's determine how many processes we have running vs.
13609 // how many slots we have for background processes; we may want
13610 // to put multiple processes in a slot of there are enough of
13611 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013612 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13613 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013614 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13615 if (numEmptyProcs > hiddenProcessLimit) {
13616 // If there are more empty processes than our limit on hidden
13617 // processes, then use the hidden process limit for the factor.
13618 // This ensures that the really old empty processes get pushed
13619 // down to the bottom, so if we are running low on memory we will
13620 // have a better chance at keeping around more hidden processes
13621 // instead of a gazillion empty processes.
13622 numEmptyProcs = hiddenProcessLimit;
13623 }
13624 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013625 if (emptyFactor < 1) emptyFactor = 1;
13626 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13627 if (hiddenFactor < 1) hiddenFactor = 1;
13628 int stepHidden = 0;
13629 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013630 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013631 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013632 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013633
13634 mNumNonHiddenProcs = 0;
13635 mNumHiddenProcs = 0;
13636
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013637 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013638 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013639 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013640 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013641 int nextHiddenAdj = curHiddenAdj+1;
13642 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13643 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013644 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013645 while (i > 0) {
13646 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013647 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013648 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013649 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013650 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013651 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13652 // This process was assigned as a hidden process... step the
13653 // hidden level.
13654 mNumHiddenProcs++;
13655 if (curHiddenAdj != nextHiddenAdj) {
13656 stepHidden++;
13657 if (stepHidden >= hiddenFactor) {
13658 stepHidden = 0;
13659 curHiddenAdj = nextHiddenAdj;
13660 nextHiddenAdj += 2;
13661 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13662 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13663 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013664 if (curClientHiddenAdj <= curHiddenAdj) {
13665 curClientHiddenAdj = curHiddenAdj + 1;
13666 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13667 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13668 }
13669 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013670 }
13671 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013672 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013673 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013674 Slog.i(TAG, "No longer want " + app.processName
13675 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013676 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013677 app.processName, app.setAdj, "too many background");
13678 app.killedBackground = true;
13679 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013680 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013681 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13682 // This process has a client that has activities. We will have
13683 // given it the current hidden adj; here we will just leave it
13684 // without stepping the hidden adj.
13685 curClientHiddenAdj++;
13686 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13687 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13688 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013689 } else {
13690 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13691 // This process was assigned as an empty process... step the
13692 // empty level.
13693 if (curEmptyAdj != nextEmptyAdj) {
13694 stepEmpty++;
13695 if (stepEmpty >= emptyFactor) {
13696 stepEmpty = 0;
13697 curEmptyAdj = nextEmptyAdj;
13698 nextEmptyAdj += 2;
13699 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13700 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13701 }
13702 }
13703 }
13704 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13705 mNumNonHiddenProcs++;
13706 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013707 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13708 && !app.hasClientActivities) {
13709 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13710 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013711 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013712 + " (pid " + app.pid + "): empty for "
13713 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13714 / 1000) + "s");
13715 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13716 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013717 app.killedBackground = true;
13718 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013719 } else {
13720 numEmpty++;
13721 if (numEmpty > emptyProcessLimit) {
13722 Slog.i(TAG, "No longer want " + app.processName
13723 + " (pid " + app.pid + "): empty #" + numEmpty);
13724 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13725 app.processName, app.setAdj, "too many background");
13726 app.killedBackground = true;
13727 Process.killProcessQuiet(app.pid);
13728 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013729 }
13730 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013731 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013732 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013733 // If this is an isolated process, and there are no
13734 // services running in it, then the process is no longer
13735 // needed. We agressively kill these because we can by
13736 // definition not re-use the same process again, and it is
13737 // good to avoid having whatever code was running in them
13738 // left sitting around after no longer needed.
13739 Slog.i(TAG, "Isolated process " + app.processName
13740 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013741 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013742 app.processName, app.setAdj, "isolated not needed");
13743 app.killedBackground = true;
13744 Process.killProcessQuiet(app.pid);
13745 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013746 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13747 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13748 && !app.killedBackground) {
13749 numTrimming++;
13750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013751 }
13752 }
13753
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013754 mNumServiceProcs = mNewNumServiceProcs;
13755
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013756 // Now determine the memory trimming level of background processes.
13757 // Unfortunately we need to start at the back of the list to do this
13758 // properly. We only do this if the number of background apps we
13759 // are managing to keep around is less than half the maximum we desire;
13760 // if we are keeping a good number around, we'll let them use whatever
13761 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013762 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13763 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013764 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013765 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013766 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013767 int minFactor = 2;
13768 if (mHomeProcess != null) minFactor++;
13769 if (mPreviousProcess != null) minFactor++;
13770 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013771 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013772 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013773 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013774 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013775 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013776 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13777 } else {
13778 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13779 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013780 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013781 for (i=0; i<N; i++) {
13782 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013783 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13784 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013785 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013786 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13787 try {
13788 app.thread.scheduleTrimMemory(curLevel);
13789 } catch (RemoteException e) {
13790 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013791 if (false) {
13792 // For now we won't do this; our memory trimming seems
13793 // to be good enough at this point that destroying
13794 // activities causes more harm than good.
13795 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13796 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013797 // Need to do this on its own message because the stack may not
13798 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013799 // For these apps we will also finish their activities
13800 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013801 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013802 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013803 }
13804 }
13805 app.trimMemoryLevel = curLevel;
13806 step++;
13807 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013808 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013809 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013810 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13811 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013812 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013813 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13814 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013815 break;
13816 }
13817 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013818 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013819 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013820 && app.thread != null) {
13821 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013822 app.thread.scheduleTrimMemory(
13823 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013824 } catch (RemoteException e) {
13825 }
13826 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013827 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013828 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013829 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013830 && app.pendingUiClean) {
13831 // If this application is now in the background and it
13832 // had done UI, then give it the special trim level to
13833 // have it free UI resources.
13834 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13835 if (app.trimMemoryLevel < level && app.thread != null) {
13836 try {
13837 app.thread.scheduleTrimMemory(level);
13838 } catch (RemoteException e) {
13839 }
13840 }
13841 app.pendingUiClean = false;
13842 }
13843 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013844 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013845 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013846 } catch (RemoteException e) {
13847 }
13848 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013849 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013850 }
13851 }
13852 } else {
13853 final int N = mLruProcesses.size();
13854 for (i=0; i<N; i++) {
13855 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013856 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013857 && app.pendingUiClean) {
13858 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13859 && app.thread != null) {
13860 try {
13861 app.thread.scheduleTrimMemory(
13862 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13863 } catch (RemoteException e) {
13864 }
13865 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013866 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013867 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013868 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013869 }
13870 }
13871
13872 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013873 // Need to do this on its own message because the stack may not
13874 // be in a consistent state at this point.
13875 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013877 }
13878
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013879 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013880 synchronized (this) {
13881 int i;
13882
13883 // First remove any unused application processes whose package
13884 // has been removed.
13885 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13886 final ProcessRecord app = mRemovedProcesses.get(i);
13887 if (app.activities.size() == 0
13888 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013889 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 TAG, "Exiting empty application process "
13891 + app.processName + " ("
13892 + (app.thread != null ? app.thread.asBinder() : null)
13893 + ")\n");
13894 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013895 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013896 app.processName, app.setAdj, "empty");
13897 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013898 } else {
13899 try {
13900 app.thread.scheduleExit();
13901 } catch (Exception e) {
13902 // Ignore exceptions.
13903 }
13904 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013905 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013906 mRemovedProcesses.remove(i);
13907
13908 if (app.persistent) {
13909 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013910 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 }
13912 }
13913 }
13914 }
13915
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013916 // Now update the oom adj for all processes.
13917 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013918 }
13919 }
13920
13921 /** This method sends the specified signal to each of the persistent apps */
13922 public void signalPersistentProcesses(int sig) throws RemoteException {
13923 if (sig != Process.SIGNAL_USR1) {
13924 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13925 }
13926
13927 synchronized (this) {
13928 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13929 != PackageManager.PERMISSION_GRANTED) {
13930 throw new SecurityException("Requires permission "
13931 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13932 }
13933
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013934 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13935 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013936 if (r.thread != null && r.persistent) {
13937 Process.sendSignal(r.pid, sig);
13938 }
13939 }
13940 }
13941 }
13942
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013943 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13944 if (proc == null || proc == mProfileProc) {
13945 proc = mProfileProc;
13946 path = mProfileFile;
13947 profileType = mProfileType;
13948 clearProfilerLocked();
13949 }
13950 if (proc == null) {
13951 return;
13952 }
13953 try {
13954 proc.thread.profilerControl(false, path, null, profileType);
13955 } catch (RemoteException e) {
13956 throw new IllegalStateException("Process disappeared");
13957 }
13958 }
13959
13960 private void clearProfilerLocked() {
13961 if (mProfileFd != null) {
13962 try {
13963 mProfileFd.close();
13964 } catch (IOException e) {
13965 }
13966 }
13967 mProfileApp = null;
13968 mProfileProc = null;
13969 mProfileFile = null;
13970 mProfileType = 0;
13971 mAutoStopProfiler = false;
13972 }
13973
Dianne Hackborn1676c852012-09-10 14:52:30 -070013974 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013975 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013976
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013977 try {
13978 synchronized (this) {
13979 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13980 // its own permission.
13981 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13982 != PackageManager.PERMISSION_GRANTED) {
13983 throw new SecurityException("Requires permission "
13984 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013985 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013986
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013987 if (start && fd == null) {
13988 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013989 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013990
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013991 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013992 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013993 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013994 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013995
13996 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013997 throw new IllegalArgumentException("Unknown process: " + process);
13998 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013999
14000 if (start) {
14001 stopProfilerLocked(null, null, 0);
14002 setProfileApp(proc.info, proc.processName, path, fd, false);
14003 mProfileProc = proc;
14004 mProfileType = profileType;
14005 try {
14006 fd = fd.dup();
14007 } catch (IOException e) {
14008 fd = null;
14009 }
14010 proc.thread.profilerControl(start, path, fd, profileType);
14011 fd = null;
14012 mProfileFd = null;
14013 } else {
14014 stopProfilerLocked(proc, path, profileType);
14015 if (fd != null) {
14016 try {
14017 fd.close();
14018 } catch (IOException e) {
14019 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014020 }
14021 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014022
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014023 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014024 }
14025 } catch (RemoteException e) {
14026 throw new IllegalStateException("Process disappeared");
14027 } finally {
14028 if (fd != null) {
14029 try {
14030 fd.close();
14031 } catch (IOException e) {
14032 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014033 }
14034 }
14035 }
Andy McFadden824c5102010-07-09 16:26:57 -070014036
Dianne Hackborn1676c852012-09-10 14:52:30 -070014037 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014038 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014039 userId, true, true, callName, null);
14040 ProcessRecord proc = null;
14041 try {
14042 int pid = Integer.parseInt(process);
14043 synchronized (mPidsSelfLocked) {
14044 proc = mPidsSelfLocked.get(pid);
14045 }
14046 } catch (NumberFormatException e) {
14047 }
14048
14049 if (proc == null) {
14050 HashMap<String, SparseArray<ProcessRecord>> all
14051 = mProcessNames.getMap();
14052 SparseArray<ProcessRecord> procs = all.get(process);
14053 if (procs != null && procs.size() > 0) {
14054 proc = procs.valueAt(0);
14055 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14056 for (int i=1; i<procs.size(); i++) {
14057 ProcessRecord thisProc = procs.valueAt(i);
14058 if (thisProc.userId == userId) {
14059 proc = thisProc;
14060 break;
14061 }
14062 }
14063 }
14064 }
14065 }
14066
14067 return proc;
14068 }
14069
14070 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014071 String path, ParcelFileDescriptor fd) throws RemoteException {
14072
14073 try {
14074 synchronized (this) {
14075 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14076 // its own permission (same as profileControl).
14077 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14078 != PackageManager.PERMISSION_GRANTED) {
14079 throw new SecurityException("Requires permission "
14080 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14081 }
14082
14083 if (fd == null) {
14084 throw new IllegalArgumentException("null fd");
14085 }
14086
Dianne Hackborn1676c852012-09-10 14:52:30 -070014087 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014088 if (proc == null || proc.thread == null) {
14089 throw new IllegalArgumentException("Unknown process: " + process);
14090 }
14091
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014092 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14093 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014094 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14095 throw new SecurityException("Process not debuggable: " + proc);
14096 }
14097 }
14098
14099 proc.thread.dumpHeap(managed, path, fd);
14100 fd = null;
14101 return true;
14102 }
14103 } catch (RemoteException e) {
14104 throw new IllegalStateException("Process disappeared");
14105 } finally {
14106 if (fd != null) {
14107 try {
14108 fd.close();
14109 } catch (IOException e) {
14110 }
14111 }
14112 }
14113 }
14114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014115 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14116 public void monitor() {
14117 synchronized (this) { }
14118 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014119
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014120 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014121 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14122 ProcessRecord processRecord = mLruProcesses.get(i);
14123 try {
14124 if (processRecord.thread != null) {
14125 processRecord.thread.setCoreSettings(settings);
14126 }
14127 } catch (RemoteException re) {
14128 /* ignore */
14129 }
14130 }
14131 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014132
14133 // Multi-user methods
14134
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014135 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014136 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014137 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14138 != PackageManager.PERMISSION_GRANTED) {
14139 String msg = "Permission Denial: switchUser() from pid="
14140 + Binder.getCallingPid()
14141 + ", uid=" + Binder.getCallingUid()
14142 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14143 Slog.w(TAG, msg);
14144 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014145 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014146
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014147 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014148 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014149 synchronized (this) {
14150 final int oldUserId = mCurrentUserId;
14151 if (oldUserId == userId) {
14152 return true;
14153 }
14154
14155 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14156 if (userInfo == null) {
14157 Slog.w(TAG, "No user info for user #" + userId);
14158 return false;
14159 }
14160
14161 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14162 R.anim.screen_user_enter);
14163
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014164 boolean needStart = false;
14165
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014166 // If the user we are switching to is not currently started, then
14167 // we need to start it now.
14168 if (mStartedUsers.get(userId) == null) {
14169 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014170 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014171 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014172 }
14173
14174 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014175 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014176 final Integer userIdInt = Integer.valueOf(userId);
14177 mUserLru.remove(userIdInt);
14178 mUserLru.add(userIdInt);
14179
Craig Mautnerf1b67412012-09-19 13:18:29 -070014180 mWindowManager.setCurrentUser(userId);
14181
Adam Cohenf7522022012-10-03 20:03:18 -070014182 // Once the internal notion of the active user has switched, we lock the device
14183 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014184 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014185
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014186 final UserStartedState uss = mStartedUsers.get(userId);
14187
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014188 // Make sure user is in the started state. If it is currently
14189 // stopping, we need to knock that off.
14190 if (uss.mState == UserStartedState.STATE_STOPPING) {
14191 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14192 // so we can just fairly silently bring the user back from
14193 // the almost-dead.
14194 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014195 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014196 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014197 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14198 // This means ACTION_SHUTDOWN has been sent, so we will
14199 // need to treat this as a new boot of the user.
14200 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014201 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014202 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014203 }
14204
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014205 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14206 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14207 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14208 oldUserId, userId, uss));
14209 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14210 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014211 if (needStart) {
14212 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14213 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14214 | Intent.FLAG_RECEIVER_FOREGROUND);
14215 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14216 broadcastIntentLocked(null, null, intent,
14217 null, null, 0, null, null, null,
14218 false, false, MY_PID, Process.SYSTEM_UID, userId);
14219 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014220
14221 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14222 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014223 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014224 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014225 broadcastIntentLocked(null, null, intent, null,
14226 new IIntentReceiver.Stub() {
14227 public void performReceive(Intent intent, int resultCode,
14228 String data, Bundle extras, boolean ordered,
14229 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014230 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014231 }
14232 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14233 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014234 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014235 } else {
14236 getUserManagerLocked().makeInitialized(userInfo.id);
14237 }
14238 }
14239
14240 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14241 if (!haveActivities) {
14242 startHomeActivityLocked(userId);
14243 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014244
Jeff Sharkey86597df2012-11-09 15:00:31 -080014245 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014246 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014247 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014248 if (needStart) {
14249 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14250 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14251 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14252 broadcastIntentLocked(null, null, intent,
14253 null, new IIntentReceiver.Stub() {
14254 @Override
14255 public void performReceive(Intent intent, int resultCode, String data,
14256 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14257 throws RemoteException {
14258 }
14259 }, 0, null, null,
14260 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014261 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014262 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014263 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014264 } finally {
14265 Binder.restoreCallingIdentity(ident);
14266 }
Amith Yamasani13593602012-03-22 16:16:17 -070014267
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014268 return true;
14269 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014270
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014271 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14272 long ident = Binder.clearCallingIdentity();
14273 try {
14274 Intent intent;
14275 if (oldUserId >= 0) {
14276 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014277 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14278 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014279 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14280 broadcastIntentLocked(null, null, intent,
14281 null, null, 0, null, null, null,
14282 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14283 }
14284 if (newUserId >= 0) {
14285 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014286 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14287 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014288 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14289 broadcastIntentLocked(null, null, intent,
14290 null, null, 0, null, null, null,
14291 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14292 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014293 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14294 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014295 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14296 broadcastIntentLocked(null, null, intent,
14297 null, null, 0, null, null,
14298 android.Manifest.permission.MANAGE_USERS,
14299 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14300 }
14301 } finally {
14302 Binder.restoreCallingIdentity(ident);
14303 }
14304 }
14305
14306 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14307 final int newUserId) {
14308 final int N = mUserSwitchObservers.beginBroadcast();
14309 if (N > 0) {
14310 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14311 int mCount = 0;
14312 @Override
14313 public void sendResult(Bundle data) throws RemoteException {
14314 synchronized (ActivityManagerService.this) {
14315 if (mCurUserSwitchCallback == this) {
14316 mCount++;
14317 if (mCount == N) {
14318 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14319 }
14320 }
14321 }
14322 }
14323 };
14324 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014325 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014326 mCurUserSwitchCallback = callback;
14327 }
14328 for (int i=0; i<N; i++) {
14329 try {
14330 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14331 newUserId, callback);
14332 } catch (RemoteException e) {
14333 }
14334 }
14335 } else {
14336 synchronized (this) {
14337 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14338 }
14339 }
14340 mUserSwitchObservers.finishBroadcast();
14341 }
14342
14343 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14344 synchronized (this) {
14345 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14346 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14347 }
14348 }
14349
14350 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14351 mCurUserSwitchCallback = null;
14352 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14353 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14354 oldUserId, newUserId, uss));
14355 }
14356
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014357 void userInitialized(UserStartedState uss, int newUserId) {
14358 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014359 }
14360
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014361 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014362 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014363 }
14364
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014365 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14366 boolean clearInitializing, boolean clearSwitching) {
14367 boolean unfrozen = false;
14368 synchronized (this) {
14369 if (clearInitializing) {
14370 uss.initializing = false;
14371 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14372 }
14373 if (clearSwitching) {
14374 uss.switching = false;
14375 }
14376 if (!uss.switching && !uss.initializing) {
14377 mWindowManager.stopFreezingScreen();
14378 unfrozen = true;
14379 }
14380 }
14381 if (unfrozen) {
14382 final int N = mUserSwitchObservers.beginBroadcast();
14383 for (int i=0; i<N; i++) {
14384 try {
14385 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14386 } catch (RemoteException e) {
14387 }
14388 }
14389 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014390 }
14391 }
14392
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014393 void finishUserSwitch(UserStartedState uss) {
14394 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014395 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014396 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14397 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014398 final int userId = uss.mHandle.getIdentifier();
14399 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14400 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14401 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014402 null, null, 0, null, null,
14403 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014404 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014405 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014406 int num = mUserLru.size();
14407 int i = 0;
14408 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14409 Integer oldUserId = mUserLru.get(i);
14410 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14411 if (oldUss == null) {
14412 // Shouldn't happen, but be sane if it does.
14413 mUserLru.remove(i);
14414 num--;
14415 continue;
14416 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014417 if (oldUss.mState == UserStartedState.STATE_STOPPING
14418 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014419 // This user is already stopping, doesn't count.
14420 num--;
14421 i++;
14422 continue;
14423 }
14424 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14425 // Owner and current can't be stopped, but count as running.
14426 i++;
14427 continue;
14428 }
14429 // This is a user to be stopped.
14430 stopUserLocked(oldUserId, null);
14431 num--;
14432 i++;
14433 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014434 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014435 }
14436
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014437 @Override
14438 public int stopUser(final int userId, final IStopUserCallback callback) {
14439 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14440 != PackageManager.PERMISSION_GRANTED) {
14441 String msg = "Permission Denial: switchUser() from pid="
14442 + Binder.getCallingPid()
14443 + ", uid=" + Binder.getCallingUid()
14444 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14445 Slog.w(TAG, msg);
14446 throw new SecurityException(msg);
14447 }
14448 if (userId <= 0) {
14449 throw new IllegalArgumentException("Can't stop primary user " + userId);
14450 }
Amith Yamasani13593602012-03-22 16:16:17 -070014451 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014452 return stopUserLocked(userId, callback);
14453 }
14454 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014455
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014456 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14457 if (mCurrentUserId == userId) {
14458 return ActivityManager.USER_OP_IS_CURRENT;
14459 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014460
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014461 final UserStartedState uss = mStartedUsers.get(userId);
14462 if (uss == null) {
14463 // User is not started, nothing to do... but we do need to
14464 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014465 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014466 mHandler.post(new Runnable() {
14467 @Override
14468 public void run() {
14469 try {
14470 callback.userStopped(userId);
14471 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014472 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014473 }
14474 });
14475 }
14476 return ActivityManager.USER_OP_SUCCESS;
14477 }
14478
14479 if (callback != null) {
14480 uss.mStopCallbacks.add(callback);
14481 }
14482
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014483 if (uss.mState != UserStartedState.STATE_STOPPING
14484 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014485 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014486 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014487
14488 long ident = Binder.clearCallingIdentity();
14489 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014490 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014491 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014492 // stop the user.
14493 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14494 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14495 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14496 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14497 // This is the result receiver for the final shutdown broadcast.
14498 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014499 @Override
14500 public void performReceive(Intent intent, int resultCode, String data,
14501 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14502 finishUserStop(uss);
14503 }
14504 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014505 // This is the result receiver for the initial stopping broadcast.
14506 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14507 @Override
14508 public void performReceive(Intent intent, int resultCode, String data,
14509 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14510 // On to the next.
14511 synchronized (ActivityManagerService.this) {
14512 if (uss.mState != UserStartedState.STATE_STOPPING) {
14513 // Whoops, we are being started back up. Abort, abort!
14514 return;
14515 }
14516 uss.mState = UserStartedState.STATE_SHUTDOWN;
14517 }
14518 broadcastIntentLocked(null, null, shutdownIntent,
14519 null, shutdownReceiver, 0, null, null, null,
14520 true, false, MY_PID, Process.SYSTEM_UID, userId);
14521 }
14522 };
14523 // Kick things off.
14524 broadcastIntentLocked(null, null, stoppingIntent,
14525 null, stoppingReceiver, 0, null, null,
14526 android.Manifest.permission.INTERACT_ACROSS_USERS,
14527 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014528 } finally {
14529 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014530 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014531 }
Amith Yamasani13593602012-03-22 16:16:17 -070014532
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014533 return ActivityManager.USER_OP_SUCCESS;
14534 }
14535
14536 void finishUserStop(UserStartedState uss) {
14537 final int userId = uss.mHandle.getIdentifier();
14538 boolean stopped;
14539 ArrayList<IStopUserCallback> callbacks;
14540 synchronized (this) {
14541 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014542 if (mStartedUsers.get(userId) != uss) {
14543 stopped = false;
14544 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014545 stopped = false;
14546 } else {
14547 stopped = true;
14548 // User can no longer run.
14549 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014550 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014551 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014552
14553 // Clean up all state and processes associated with the user.
14554 // Kill all the processes for the user.
14555 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014556 }
14557 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014558
14559 for (int i=0; i<callbacks.size(); i++) {
14560 try {
14561 if (stopped) callbacks.get(i).userStopped(userId);
14562 else callbacks.get(i).userStopAborted(userId);
14563 } catch (RemoteException e) {
14564 }
14565 }
14566 }
14567
14568 @Override
14569 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014570 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14571 != PackageManager.PERMISSION_GRANTED) && (
14572 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14573 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014574 String msg = "Permission Denial: getCurrentUser() from pid="
14575 + Binder.getCallingPid()
14576 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014577 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014578 Slog.w(TAG, msg);
14579 throw new SecurityException(msg);
14580 }
14581 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014582 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014583 }
Amith Yamasani13593602012-03-22 16:16:17 -070014584 }
14585
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014586 int getCurrentUserIdLocked() {
14587 return mCurrentUserId;
14588 }
14589
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014590 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014591 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014592 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14593 != PackageManager.PERMISSION_GRANTED) {
14594 String msg = "Permission Denial: isUserRunning() from pid="
14595 + Binder.getCallingPid()
14596 + ", uid=" + Binder.getCallingUid()
14597 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14598 Slog.w(TAG, msg);
14599 throw new SecurityException(msg);
14600 }
14601 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014602 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014603 }
14604 }
14605
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014606 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014607 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014608 if (state == null) {
14609 return false;
14610 }
14611 if (orStopped) {
14612 return true;
14613 }
14614 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014615 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014616 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014617
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014618 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014619 public int[] getRunningUserIds() {
14620 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14621 != PackageManager.PERMISSION_GRANTED) {
14622 String msg = "Permission Denial: isUserRunning() from pid="
14623 + Binder.getCallingPid()
14624 + ", uid=" + Binder.getCallingUid()
14625 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14626 Slog.w(TAG, msg);
14627 throw new SecurityException(msg);
14628 }
14629 synchronized (this) {
14630 return mStartedUserArray;
14631 }
14632 }
14633
14634 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014635 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014636 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014637 UserStartedState uss = mStartedUsers.valueAt(i);
14638 // This list does not include stopping users.
14639 if (uss.mState != UserStartedState.STATE_STOPPING
14640 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14641 num++;
14642 }
14643 }
14644 mStartedUserArray = new int[num];
14645 num = 0;
14646 for (int i=0; i<mStartedUsers.size(); i++) {
14647 UserStartedState uss = mStartedUsers.valueAt(i);
14648 if (uss.mState != UserStartedState.STATE_STOPPING
14649 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14650 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14651 num++;
14652 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014653 }
14654 }
14655
14656 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014657 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14658 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14659 != PackageManager.PERMISSION_GRANTED) {
14660 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14661 + Binder.getCallingPid()
14662 + ", uid=" + Binder.getCallingUid()
14663 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14664 Slog.w(TAG, msg);
14665 throw new SecurityException(msg);
14666 }
14667
14668 mUserSwitchObservers.register(observer);
14669 }
14670
14671 @Override
14672 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14673 mUserSwitchObservers.unregister(observer);
14674 }
14675
Dianne Hackborn1676c852012-09-10 14:52:30 -070014676 private boolean userExists(int userId) {
14677 if (userId == 0) {
14678 return true;
14679 }
14680 UserManagerService ums = getUserManagerLocked();
14681 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14682 }
14683
14684 int[] getUsersLocked() {
14685 UserManagerService ums = getUserManagerLocked();
14686 return ums != null ? ums.getUserIds() : new int[] { 0 };
14687 }
14688
14689 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014690 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014691 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14692 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014693 }
14694 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014695 }
14696
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014697 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014698 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014699
14700 throw new SecurityException("Caller uid=" + uid
14701 + " is not privileged to communicate with user=" + userId);
14702 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014703
14704 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014705 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014706 }
14707
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014708 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014709 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014710 ApplicationInfo newInfo = new ApplicationInfo(info);
14711 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014712 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14713 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014714 return newInfo;
14715 }
14716
14717 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014718 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014719 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014720 return aInfo;
14721 }
14722
14723 ActivityInfo info = new ActivityInfo(aInfo);
14724 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14725 return info;
14726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014727}