blob: 222b44a3b54965e5ba9be330ff9f91620502d096 [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,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700973 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700974 d.show();
975 proc.anrDialog = d;
976 } else {
977 // Just kill the app if there is no dialog to be shown.
978 killAppAtUsersRequest(proc, null);
979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700981
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700982 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700984 case SHOW_STRICT_MODE_VIOLATION_MSG: {
985 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
986 synchronized (ActivityManagerService.this) {
987 ProcessRecord proc = (ProcessRecord) data.get("app");
988 if (proc == null) {
989 Slog.e(TAG, "App not found when showing strict mode dialog.");
990 break;
991 }
992 if (proc.crashDialog != null) {
993 Slog.e(TAG, "App already has strict mode dialog: " + proc);
994 return;
995 }
996 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700997 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700998 Dialog d = new StrictModeViolationDialog(mContext,
999 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001000 d.show();
1001 proc.crashDialog = d;
1002 } else {
1003 // The device is asleep, so just pretend that the user
1004 // saw a crash dialog and hit "force quit".
1005 res.set(0);
1006 }
1007 }
1008 ensureBootCompleted();
1009 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 case SHOW_FACTORY_ERROR_MSG: {
1011 Dialog d = new FactoryErrorDialog(
1012 mContext, msg.getData().getCharSequence("msg"));
1013 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001014 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 } break;
1016 case UPDATE_CONFIGURATION_MSG: {
1017 final ContentResolver resolver = mContext.getContentResolver();
1018 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1019 } break;
1020 case GC_BACKGROUND_PROCESSES_MSG: {
1021 synchronized (ActivityManagerService.this) {
1022 performAppGcsIfAppropriateLocked();
1023 }
1024 } break;
1025 case WAIT_FOR_DEBUGGER_MSG: {
1026 synchronized (ActivityManagerService.this) {
1027 ProcessRecord app = (ProcessRecord)msg.obj;
1028 if (msg.arg1 != 0) {
1029 if (!app.waitedForDebugger) {
1030 Dialog d = new AppWaitingForDebuggerDialog(
1031 ActivityManagerService.this,
1032 mContext, app);
1033 app.waitDialog = d;
1034 app.waitedForDebugger = true;
1035 d.show();
1036 }
1037 } else {
1038 if (app.waitDialog != null) {
1039 app.waitDialog.dismiss();
1040 app.waitDialog = null;
1041 }
1042 }
1043 }
1044 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001046 if (mDidDexOpt) {
1047 mDidDexOpt = false;
1048 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1049 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001050 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001051 return;
1052 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001053 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 } break;
1055 case UPDATE_TIME_ZONE: {
1056 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001057 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1058 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 if (r.thread != null) {
1060 try {
1061 r.thread.updateTimeZone();
1062 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001063 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065 }
1066 }
1067 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001068 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001069 case CLEAR_DNS_CACHE: {
1070 synchronized (ActivityManagerService.this) {
1071 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1072 ProcessRecord r = mLruProcesses.get(i);
1073 if (r.thread != null) {
1074 try {
1075 r.thread.clearDnsCache();
1076 } catch (RemoteException ex) {
1077 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1078 }
1079 }
1080 }
1081 }
1082 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001083 case UPDATE_HTTP_PROXY: {
1084 ProxyProperties proxy = (ProxyProperties)msg.obj;
1085 String host = "";
1086 String port = "";
1087 String exclList = "";
1088 if (proxy != null) {
1089 host = proxy.getHost();
1090 port = Integer.toString(proxy.getPort());
1091 exclList = proxy.getExclusionList();
1092 }
1093 synchronized (ActivityManagerService.this) {
1094 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1095 ProcessRecord r = mLruProcesses.get(i);
1096 if (r.thread != null) {
1097 try {
1098 r.thread.setHttpProxy(host, port, exclList);
1099 } catch (RemoteException ex) {
1100 Slog.w(TAG, "Failed to update http proxy for: " +
1101 r.info.processName);
1102 }
1103 }
1104 }
1105 }
1106 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001108 String title = "System UIDs Inconsistent";
1109 String text = "UIDs on the system are inconsistent, you need to wipe your"
1110 + " data partition or your device will be unstable.";
1111 Log.e(TAG, title + ": " + text);
1112 if (mShowDialogs) {
1113 // XXX This is a temporary dialog, no need to localize.
1114 AlertDialog d = new BaseErrorDialog(mContext);
1115 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1116 d.setCancelable(false);
1117 d.setTitle(title);
1118 d.setMessage(text);
1119 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1120 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1121 mUidAlert = d;
1122 d.show();
1123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 } break;
1125 case IM_FEELING_LUCKY_MSG: {
1126 if (mUidAlert != null) {
1127 mUidAlert.dismiss();
1128 mUidAlert = null;
1129 }
1130 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001132 if (mDidDexOpt) {
1133 mDidDexOpt = false;
1134 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1135 nmsg.obj = msg.obj;
1136 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1137 return;
1138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 ProcessRecord app = (ProcessRecord)msg.obj;
1140 synchronized (ActivityManagerService.this) {
1141 processStartTimedOutLocked(app);
1142 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001143 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001144 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1145 synchronized (ActivityManagerService.this) {
1146 doPendingActivityLaunchesLocked(true);
1147 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001148 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001149 case KILL_APPLICATION_MSG: {
1150 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001151 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001152 boolean restart = (msg.arg2 == 1);
1153 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001154 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1155 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001156 }
1157 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001158 case FINALIZE_PENDING_INTENT_MSG: {
1159 ((PendingIntentRecord)msg.obj).completeFinalize();
1160 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001161 case POST_HEAVY_NOTIFICATION_MSG: {
1162 INotificationManager inm = NotificationManager.getService();
1163 if (inm == null) {
1164 return;
1165 }
1166
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001167 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001168 ProcessRecord process = root.app;
1169 if (process == null) {
1170 return;
1171 }
1172
1173 try {
1174 Context context = mContext.createPackageContext(process.info.packageName, 0);
1175 String text = mContext.getString(R.string.heavy_weight_notification,
1176 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1177 Notification notification = new Notification();
1178 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1179 notification.when = 0;
1180 notification.flags = Notification.FLAG_ONGOING_EVENT;
1181 notification.tickerText = text;
1182 notification.defaults = 0; // please be quiet
1183 notification.sound = null;
1184 notification.vibrate = null;
1185 notification.setLatestEventInfo(context, text,
1186 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001187 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1188 PendingIntent.FLAG_CANCEL_CURRENT, null,
1189 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001190
1191 try {
1192 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001193 inm.enqueueNotificationWithTag("android", null,
1194 R.string.heavy_weight_notification,
1195 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001196 } catch (RuntimeException e) {
1197 Slog.w(ActivityManagerService.TAG,
1198 "Error showing notification for heavy-weight app", e);
1199 } catch (RemoteException e) {
1200 }
1201 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001202 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001203 }
1204 } break;
1205 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1206 INotificationManager inm = NotificationManager.getService();
1207 if (inm == null) {
1208 return;
1209 }
1210 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001211 inm.cancelNotificationWithTag("android", null,
1212 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001213 } catch (RuntimeException e) {
1214 Slog.w(ActivityManagerService.TAG,
1215 "Error canceling notification for service", e);
1216 } catch (RemoteException e) {
1217 }
1218 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001219 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1220 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001221 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001222 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001223 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1224 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001225 }
1226 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001227 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1228 synchronized (ActivityManagerService.this) {
1229 ActivityRecord ar = (ActivityRecord)msg.obj;
1230 if (mCompatModeDialog != null) {
1231 if (mCompatModeDialog.mAppInfo.packageName.equals(
1232 ar.info.applicationInfo.packageName)) {
1233 return;
1234 }
1235 mCompatModeDialog.dismiss();
1236 mCompatModeDialog = null;
1237 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001238 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001239 if (mCompatModePackages.getPackageAskCompatModeLocked(
1240 ar.packageName)) {
1241 int mode = mCompatModePackages.computeCompatModeLocked(
1242 ar.info.applicationInfo);
1243 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1244 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1245 mCompatModeDialog = new CompatModeDialog(
1246 ActivityManagerService.this, mContext,
1247 ar.info.applicationInfo);
1248 mCompatModeDialog.show();
1249 }
1250 }
1251 }
1252 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001253 break;
1254 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001255 case DISPATCH_PROCESSES_CHANGED: {
1256 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001257 break;
1258 }
1259 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001260 final int pid = msg.arg1;
1261 final int uid = msg.arg2;
1262 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001263 break;
1264 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001265 case REPORT_MEM_USAGE: {
1266 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1267 if (!isDebuggable) {
1268 return;
1269 }
1270 synchronized (ActivityManagerService.this) {
1271 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001272 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1273 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001274 // avoid spamming.
1275 return;
1276 }
1277 mLastMemUsageReportTime = now;
1278 }
1279 Thread thread = new Thread() {
1280 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001281 StringBuilder dropBuilder = new StringBuilder(1024);
1282 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001283 StringWriter oomSw = new StringWriter();
1284 PrintWriter oomPw = new PrintWriter(oomSw);
1285 StringWriter catSw = new StringWriter();
1286 PrintWriter catPw = new PrintWriter(catSw);
1287 String[] emptyArgs = new String[] { };
1288 StringBuilder tag = new StringBuilder(128);
1289 StringBuilder stack = new StringBuilder(128);
1290 tag.append("Low on memory -- ");
1291 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1292 tag, stack);
1293 dropBuilder.append(stack);
1294 dropBuilder.append('\n');
1295 dropBuilder.append('\n');
1296 String oomString = oomSw.toString();
1297 dropBuilder.append(oomString);
1298 dropBuilder.append('\n');
1299 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001300 try {
1301 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1302 "procrank", });
1303 final InputStreamReader converter = new InputStreamReader(
1304 proc.getInputStream());
1305 BufferedReader in = new BufferedReader(converter);
1306 String line;
1307 while (true) {
1308 line = in.readLine();
1309 if (line == null) {
1310 break;
1311 }
1312 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001313 logBuilder.append(line);
1314 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001315 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001316 dropBuilder.append(line);
1317 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001318 }
1319 converter.close();
1320 } catch (IOException e) {
1321 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001322 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001323 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001324 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001325 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001326 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1327 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001328 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001329 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001330 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001331 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001332 addErrorToDropBox("lowmem", null, "system_server", null,
1333 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001334 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001335 synchronized (ActivityManagerService.this) {
1336 long now = SystemClock.uptimeMillis();
1337 if (mLastMemUsageReportTime < now) {
1338 mLastMemUsageReportTime = now;
1339 }
1340 }
1341 }
1342 };
1343 thread.start();
1344 break;
1345 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001346 case REPORT_USER_SWITCH_MSG: {
1347 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1348 break;
1349 }
1350 case CONTINUE_USER_SWITCH_MSG: {
1351 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1352 break;
1353 }
1354 case USER_SWITCH_TIMEOUT_MSG: {
1355 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1356 break;
1357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359 }
1360 };
1361
1362 public static void setSystemProcess() {
1363 try {
1364 ActivityManagerService m = mSelf;
1365
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001366 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001368 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001369 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 if (MONITOR_CPU_USAGE) {
1371 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 ServiceManager.addService("permission", new PermissionController(m));
1374
1375 ApplicationInfo info =
1376 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001377 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001378 mSystemThread.installSystemApplicationInfo(info);
1379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 synchronized (mSelf) {
1381 ProcessRecord app = mSelf.newProcessRecordLocked(
1382 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001383 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001385 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001386 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001387 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 synchronized (mSelf.mPidsSelfLocked) {
1389 mSelf.mPidsSelfLocked.put(app.pid, app);
1390 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001391 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393 } catch (PackageManager.NameNotFoundException e) {
1394 throw new RuntimeException(
1395 "Unable to find android system package", e);
1396 }
1397 }
1398
1399 public void setWindowManager(WindowManagerService wm) {
1400 mWindowManager = wm;
1401 }
1402
1403 public static final Context main(int factoryTest) {
1404 AThread thr = new AThread();
1405 thr.start();
1406
1407 synchronized (thr) {
1408 while (thr.mService == null) {
1409 try {
1410 thr.wait();
1411 } catch (InterruptedException e) {
1412 }
1413 }
1414 }
1415
1416 ActivityManagerService m = thr.mService;
1417 mSelf = m;
1418 ActivityThread at = ActivityThread.systemMain();
1419 mSystemThread = at;
1420 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001421 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 m.mContext = context;
1423 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001424 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425
1426 m.mBatteryStatsService.publish(context);
1427 m.mUsageStatsService.publish(context);
1428
1429 synchronized (thr) {
1430 thr.mReady = true;
1431 thr.notifyAll();
1432 }
1433
1434 m.startRunning(null, null, null, null);
1435
1436 return context;
1437 }
1438
1439 public static ActivityManagerService self() {
1440 return mSelf;
1441 }
1442
1443 static class AThread extends Thread {
1444 ActivityManagerService mService;
1445 boolean mReady = false;
1446
1447 public AThread() {
1448 super("ActivityManager");
1449 }
1450
1451 public void run() {
1452 Looper.prepare();
1453
1454 android.os.Process.setThreadPriority(
1455 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001456 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457
1458 ActivityManagerService m = new ActivityManagerService();
1459
1460 synchronized (this) {
1461 mService = m;
1462 notifyAll();
1463 }
1464
1465 synchronized (this) {
1466 while (!mReady) {
1467 try {
1468 wait();
1469 } catch (InterruptedException e) {
1470 }
1471 }
1472 }
1473
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001474 // For debug builds, log event loop stalls to dropbox for analysis.
1475 if (StrictMode.conditionallyEnableDebugLogging()) {
1476 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1477 }
1478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 Looper.loop();
1480 }
1481 }
1482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 static class MemBinder extends Binder {
1484 ActivityManagerService mActivityManagerService;
1485 MemBinder(ActivityManagerService activityManagerService) {
1486 mActivityManagerService = activityManagerService;
1487 }
1488
1489 @Override
1490 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001491 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1492 != PackageManager.PERMISSION_GRANTED) {
1493 pw.println("Permission Denial: can't dump meminfo from from pid="
1494 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1495 + " without permission " + android.Manifest.permission.DUMP);
1496 return;
1497 }
1498
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001499 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001500 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 }
1503
Chet Haase9c1e23b2011-03-24 10:51:31 -07001504 static class GraphicsBinder extends Binder {
1505 ActivityManagerService mActivityManagerService;
1506 GraphicsBinder(ActivityManagerService activityManagerService) {
1507 mActivityManagerService = activityManagerService;
1508 }
1509
1510 @Override
1511 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001512 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1513 != PackageManager.PERMISSION_GRANTED) {
1514 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1515 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1516 + " without permission " + android.Manifest.permission.DUMP);
1517 return;
1518 }
1519
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001520 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001521 }
1522 }
1523
Jeff Brown6754ba22011-12-14 20:20:01 -08001524 static class DbBinder extends Binder {
1525 ActivityManagerService mActivityManagerService;
1526 DbBinder(ActivityManagerService activityManagerService) {
1527 mActivityManagerService = activityManagerService;
1528 }
1529
1530 @Override
1531 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1532 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1533 != PackageManager.PERMISSION_GRANTED) {
1534 pw.println("Permission Denial: can't dump dbinfo from from pid="
1535 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1536 + " without permission " + android.Manifest.permission.DUMP);
1537 return;
1538 }
1539
1540 mActivityManagerService.dumpDbInfo(fd, pw, args);
1541 }
1542 }
1543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 static class CpuBinder extends Binder {
1545 ActivityManagerService mActivityManagerService;
1546 CpuBinder(ActivityManagerService activityManagerService) {
1547 mActivityManagerService = activityManagerService;
1548 }
1549
1550 @Override
1551 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001552 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1553 != PackageManager.PERMISSION_GRANTED) {
1554 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1555 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1556 + " without permission " + android.Manifest.permission.DUMP);
1557 return;
1558 }
1559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001561 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1562 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1563 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 }
1566 }
1567
1568 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001569 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001570
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001571 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1572 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1573 mBroadcastQueues[0] = mFgBroadcastQueue;
1574 mBroadcastQueues[1] = mBgBroadcastQueue;
1575
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001576 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001577 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 File dataDir = Environment.getDataDirectory();
1580 File systemDir = new File(dataDir, "system");
1581 systemDir.mkdirs();
1582 mBatteryStatsService = new BatteryStatsService(new File(
1583 systemDir, "batterystats.bin").toString());
1584 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001585 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001586 mOnBattery = DEBUG_POWER ? true
1587 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001588 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001590 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001591 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001592 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001594 // User 0 is the first and only user that runs at boot.
1595 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001596 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001597 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001598
Jack Palevichb90d28c2009-07-22 15:35:24 -07001599 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1600 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1601
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001602 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001603 mConfiguration.setLocale(Locale.getDefault());
1604
Dianne Hackborn813075a62011-11-14 17:45:19 -08001605 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 mProcessStats.init();
1607
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001608 mCompatModePackages = new CompatModePackages(this, systemDir);
1609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 // Add ourself to the Watchdog monitors.
1611 Watchdog.getInstance().addMonitor(this);
1612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 mProcessStatsThread = new Thread("ProcessStats") {
1614 public void run() {
1615 while (true) {
1616 try {
1617 try {
1618 synchronized(this) {
1619 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001620 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001622 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 // + ", write delay=" + nextWriteDelay);
1624 if (nextWriteDelay < nextCpuDelay) {
1625 nextCpuDelay = nextWriteDelay;
1626 }
1627 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001628 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 this.wait(nextCpuDelay);
1630 }
1631 }
1632 } catch (InterruptedException e) {
1633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 updateCpuStatsNow();
1635 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638 }
1639 }
1640 };
1641 mProcessStatsThread.start();
1642 }
1643
1644 @Override
1645 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1646 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001647 if (code == SYSPROPS_TRANSACTION) {
1648 // We need to tell all apps about the system property change.
1649 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1650 synchronized(this) {
1651 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1652 final int NA = apps.size();
1653 for (int ia=0; ia<NA; ia++) {
1654 ProcessRecord app = apps.valueAt(ia);
1655 if (app.thread != null) {
1656 procs.add(app.thread.asBinder());
1657 }
1658 }
1659 }
1660 }
1661
1662 int N = procs.size();
1663 for (int i=0; i<N; i++) {
1664 Parcel data2 = Parcel.obtain();
1665 try {
1666 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1667 } catch (RemoteException e) {
1668 }
1669 data2.recycle();
1670 }
1671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 try {
1673 return super.onTransact(code, data, reply, flags);
1674 } catch (RuntimeException e) {
1675 // The activity manager only throws security exceptions, so let's
1676 // log all others.
1677 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001678 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680 throw e;
1681 }
1682 }
1683
1684 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001685 final long now = SystemClock.uptimeMillis();
1686 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1687 return;
1688 }
1689 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1690 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 mProcessStatsThread.notify();
1692 }
1693 }
1694 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 void updateCpuStatsNow() {
1697 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001698 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 final long now = SystemClock.uptimeMillis();
1700 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001703 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1704 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 haveNewCpuStats = true;
1706 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001707 //Slog.i(TAG, mProcessStats.printCurrentState());
1708 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 // + mProcessStats.getTotalCpuPercent() + "%");
1710
Joe Onorato8a9b2202010-02-26 18:56:32 -08001711 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 if ("true".equals(SystemProperties.get("events.cpu"))) {
1713 int user = mProcessStats.getLastUserTime();
1714 int system = mProcessStats.getLastSystemTime();
1715 int iowait = mProcessStats.getLastIoWaitTime();
1716 int irq = mProcessStats.getLastIrqTime();
1717 int softIrq = mProcessStats.getLastSoftIrqTime();
1718 int idle = mProcessStats.getLastIdleTime();
1719
1720 int total = user + system + iowait + irq + softIrq + idle;
1721 if (total == 0) total = 1;
1722
Doug Zongker2bec3d42009-12-04 12:52:44 -08001723 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 ((user+system+iowait+irq+softIrq) * 100) / total,
1725 (user * 100) / total,
1726 (system * 100) / total,
1727 (iowait * 100) / total,
1728 (irq * 100) / total,
1729 (softIrq * 100) / total);
1730 }
1731 }
1732
Amith Yamasanie43530a2009-08-21 13:11:37 -07001733 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001734 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001735 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 synchronized(mPidsSelfLocked) {
1737 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001738 if (mOnBattery) {
1739 int perc = bstats.startAddingCpuLocked();
1740 int totalUTime = 0;
1741 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001742 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001744 ProcessStats.Stats st = mProcessStats.getStats(i);
1745 if (!st.working) {
1746 continue;
1747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001749 int otherUTime = (st.rel_utime*perc)/100;
1750 int otherSTime = (st.rel_stime*perc)/100;
1751 totalUTime += otherUTime;
1752 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 if (pr != null) {
1754 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001755 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1756 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001757 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001758 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001759 } else {
1760 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001761 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001762 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001763 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1764 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001765 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001769 bstats.finishAddingCpuLocked(perc, totalUTime,
1770 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 }
1772 }
1773 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1776 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001777 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779 }
1780 }
1781 }
1782
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001783 @Override
1784 public void batteryNeedsCpuUpdate() {
1785 updateCpuStatsNow();
1786 }
1787
1788 @Override
1789 public void batteryPowerChanged(boolean onBattery) {
1790 // When plugging in, update the CPU stats first before changing
1791 // the plug state.
1792 updateCpuStatsNow();
1793 synchronized (this) {
1794 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001795 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001796 }
1797 }
1798 }
1799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 /**
1801 * Initialize the application bind args. These are passed to each
1802 * process when the bindApplication() IPC is sent to the process. They're
1803 * lazily setup to make sure the services are running when they're asked for.
1804 */
1805 private HashMap<String, IBinder> getCommonServicesLocked() {
1806 if (mAppBindArgs == null) {
1807 mAppBindArgs = new HashMap<String, IBinder>();
1808
1809 // Setup the application init args
1810 mAppBindArgs.put("package", ServiceManager.getService("package"));
1811 mAppBindArgs.put("window", ServiceManager.getService("window"));
1812 mAppBindArgs.put(Context.ALARM_SERVICE,
1813 ServiceManager.getService(Context.ALARM_SERVICE));
1814 }
1815 return mAppBindArgs;
1816 }
1817
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001818 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 if (mFocusedActivity != r) {
1820 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001821 if (r != null) {
1822 mWindowManager.setFocusedApp(r.appToken, true);
1823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 }
1826
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001827 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001829 int lrui = mLruProcesses.indexOf(app);
1830 if (lrui >= 0) mLruProcesses.remove(lrui);
1831
1832 int i = mLruProcesses.size()-1;
1833 int skipTop = 0;
1834
Dianne Hackborn906497c2010-05-10 15:57:38 -07001835 app.lruSeq = mLruSeq;
1836
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001837 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001838 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001839 if (app.activities.size() > 0) {
1840 // If this process has activities, we more strongly want to keep
1841 // it around.
1842 app.lruWeight = app.lastActivityTime;
1843 } else if (app.pubProviders.size() > 0) {
1844 // If this process contains content providers, we want to keep
1845 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001846 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001847 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001848 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001849 } else {
1850 // If this process doesn't have activities, we less strongly
1851 // want to keep it around, and generally want to avoid getting
1852 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001853 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001854 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001855 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001856 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001857
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001858 while (i >= 0) {
1859 ProcessRecord p = mLruProcesses.get(i);
1860 // If this app shouldn't be in front of the first N background
1861 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001862 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001863 skipTop--;
1864 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001865 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001866 mLruProcesses.add(i+1, app);
1867 break;
1868 }
1869 i--;
1870 }
1871 if (i < 0) {
1872 mLruProcesses.add(0, app);
1873 }
1874
Dianne Hackborn906497c2010-05-10 15:57:38 -07001875 // If the app is currently using a content provider or service,
1876 // bump those processes as well.
1877 if (app.connections.size() > 0) {
1878 for (ConnectionRecord cr : app.connections) {
1879 if (cr.binding != null && cr.binding.service != null
1880 && cr.binding.service.app != null
1881 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001882 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001883 }
1884 }
1885 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001886 for (int j=app.conProviders.size()-1; j>=0; j--) {
1887 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1888 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001889 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001890 }
1891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001894 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001895 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001896 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001897 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001898
1899 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1900 if (oomAdj) {
1901 updateOomAdjLocked();
1902 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001903 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001904
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001905 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001907 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001908 // The system gets to run in any process. If there are multiple
1909 // processes with the same uid, just pick the first (this
1910 // should never happen).
1911 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1912 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001913 if (procs == null) return null;
1914 final int N = procs.size();
1915 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001916 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 }
1919 ProcessRecord proc = mProcessNames.get(processName, uid);
1920 return proc;
1921 }
1922
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001923 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001924 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001925 try {
1926 if (pm.performDexOpt(packageName)) {
1927 mDidDexOpt = true;
1928 }
1929 } catch (RemoteException e) {
1930 }
1931 }
1932
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001933 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 int transit = mWindowManager.getPendingAppTransition();
1935 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1936 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1937 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1938 }
1939
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001940 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001942 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1943 boolean isolated) {
1944 ProcessRecord app;
1945 if (!isolated) {
1946 app = getProcessRecordLocked(processName, info.uid);
1947 } else {
1948 // If this is an isolated process, it can't re-use an existing process.
1949 app = null;
1950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 // We don't have to do anything more if:
1952 // (1) There is an existing application record; and
1953 // (2) The caller doesn't think it is dead, OR there is no thread
1954 // object attached to it so we know it couldn't have crashed; and
1955 // (3) There is a pid assigned to it, so it is either starting or
1956 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001957 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 + " app=" + app + " knownToBeDead=" + knownToBeDead
1959 + " thread=" + (app != null ? app.thread : null)
1960 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001961 if (app != null && app.pid > 0) {
1962 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001963 // We already have the app running, or are waiting for it to
1964 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001965 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001966 // If this is a new package in the process, add the package to the list
1967 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001968 return app;
1969 } else {
1970 // An application record is attached to a previous process,
1971 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001972 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001973 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 String hostingNameStr = hostingName != null
1978 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001979
1980 if (!isolated) {
1981 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1982 // If we are in the background, then check to see if this process
1983 // is bad. If so, we will just silently fail.
1984 if (mBadProcesses.get(info.processName, info.uid) != null) {
1985 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1986 + "/" + info.processName);
1987 return null;
1988 }
1989 } else {
1990 // When the user is explicitly starting a process, then clear its
1991 // crash count so that we won't make it bad until they see at
1992 // least one crash dialog again, and make the process good again
1993 // if it had been bad.
1994 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001995 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001996 mProcessCrashTimes.remove(info.processName, info.uid);
1997 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001998 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
1999 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002000 info.processName);
2001 mBadProcesses.remove(info.processName, info.uid);
2002 if (app != null) {
2003 app.bad = false;
2004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 }
2006 }
2007 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002010 app = newProcessRecordLocked(null, info, processName, isolated);
2011 if (app == null) {
2012 Slog.w(TAG, "Failed making new process record for "
2013 + processName + "/" + info.uid + " isolated=" + isolated);
2014 return null;
2015 }
2016 mProcessNames.put(processName, app.uid, app);
2017 if (isolated) {
2018 mIsolatedProcesses.put(app.uid, app);
2019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 } else {
2021 // If this is a new package in the process, add the package to the list
2022 app.addPackage(info.packageName);
2023 }
2024
2025 // If the system is not ready yet, then hold off on starting this
2026 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002027 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002028 && !isAllowedWhileBooting(info)
2029 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 if (!mProcessesOnHold.contains(app)) {
2031 mProcessesOnHold.add(app);
2032 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002033 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 return app;
2035 }
2036
2037 startProcessLocked(app, hostingType, hostingNameStr);
2038 return (app.pid != 0) ? app : null;
2039 }
2040
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002041 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2042 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2043 }
2044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 private final void startProcessLocked(ProcessRecord app,
2046 String hostingType, String hostingNameStr) {
2047 if (app.pid > 0 && app.pid != MY_PID) {
2048 synchronized (mPidsSelfLocked) {
2049 mPidsSelfLocked.remove(app.pid);
2050 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2051 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002052 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002055 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2056 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 mProcessesOnHold.remove(app);
2058
2059 updateCpuStats();
2060
2061 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2062 mProcDeaths[0] = 0;
2063
2064 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002065 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002068 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002069 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002070 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002071 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002072 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002073 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002074
2075 if (Environment.isExternalStorageEmulated()) {
2076 if (pm.checkPermission(
2077 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2078 app.info.packageName) == PERMISSION_GRANTED) {
2079 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2080 } else {
2081 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2082 }
2083 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002084 } catch (PackageManager.NameNotFoundException e) {
2085 Slog.w(TAG, "Unable to retrieve gids", e);
2086 }
Kenny Roote091f222012-09-11 15:01:26 -07002087
2088 /*
2089 * Add shared application GID so applications can share some
2090 * resources like shared libraries
2091 */
2092 if (permGids == null) {
2093 gids = new int[1];
2094 } else {
2095 gids = new int[permGids.length + 1];
2096 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2097 }
2098 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 }
2100 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2101 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2102 && mTopComponent != null
2103 && app.processName.equals(mTopComponent.getPackageName())) {
2104 uid = 0;
2105 }
2106 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2107 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2108 uid = 0;
2109 }
2110 }
2111 int debugFlags = 0;
2112 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2113 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002114 // Also turn on CheckJNI for debuggable apps. It's quite
2115 // awkward to turn on otherwise.
2116 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002118 // Run the app in safe mode if its manifest requests so or the
2119 // system is booted in safe mode.
2120 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2121 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002122 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2125 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2126 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002127 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2128 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 if ("1".equals(SystemProperties.get("debug.assert"))) {
2131 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2132 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002133
2134 // Start the process. It will either succeed and return a result containing
2135 // the PID of the new process, or else throw a RuntimeException.
2136 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002137 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002138 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2141 synchronized (bs) {
2142 if (bs.isOnBattery()) {
2143 app.batteryStats.incStartsLocked();
2144 }
2145 }
2146
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002147 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2148 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 app.processName, hostingType,
2150 hostingNameStr != null ? hostingNameStr : "");
2151
2152 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002153 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002156 StringBuilder buf = mStringBuilder;
2157 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 buf.append("Start proc ");
2159 buf.append(app.processName);
2160 buf.append(" for ");
2161 buf.append(hostingType);
2162 if (hostingNameStr != null) {
2163 buf.append(" ");
2164 buf.append(hostingNameStr);
2165 }
2166 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002167 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 buf.append(" uid=");
2169 buf.append(uid);
2170 buf.append(" gids={");
2171 if (gids != null) {
2172 for (int gi=0; gi<gids.length; gi++) {
2173 if (gi != 0) buf.append(", ");
2174 buf.append(gids[gi]);
2175
2176 }
2177 }
2178 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002179 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002180 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002181 app.usingWrapper = startResult.usingWrapper;
2182 app.removed = false;
2183 synchronized (mPidsSelfLocked) {
2184 this.mPidsSelfLocked.put(startResult.pid, app);
2185 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2186 msg.obj = app;
2187 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2188 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 }
2190 } catch (RuntimeException e) {
2191 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002192 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002193 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 }
2195 }
2196
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002197 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 if (resumed) {
2199 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2200 } else {
2201 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2202 }
2203 }
2204
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002205 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002206 if (mHeadless) {
2207 // Added because none of the other calls to ensureBootCompleted seem to fire
2208 // when running headless.
2209 ensureBootCompleted();
2210 return false;
2211 }
2212
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002213 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2214 && mTopAction == null) {
2215 // We are running in factory test mode, but unable to find
2216 // the factory test app, so just sit around displaying the
2217 // error message and don't try to start anything.
2218 return false;
2219 }
2220 Intent intent = new Intent(
2221 mTopAction,
2222 mTopData != null ? Uri.parse(mTopData) : null);
2223 intent.setComponent(mTopComponent);
2224 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2225 intent.addCategory(Intent.CATEGORY_HOME);
2226 }
2227 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002228 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002229 if (aInfo != null) {
2230 intent.setComponent(new ComponentName(
2231 aInfo.applicationInfo.packageName, aInfo.name));
2232 // Don't do this if the home app is currently being
2233 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002234 aInfo = new ActivityInfo(aInfo);
2235 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002236 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2237 aInfo.applicationInfo.uid);
2238 if (app == null || app.instrumentationClass == null) {
2239 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002240 mMainStack.startActivityLocked(null, intent, null, aInfo,
2241 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002242 }
2243 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002244
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002245 return true;
2246 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002247
Amith Yamasani259d5e52012-08-31 15:11:01 -07002248 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2249 ActivityInfo ai = null;
2250 ComponentName comp = intent.getComponent();
2251 try {
2252 if (comp != null) {
2253 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2254 } else {
2255 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2256 intent,
2257 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2258 flags, userId);
2259
2260 if (info != null) {
2261 ai = info.activityInfo;
2262 }
2263 }
2264 } catch (RemoteException e) {
2265 // ignore
2266 }
2267
2268 return ai;
2269 }
2270
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002271 /**
2272 * Starts the "new version setup screen" if appropriate.
2273 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002274 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002275 // Only do this once per boot.
2276 if (mCheckedForSetup) {
2277 return;
2278 }
2279
2280 // We will show this screen if the current one is a different
2281 // version than the last one shown, and we are not running in
2282 // low-level factory test mode.
2283 final ContentResolver resolver = mContext.getContentResolver();
2284 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002285 Settings.Global.getInt(resolver,
2286 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002287 mCheckedForSetup = true;
2288
2289 // See if we should be showing the platform update setup UI.
2290 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2291 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2292 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2293
2294 // We don't allow third party apps to replace this.
2295 ResolveInfo ri = null;
2296 for (int i=0; ris != null && i<ris.size(); i++) {
2297 if ((ris.get(i).activityInfo.applicationInfo.flags
2298 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2299 ri = ris.get(i);
2300 break;
2301 }
2302 }
2303
2304 if (ri != null) {
2305 String vers = ri.activityInfo.metaData != null
2306 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2307 : null;
2308 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2309 vers = ri.activityInfo.applicationInfo.metaData.getString(
2310 Intent.METADATA_SETUP_VERSION);
2311 }
2312 String lastVers = Settings.Secure.getString(
2313 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2314 if (vers != null && !vers.equals(lastVers)) {
2315 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2316 intent.setComponent(new ComponentName(
2317 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002318 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2319 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002320 }
2321 }
2322 }
2323 }
2324
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002325 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002326 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002327 }
2328
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002329 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002330 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002331 throw new SecurityException("Isolated process not allowed to call " + caller);
2332 }
2333 }
2334
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002335 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002336 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002337 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002338 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2339 }
2340 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002341
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002342 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002343 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2344 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002345 synchronized (this) {
2346 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2347 }
2348 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002349
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002350 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002351 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002352 synchronized (this) {
2353 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2354 }
2355 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002356
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002357 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002358 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2359 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002360 synchronized (this) {
2361 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002362 }
2363 }
2364
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002365 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002366 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002367 synchronized (this) {
2368 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2369 }
2370 }
2371
2372 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002373 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2374 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002375 synchronized (this) {
2376 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2377 }
2378 }
2379
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002380 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002381 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002382 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002385 private void dispatchProcessesChanged() {
2386 int N;
2387 synchronized (this) {
2388 N = mPendingProcessChanges.size();
2389 if (mActiveProcessChanges.length < N) {
2390 mActiveProcessChanges = new ProcessChangeItem[N];
2391 }
2392 mPendingProcessChanges.toArray(mActiveProcessChanges);
2393 mAvailProcessChanges.addAll(mPendingProcessChanges);
2394 mPendingProcessChanges.clear();
2395 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2396 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002397 int i = mProcessObservers.beginBroadcast();
2398 while (i > 0) {
2399 i--;
2400 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2401 if (observer != null) {
2402 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002403 for (int j=0; j<N; j++) {
2404 ProcessChangeItem item = mActiveProcessChanges[j];
2405 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2406 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2407 + item.pid + " uid=" + item.uid + ": "
2408 + item.foregroundActivities);
2409 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2410 item.foregroundActivities);
2411 }
2412 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2413 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2414 + item.pid + " uid=" + item.uid + ": " + item.importance);
2415 observer.onImportanceChanged(item.pid, item.uid,
2416 item.importance);
2417 }
2418 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002419 } catch (RemoteException e) {
2420 }
2421 }
2422 }
2423 mProcessObservers.finishBroadcast();
2424 }
2425
2426 private void dispatchProcessDied(int pid, int uid) {
2427 int i = mProcessObservers.beginBroadcast();
2428 while (i > 0) {
2429 i--;
2430 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2431 if (observer != null) {
2432 try {
2433 observer.onProcessDied(pid, uid);
2434 } catch (RemoteException e) {
2435 }
2436 }
2437 }
2438 mProcessObservers.finishBroadcast();
2439 }
2440
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002441 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002442 final int N = mPendingActivityLaunches.size();
2443 if (N <= 0) {
2444 return;
2445 }
2446 for (int i=0; i<N; i++) {
2447 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002448 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002449 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002450 }
2451 mPendingActivityLaunches.clear();
2452 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002453
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002454 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002455 Intent intent, String resolvedType, IBinder resultTo,
2456 String resultWho, int requestCode, int startFlags,
2457 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002458 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002459 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002460 }
2461
2462 public final int startActivityAsUser(IApplicationThread caller,
2463 Intent intent, String resolvedType, IBinder resultTo,
2464 String resultWho, int requestCode, int startFlags,
2465 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002466 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002467 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002468 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002469 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002470 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2471 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002472 }
2473
2474 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 Intent intent, String resolvedType, IBinder resultTo,
2476 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002477 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002478 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002479 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002480 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002481 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002482 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002483 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002484 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002485 return res;
2486 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002487
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002488 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002489 Intent intent, String resolvedType, IBinder resultTo,
2490 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002491 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002492 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002493 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002494 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002495 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002496 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002497 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002498 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002499 }
2500
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002501 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002502 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002503 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002504 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002505 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002506 // Refuse possible leaked file descriptors
2507 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2508 throw new IllegalArgumentException("File descriptors passed in Intent");
2509 }
2510
2511 IIntentSender sender = intent.getTarget();
2512 if (!(sender instanceof PendingIntentRecord)) {
2513 throw new IllegalArgumentException("Bad PendingIntent object");
2514 }
2515
2516 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002517
2518 synchronized (this) {
2519 // If this is coming from the currently resumed activity, it is
2520 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521 if (mMainStack.mResumedActivity != null
2522 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002523 Binder.getCallingUid()) {
2524 mAppSwitchesAllowedTime = 0;
2525 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002526 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002527 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2528 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002529 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002530 }
2531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002533 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 // Refuse possible leaked file descriptors
2535 if (intent != null && intent.hasFileDescriptors() == true) {
2536 throw new IllegalArgumentException("File descriptors passed in Intent");
2537 }
2538
2539 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002540 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2541 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002542 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 return false;
2544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 if (r.app == null || r.app.thread == null) {
2546 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002547 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 return false;
2549 }
2550 intent = new Intent(intent);
2551 // The caller is not allowed to change the data.
2552 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2553 // And we are resetting to find the next component...
2554 intent.setComponent(null);
2555
2556 ActivityInfo aInfo = null;
2557 try {
2558 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002559 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002561 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002562 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563
2564 // Look for the original activity in the list...
2565 final int N = resolves != null ? resolves.size() : 0;
2566 for (int i=0; i<N; i++) {
2567 ResolveInfo rInfo = resolves.get(i);
2568 if (rInfo.activityInfo.packageName.equals(r.packageName)
2569 && rInfo.activityInfo.name.equals(r.info.name)) {
2570 // We found the current one... the next matching is
2571 // after it.
2572 i++;
2573 if (i<N) {
2574 aInfo = resolves.get(i).activityInfo;
2575 }
2576 break;
2577 }
2578 }
2579 } catch (RemoteException e) {
2580 }
2581
2582 if (aInfo == null) {
2583 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002584 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 return false;
2586 }
2587
2588 intent.setComponent(new ComponentName(
2589 aInfo.applicationInfo.packageName, aInfo.name));
2590 intent.setFlags(intent.getFlags()&~(
2591 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2592 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2593 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2594 Intent.FLAG_ACTIVITY_NEW_TASK));
2595
2596 // Okay now we need to start the new activity, replacing the
2597 // currently running activity. This is a little tricky because
2598 // we want to start the new one as if the current one is finished,
2599 // but not finish the current one first so that there is no flicker.
2600 // And thus...
2601 final boolean wasFinishing = r.finishing;
2602 r.finishing = true;
2603
2604 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002605 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 final String resultWho = r.resultWho;
2607 final int requestCode = r.requestCode;
2608 r.resultTo = null;
2609 if (resultTo != null) {
2610 resultTo.removeResultsLocked(r, resultWho, requestCode);
2611 }
2612
2613 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002614 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002615 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2616 resultWho, requestCode, -1, r.launchedFromUid, 0,
2617 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 Binder.restoreCallingIdentity(origId);
2619
2620 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002621 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 return false;
2623 }
2624 return true;
2625 }
2626 }
2627
Dianne Hackborn41203752012-08-31 14:05:51 -07002628 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002630 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2631
Dianne Hackborn139748f2012-09-24 11:36:57 -07002632 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002633 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634
Amith Yamasani742a6712011-05-04 14:49:28 -07002635 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002636 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002637 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002638 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002639 }
2640
2641 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002642 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2643 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002644 enforceNotIsolatedCaller("startActivities");
Amith Yamasani95293862012-09-24 18:14:47 -07002645 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002646 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002647 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002648 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002649 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002650 }
2651
Dianne Hackborn41203752012-08-31 14:05:51 -07002652 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002653 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002654 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002655
Dianne Hackborn139748f2012-09-24 11:36:57 -07002656 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002657 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002658 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002659 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002660 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002665 // Quick case: check if the top-most recent task is the same.
2666 if (N > 0 && mRecentTasks.get(0) == task) {
2667 return;
2668 }
2669 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 for (int i=0; i<N; i++) {
2671 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002672 if (task.userId == tr.userId
2673 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2674 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 mRecentTasks.remove(i);
2676 i--;
2677 N--;
2678 if (task.intent == null) {
2679 // If the new recent task we are adding is not fully
2680 // specified, then replace it with the existing recent task.
2681 task = tr;
2682 }
2683 }
2684 }
2685 if (N >= MAX_RECENT_TASKS) {
2686 mRecentTasks.remove(N-1);
2687 }
2688 mRecentTasks.add(0, task);
2689 }
2690
2691 public void setRequestedOrientation(IBinder token,
2692 int requestedOrientation) {
2693 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002694 ActivityRecord r = mMainStack.isInStackLocked(token);
2695 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 return;
2697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002699 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002701 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002702 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 if (config != null) {
2704 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002705 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002706 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
2708 }
2709 Binder.restoreCallingIdentity(origId);
2710 }
2711 }
2712
2713 public int getRequestedOrientation(IBinder token) {
2714 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002715 ActivityRecord r = mMainStack.isInStackLocked(token);
2716 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2718 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002719 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
2721 }
2722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 /**
2724 * This is the internal entry point for handling Activity.finish().
2725 *
2726 * @param token The Binder token referencing the Activity we want to finish.
2727 * @param resultCode Result code, if any, from this Activity.
2728 * @param resultData Result data (Intent), if any, from this Activity.
2729 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002730 * @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 -08002731 */
2732 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2733 // Refuse possible leaked file descriptors
2734 if (resultData != null && resultData.hasFileDescriptors() == true) {
2735 throw new IllegalArgumentException("File descriptors passed in Intent");
2736 }
2737
2738 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002739 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002741 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 if (next != null) {
2743 // ask watcher if this is allowed
2744 boolean resumeOK = true;
2745 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002746 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002748 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 }
2750
2751 if (!resumeOK) {
2752 return false;
2753 }
2754 }
2755 }
2756 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002757 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002758 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 Binder.restoreCallingIdentity(origId);
2760 return res;
2761 }
2762 }
2763
Dianne Hackborn860755f2010-06-03 18:47:52 -07002764 public final void finishHeavyWeightApp() {
2765 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2766 != PackageManager.PERMISSION_GRANTED) {
2767 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2768 + Binder.getCallingPid()
2769 + ", uid=" + Binder.getCallingUid()
2770 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2771 Slog.w(TAG, msg);
2772 throw new SecurityException(msg);
2773 }
2774
2775 synchronized(this) {
2776 if (mHeavyWeightProcess == null) {
2777 return;
2778 }
2779
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002780 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002781 mHeavyWeightProcess.activities);
2782 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002783 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002784 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002785 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002786 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002787 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002788 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002789 }
2790 }
2791 }
2792
Dianne Hackborn41203752012-08-31 14:05:51 -07002793 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2794 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002795 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002796 }
2797 }
2798
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002799 public void crashApplication(int uid, int initialPid, String packageName,
2800 String message) {
2801 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2802 != PackageManager.PERMISSION_GRANTED) {
2803 String msg = "Permission Denial: crashApplication() from pid="
2804 + Binder.getCallingPid()
2805 + ", uid=" + Binder.getCallingUid()
2806 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2807 Slog.w(TAG, msg);
2808 throw new SecurityException(msg);
2809 }
2810
2811 synchronized(this) {
2812 ProcessRecord proc = null;
2813
2814 // Figure out which process to kill. We don't trust that initialPid
2815 // still has any relation to current pids, so must scan through the
2816 // list.
2817 synchronized (mPidsSelfLocked) {
2818 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2819 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002820 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002821 continue;
2822 }
2823 if (p.pid == initialPid) {
2824 proc = p;
2825 break;
2826 }
2827 for (String str : p.pkgList) {
2828 if (str.equals(packageName)) {
2829 proc = p;
2830 }
2831 }
2832 }
2833 }
2834
2835 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002836 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002837 + " initialPid=" + initialPid
2838 + " packageName=" + packageName);
2839 return;
2840 }
2841
2842 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002843 if (proc.pid == Process.myPid()) {
2844 Log.w(TAG, "crashApplication: trying to crash self!");
2845 return;
2846 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002847 long ident = Binder.clearCallingIdentity();
2848 try {
2849 proc.thread.scheduleCrash(message);
2850 } catch (RemoteException e) {
2851 }
2852 Binder.restoreCallingIdentity(ident);
2853 }
2854 }
2855 }
2856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 public final void finishSubActivity(IBinder token, String resultWho,
2858 int requestCode) {
2859 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002861 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 Binder.restoreCallingIdentity(origId);
2863 }
2864 }
2865
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002866 public boolean finishActivityAffinity(IBinder token) {
2867 synchronized(this) {
2868 final long origId = Binder.clearCallingIdentity();
2869 boolean res = mMainStack.finishActivityAffinityLocked(token);
2870 Binder.restoreCallingIdentity(origId);
2871 return res;
2872 }
2873 }
2874
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002875 public boolean willActivityBeVisible(IBinder token) {
2876 synchronized(this) {
2877 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002878 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2879 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002880 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002881 return true;
2882 }
2883 if (r.fullscreen && !r.finishing) {
2884 return false;
2885 }
2886 }
2887 return true;
2888 }
2889 }
2890
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002891 public void overridePendingTransition(IBinder token, String packageName,
2892 int enterAnim, int exitAnim) {
2893 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002894 ActivityRecord self = mMainStack.isInStackLocked(token);
2895 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002896 return;
2897 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002898
2899 final long origId = Binder.clearCallingIdentity();
2900
2901 if (self.state == ActivityState.RESUMED
2902 || self.state == ActivityState.PAUSING) {
2903 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002904 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002905 }
2906
2907 Binder.restoreCallingIdentity(origId);
2908 }
2909 }
2910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 * Main function for removing an existing process from the activity manager
2913 * as a result of that process going away. Clears out all connections
2914 * to the process.
2915 */
2916 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002917 boolean restarting, boolean allowRestart) {
2918 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002920 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 }
2922
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002923 if (mProfileProc == app) {
2924 clearProfilerLocked();
2925 }
2926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002928 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002929 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2930 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002931 mMainStack.mPausingActivity = null;
2932 }
2933 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2934 mMainStack.mLastPausedActivity = null;
2935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936
2937 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002938 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939
2940 app.activities.clear();
2941
2942 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002943 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 + " running instrumentation " + app.instrumentationClass);
2945 Bundle info = new Bundle();
2946 info.putString("shortMsg", "Process crashed.");
2947 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2948 }
2949
2950 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002951 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 // If there was nothing to resume, and we are not already
2953 // restarting this process, but there is a visible activity that
2954 // is hosted by the process... then make sure all visible
2955 // activities are running, taking care of restarting this
2956 // process.
2957 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002958 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 }
2960 }
2961 }
2962 }
2963
2964 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2965 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002967 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2968 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2970 return i;
2971 }
2972 }
2973 return -1;
2974 }
2975
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002976 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 IApplicationThread thread) {
2978 if (thread == null) {
2979 return null;
2980 }
2981
2982 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002983 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 }
2985
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002986 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 IApplicationThread thread) {
2988
2989 mProcDeaths[0]++;
2990
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002991 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2992 synchronized (stats) {
2993 stats.noteProcessDiedLocked(app.info.uid, pid);
2994 }
2995
Magnus Edlund7bb25812010-02-24 15:45:06 +01002996 // Clean up already done if the process has been re-started.
2997 if (app.pid == pid && app.thread != null &&
2998 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002999 if (!app.killedBackground) {
3000 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3001 + ") has died.");
3002 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003003 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003004 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 TAG, "Dying app: " + app + ", pid: " + pid
3006 + ", thread: " + thread.asBinder());
3007 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003008 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009
3010 if (doLowMem) {
3011 // If there are no longer any background processes running,
3012 // and the app that died was not running instrumentation,
3013 // then tell everyone we are now low on memory.
3014 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003015 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3016 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003017 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 haveBg = true;
3019 break;
3020 }
3021 }
3022
3023 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003024 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003025 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003026 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3027 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003028 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003029 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3030 // The low memory report is overriding any current
3031 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003032 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003033 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003034 rec.lastRequestedGc = 0;
3035 } else {
3036 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003038 rec.reportLowMemory = true;
3039 rec.lastLowMemory = now;
3040 mProcessesToGc.remove(rec);
3041 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 }
3043 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003044 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003045 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 }
3047 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003048 } else if (app.pid != pid) {
3049 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003050 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003051 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003052 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003053 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003054 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 + thread.asBinder());
3056 }
3057 }
3058
Dan Egnor42471dd2010-01-07 17:25:22 -08003059 /**
3060 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003061 * @param clearTraces causes the dump file to be erased prior to the new
3062 * traces being written, if true; when false, the new traces will be
3063 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003064 * @param firstPids of dalvik VM processes to dump stack traces for first
3065 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003066 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003067 * @return file containing stack traces, or null if no dump file is configured
3068 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003069 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003070 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003071 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3072 if (tracesPath == null || tracesPath.length() == 0) {
3073 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003075
3076 File tracesFile = new File(tracesPath);
3077 try {
3078 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003079 if (!tracesDir.exists()) {
3080 tracesFile.mkdirs();
3081 if (!SELinux.restorecon(tracesDir)) {
3082 return null;
3083 }
3084 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003085 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3086
Christopher Tate6ee412d2010-05-28 12:01:56 -07003087 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003088 tracesFile.createNewFile();
3089 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3090 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003091 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003092 return null;
3093 }
3094
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003095 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003096 return tracesFile;
3097 }
3098
3099 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003100 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003101 // Use a FileObserver to detect when traces finish writing.
3102 // The order of traces is considered important to maintain for legibility.
3103 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3104 public synchronized void onEvent(int event, String path) { notify(); }
3105 };
3106
3107 try {
3108 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003109
3110 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003111 if (firstPids != null) {
3112 try {
3113 int num = firstPids.size();
3114 for (int i = 0; i < num; i++) {
3115 synchronized (observer) {
3116 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3117 observer.wait(200); // Wait for write-close, give up after 200msec
3118 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003119 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003120 } catch (InterruptedException e) {
3121 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003122 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003123 }
3124
3125 // Next measure CPU usage.
3126 if (processStats != null) {
3127 processStats.init();
3128 System.gc();
3129 processStats.update();
3130 try {
3131 synchronized (processStats) {
3132 processStats.wait(500); // measure over 1/2 second.
3133 }
3134 } catch (InterruptedException e) {
3135 }
3136 processStats.update();
3137
3138 // We'll take the stack crawls of just the top apps using CPU.
3139 final int N = processStats.countWorkingStats();
3140 int numProcs = 0;
3141 for (int i=0; i<N && numProcs<5; i++) {
3142 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3143 if (lastPids.indexOfKey(stats.pid) >= 0) {
3144 numProcs++;
3145 try {
3146 synchronized (observer) {
3147 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3148 observer.wait(200); // Wait for write-close, give up after 200msec
3149 }
3150 } catch (InterruptedException e) {
3151 Log.wtf(TAG, e);
3152 }
3153
3154 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003155 }
3156 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003157
Dan Egnor42471dd2010-01-07 17:25:22 -08003158 } finally {
3159 observer.stopWatching();
3160 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003161
3162 if (nativeProcs != null) {
3163 int[] pids = Process.getPidsForCommands(nativeProcs);
3164 if (pids != null) {
3165 for (int pid : pids) {
3166 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3167 }
3168 }
3169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 }
3171
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003172 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003173 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003174 return;
3175 }
3176 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3177 if (tracesPath == null || tracesPath.length() == 0) {
3178 return;
3179 }
3180
3181 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3182 StrictMode.allowThreadDiskWrites();
3183 try {
3184 final File tracesFile = new File(tracesPath);
3185 final File tracesDir = tracesFile.getParentFile();
3186 final File tracesTmp = new File(tracesDir, "__tmp__");
3187 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003188 if (!tracesDir.exists()) {
3189 tracesFile.mkdirs();
3190 if (!SELinux.restorecon(tracesDir.getPath())) {
3191 return;
3192 }
3193 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003194 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3195
3196 if (tracesFile.exists()) {
3197 tracesTmp.delete();
3198 tracesFile.renameTo(tracesTmp);
3199 }
3200 StringBuilder sb = new StringBuilder();
3201 Time tobj = new Time();
3202 tobj.set(System.currentTimeMillis());
3203 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3204 sb.append(": ");
3205 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3206 sb.append(" since ");
3207 sb.append(msg);
3208 FileOutputStream fos = new FileOutputStream(tracesFile);
3209 fos.write(sb.toString().getBytes());
3210 if (app == null) {
3211 fos.write("\n*** No application process!".getBytes());
3212 }
3213 fos.close();
3214 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3215 } catch (IOException e) {
3216 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3217 return;
3218 }
3219
3220 if (app != null) {
3221 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3222 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003223 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003224 }
3225
3226 File lastTracesFile = null;
3227 File curTracesFile = null;
3228 for (int i=9; i>=0; i--) {
3229 String name = String.format("slow%02d.txt", i);
3230 curTracesFile = new File(tracesDir, name);
3231 if (curTracesFile.exists()) {
3232 if (lastTracesFile != null) {
3233 curTracesFile.renameTo(lastTracesFile);
3234 } else {
3235 curTracesFile.delete();
3236 }
3237 }
3238 lastTracesFile = curTracesFile;
3239 }
3240 tracesFile.renameTo(curTracesFile);
3241 if (tracesTmp.exists()) {
3242 tracesTmp.renameTo(tracesFile);
3243 }
3244 } finally {
3245 StrictMode.setThreadPolicy(oldPolicy);
3246 }
3247 }
3248
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003249 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3250 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003251 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3252 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3253
Dianne Hackborn287952c2010-09-22 22:34:31 -07003254 if (mController != null) {
3255 try {
3256 // 0 == continue, -1 = kill process immediately
3257 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3258 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3259 } catch (RemoteException e) {
3260 mController = null;
3261 }
3262 }
3263
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003264 long anrTime = SystemClock.uptimeMillis();
3265 if (MONITOR_CPU_USAGE) {
3266 updateCpuStatsNow();
3267 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003268
3269 synchronized (this) {
3270 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3271 if (mShuttingDown) {
3272 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3273 return;
3274 } else if (app.notResponding) {
3275 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3276 return;
3277 } else if (app.crashing) {
3278 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3279 return;
3280 }
3281
3282 // In case we come through here for the same app before completing
3283 // this one, mark as anring now so we will bail out.
3284 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003285
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003286 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003287 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3288 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003289
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003290 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003291 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003292
3293 int parentPid = app.pid;
3294 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003295 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003296
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003297 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003298
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003299 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3300 ProcessRecord r = mLruProcesses.get(i);
3301 if (r != null && r.thread != null) {
3302 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003303 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3304 if (r.persistent) {
3305 firstPids.add(pid);
3306 } else {
3307 lastPids.put(pid, Boolean.TRUE);
3308 }
3309 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 }
3312 }
3313
Dan Egnor42471dd2010-01-07 17:25:22 -08003314 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003315 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003316 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003317 info.append("ANR in ").append(app.processName);
3318 if (activity != null && activity.shortComponentName != null) {
3319 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003320 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003321 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003323 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003325 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003326 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328
Dianne Hackborn287952c2010-09-22 22:34:31 -07003329 final ProcessStats processStats = new ProcessStats(true);
3330
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003331 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003332
Dan Egnor42471dd2010-01-07 17:25:22 -08003333 String cpuInfo = null;
3334 if (MONITOR_CPU_USAGE) {
3335 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003336 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003337 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003338 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003339 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003340 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 }
3342
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003343 info.append(processStats.printCurrentState(anrTime));
3344
Joe Onorato8a9b2202010-02-26 18:56:32 -08003345 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003346 if (tracesFile == null) {
3347 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3348 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3349 }
3350
Jeff Sharkeya353d262011-10-28 11:12:06 -07003351 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3352 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003353
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003354 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003356 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3357 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003359 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3360 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
3362 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003363 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 }
3365 }
3366
Dan Egnor42471dd2010-01-07 17:25:22 -08003367 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3368 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3369 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003370
3371 synchronized (this) {
3372 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003373 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003374 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003375 app.processName, app.setAdj, "background ANR");
3376 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003377 return;
3378 }
3379
3380 // Set the app's notResponding state, and look up the errorReportReceiver
3381 makeAppNotRespondingLocked(app,
3382 activity != null ? activity.shortComponentName : null,
3383 annotation != null ? "ANR " + annotation : "ANR",
3384 info.toString());
3385
3386 // Bring up the infamous App Not Responding dialog
3387 Message msg = Message.obtain();
3388 HashMap map = new HashMap();
3389 msg.what = SHOW_NOT_RESPONDING_MSG;
3390 msg.obj = map;
3391 map.put("app", app);
3392 if (activity != null) {
3393 map.put("activity", activity);
3394 }
3395
3396 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
3399
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003400 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3401 if (!mLaunchWarningShown) {
3402 mLaunchWarningShown = true;
3403 mHandler.post(new Runnable() {
3404 @Override
3405 public void run() {
3406 synchronized (ActivityManagerService.this) {
3407 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3408 d.show();
3409 mHandler.postDelayed(new Runnable() {
3410 @Override
3411 public void run() {
3412 synchronized (ActivityManagerService.this) {
3413 d.dismiss();
3414 mLaunchWarningShown = false;
3415 }
3416 }
3417 }, 4000);
3418 }
3419 }
3420 });
3421 }
3422 }
3423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003425 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003426 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 int uid = Binder.getCallingUid();
3428 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003429 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003430 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 long callingId = Binder.clearCallingIdentity();
3432 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003433 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 int pkgUid = -1;
3435 synchronized(this) {
3436 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003437 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 } catch (RemoteException e) {
3439 }
3440 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003441 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 return false;
3443 }
3444 if (uid == pkgUid || checkComponentPermission(
3445 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003446 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003448 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 } else {
3450 throw new SecurityException(pid+" does not have permission:"+
3451 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3452 "for process:"+packageName);
3453 }
3454 }
3455
3456 try {
3457 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003458 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3460 Uri.fromParts("package", packageName, null));
3461 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003462 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003463 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 } catch (RemoteException e) {
3465 }
3466 } finally {
3467 Binder.restoreCallingIdentity(callingId);
3468 }
3469 return true;
3470 }
3471
Dianne Hackborn1676c852012-09-10 14:52:30 -07003472 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003473 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3474 != PackageManager.PERMISSION_GRANTED &&
3475 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3476 != PackageManager.PERMISSION_GRANTED) {
3477 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 + Binder.getCallingPid()
3479 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003480 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003481 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 throw new SecurityException(msg);
3483 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003484
Dianne Hackborn139748f2012-09-24 11:36:57 -07003485 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003486 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 long callingId = Binder.clearCallingIdentity();
3488 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003489 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003491 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003493 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 } catch (RemoteException e) {
3495 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003496 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003497 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 return;
3499 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003500 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003501 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3502 }
3503 } finally {
3504 Binder.restoreCallingIdentity(callingId);
3505 }
3506 }
3507
3508 public void killAllBackgroundProcesses() {
3509 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3510 != PackageManager.PERMISSION_GRANTED) {
3511 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3512 + Binder.getCallingPid()
3513 + ", uid=" + Binder.getCallingUid()
3514 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3515 Slog.w(TAG, msg);
3516 throw new SecurityException(msg);
3517 }
3518
3519 long callingId = Binder.clearCallingIdentity();
3520 try {
3521 synchronized(this) {
3522 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3523 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3524 final int NA = apps.size();
3525 for (int ia=0; ia<NA; ia++) {
3526 ProcessRecord app = apps.valueAt(ia);
3527 if (app.persistent) {
3528 // we don't kill persistent processes
3529 continue;
3530 }
3531 if (app.removed) {
3532 procs.add(app);
3533 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3534 app.removed = true;
3535 procs.add(app);
3536 }
3537 }
3538 }
3539
3540 int N = procs.size();
3541 for (int i=0; i<N; i++) {
3542 removeProcessLocked(procs.get(i), false, true, "kill all background");
3543 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003544 }
3545 } finally {
3546 Binder.restoreCallingIdentity(callingId);
3547 }
3548 }
3549
Dianne Hackborn1676c852012-09-10 14:52:30 -07003550 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003551 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3552 != PackageManager.PERMISSION_GRANTED) {
3553 String msg = "Permission Denial: forceStopPackage() from pid="
3554 + Binder.getCallingPid()
3555 + ", uid=" + Binder.getCallingUid()
3556 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003557 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003558 throw new SecurityException(msg);
3559 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003560 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003561 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003562 long callingId = Binder.clearCallingIdentity();
3563 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003564 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003565 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003566 int[] users = userId == UserHandle.USER_ALL
3567 ? getUsersLocked() : new int[] { userId };
3568 for (int user : users) {
3569 int pkgUid = -1;
3570 try {
3571 pkgUid = pm.getPackageUid(packageName, user);
3572 } catch (RemoteException e) {
3573 }
3574 if (pkgUid == -1) {
3575 Slog.w(TAG, "Invalid packageName: " + packageName);
3576 continue;
3577 }
3578 try {
3579 pm.setPackageStoppedState(packageName, true, user);
3580 } catch (RemoteException e) {
3581 } catch (IllegalArgumentException e) {
3582 Slog.w(TAG, "Failed trying to unstop package "
3583 + packageName + ": " + e);
3584 }
3585 if (isUserRunningLocked(user)) {
3586 forceStopPackageLocked(packageName, pkgUid);
3587 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 }
3590 } finally {
3591 Binder.restoreCallingIdentity(callingId);
3592 }
3593 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003594
3595 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003596 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003597 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003598 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003599 if (pkg == null) {
3600 return;
3601 }
3602 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003603 if (appid < 0) {
3604 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003605 return;
3606 }
3607 int callerUid = Binder.getCallingUid();
3608 // Only the system server can kill an application
3609 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003610 // Post an aysnc message to kill the application
3611 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003612 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003613 msg.arg2 = 0;
3614 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003615 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003616 } else {
3617 throw new SecurityException(callerUid + " cannot kill pkg: " +
3618 pkg);
3619 }
3620 }
3621
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003622 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003623 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003624
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003625 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003626 final int uid = Binder.getCallingUid();
3627 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003628 try {
3629 synchronized (this) {
3630 // Only allow this from foreground processes, so that background
3631 // applications can't abuse it to prevent system UI from being shown.
3632 if (uid >= Process.FIRST_APPLICATION_UID) {
3633 ProcessRecord proc;
3634 synchronized (mPidsSelfLocked) {
3635 proc = mPidsSelfLocked.get(pid);
3636 }
3637 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3638 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3639 + " from background process " + proc);
3640 return;
3641 }
3642 }
3643 closeSystemDialogsLocked(reason);
3644 }
3645 } finally {
3646 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003647 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003648 }
3649
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003650 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003651 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003652 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3653 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003654 if (reason != null) {
3655 intent.putExtra("reason", reason);
3656 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003657 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003658
Dianne Hackborne302a162012-05-15 14:58:32 -07003659 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3660 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003661 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003662 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003663 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003664 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003665 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003666
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003667 broadcastIntentLocked(null, null, intent, null,
3668 null, 0, null, null, null, false, false, -1,
3669 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003670 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003671
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003672 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003673 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003674 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003675 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3676 for (int i=pids.length-1; i>=0; i--) {
3677 infos[i] = new Debug.MemoryInfo();
3678 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003679 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003680 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003681 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003682
Dianne Hackbornb437e092011-08-05 17:50:29 -07003683 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003684 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003685 long[] pss = new long[pids.length];
3686 for (int i=pids.length-1; i>=0; i--) {
3687 pss[i] = Debug.getPss(pids[i]);
3688 }
3689 return pss;
3690 }
3691
Christopher Tate5e1ab332009-09-01 20:32:49 -07003692 public void killApplicationProcess(String processName, int uid) {
3693 if (processName == null) {
3694 return;
3695 }
3696
3697 int callerUid = Binder.getCallingUid();
3698 // Only the system server can kill an application
3699 if (callerUid == Process.SYSTEM_UID) {
3700 synchronized (this) {
3701 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003702 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003703 try {
3704 app.thread.scheduleSuicide();
3705 } catch (RemoteException e) {
3706 // If the other end already died, then our work here is done.
3707 }
3708 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003709 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003710 + processName + " / " + uid);
3711 }
3712 }
3713 } else {
3714 throw new SecurityException(callerUid + " cannot kill app process: " +
3715 processName);
3716 }
3717 }
3718
Dianne Hackborn03abb812010-01-04 18:43:19 -08003719 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003720 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3721 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3723 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003724 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003725 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3726 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003729 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 broadcastIntentLocked(null, null, intent,
3731 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003732 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003733 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003735
3736 private void forceStopUserLocked(int userId) {
3737 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3738 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003739 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3740 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003741 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3742 broadcastIntentLocked(null, null, intent,
3743 null, null, 0, null, null, null,
3744 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003745 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003746 }
3747
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003748 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003749 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3750 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003751 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752
Dianne Hackborn03abb812010-01-04 18:43:19 -08003753 // Remove all processes this package may have touched: all with the
3754 // same UID (except for the system or root user), and all whose name
3755 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003756 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003757 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3758 final int NA = apps.size();
3759 for (int ia=0; ia<NA; ia++) {
3760 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003761 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003762 // we don't kill persistent processes
3763 continue;
3764 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003765 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003766 if (doit) {
3767 procs.add(app);
3768 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003769 continue;
3770 }
3771
3772 // Skip process if it doesn't meet our oom adj requirement.
3773 if (app.setAdj < minOomAdj) {
3774 continue;
3775 }
3776
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003777 // If no package is specified, we call all processes under the
3778 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003779 if (packageName == null) {
3780 if (app.userId != userId) {
3781 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003782 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003783 // Package has been specified, we want to hit all processes
3784 // that match it. We need to qualify this by the processes
3785 // that are running under the specified app and user ID.
3786 } else {
3787 if (UserHandle.getAppId(app.uid) != appId) {
3788 continue;
3789 }
3790 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3791 continue;
3792 }
3793 if (!app.pkgList.contains(packageName)) {
3794 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003795 }
3796 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003797
3798 // Process has passed all conditions, kill it!
3799 if (!doit) {
3800 return true;
3801 }
3802 app.removed = true;
3803 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003804 }
3805 }
3806
3807 int N = procs.size();
3808 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003809 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003810 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003811 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003812 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003813
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003814 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003815 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003816 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003817 int i;
3818 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003820 if (userId == UserHandle.USER_ALL && name == null) {
3821 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3822 }
3823
3824 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003826 appId = UserHandle.getAppId(
3827 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 } catch (RemoteException e) {
3829 }
3830 }
3831
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003832 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003833 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003834 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3835 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003836 } else {
3837 Slog.i(TAG, "Force stopping user " + userId);
3838 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003839
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003840 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3841 while (badApps.hasNext()) {
3842 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003843 for (i=ba.size()-1; i>=0; i--) {
3844 boolean remove = false;
3845 final int entUid = ba.keyAt(i);
3846 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003847 if (userId == UserHandle.USER_ALL) {
3848 if (UserHandle.getAppId(entUid) == appId) {
3849 remove = true;
3850 }
3851 } else {
3852 if (entUid == UserHandle.getUid(userId, appId)) {
3853 remove = true;
3854 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003855 }
3856 } else if (UserHandle.getUserId(entUid) == userId) {
3857 remove = true;
3858 }
3859 if (remove) {
3860 ba.removeAt(i);
3861 }
3862 }
3863 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003864 badApps.remove();
3865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
3867 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003868
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003869 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3870 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003871 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003873 TaskRecord lastTask = null;
3874 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003875 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003876 final boolean samePackage = r.packageName.equals(name)
3877 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003878 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003879 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003880 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003881 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003882 if (r.finishing) {
3883 // If this activity is just finishing, then it is not
3884 // interesting as far as something to stop.
3885 continue;
3886 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003887 return true;
3888 }
3889 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003890 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003891 if (samePackage) {
3892 if (r.app != null) {
3893 r.app.removed = true;
3894 }
3895 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003897 lastTask = r.task;
3898 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003899 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003900 i--;
3901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 }
3903 }
3904
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003905 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3906 if (!doit) {
3907 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003909 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003911
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003912 if (name == null) {
3913 // Remove all sticky broadcasts from this user.
3914 mStickyBroadcasts.remove(userId);
3915 }
3916
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003917 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003918 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3919 userId, providers)) {
3920 if (!doit) {
3921 return true;
3922 }
3923 didSomething = true;
3924 }
3925 N = providers.size();
3926 for (i=0; i<N; i++) {
3927 removeDyingProviderLocked(null, providers.get(i), true);
3928 }
3929
3930 if (mIntentSenderRecords.size() > 0) {
3931 Iterator<WeakReference<PendingIntentRecord>> it
3932 = mIntentSenderRecords.values().iterator();
3933 while (it.hasNext()) {
3934 WeakReference<PendingIntentRecord> wpir = it.next();
3935 if (wpir == null) {
3936 it.remove();
3937 continue;
3938 }
3939 PendingIntentRecord pir = wpir.get();
3940 if (pir == null) {
3941 it.remove();
3942 continue;
3943 }
3944 if (name == null) {
3945 // Stopping user, remove all objects for the user.
3946 if (pir.key.userId != userId) {
3947 // Not the same user, skip it.
3948 continue;
3949 }
3950 } else {
3951 if (UserHandle.getAppId(pir.uid) != appId) {
3952 // Different app id, skip it.
3953 continue;
3954 }
3955 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3956 // Different user, skip it.
3957 continue;
3958 }
3959 if (!pir.key.packageName.equals(name)) {
3960 // Different package, skip it.
3961 continue;
3962 }
3963 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003964 if (!doit) {
3965 return true;
3966 }
3967 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003968 it.remove();
3969 pir.canceled = true;
3970 if (pir.key.activity != null) {
3971 pir.key.activity.pendingResults.remove(pir.ref);
3972 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003973 }
3974 }
3975
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003976 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003977 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003978 AttributeCache ac = AttributeCache.instance();
3979 if (ac != null) {
3980 ac.removePackage(name);
3981 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003982 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003983 if (mBooted) {
3984 mMainStack.resumeTopActivityLocked(null);
3985 mMainStack.scheduleIdleLocked();
3986 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003987 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003988
3989 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 }
3991
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003992 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003993 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003995 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003996 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003997 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 + "/" + uid + ")");
3999
4000 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004001 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004002 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004003 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4004 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004005 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 boolean needRestart = false;
4008 if (app.pid > 0 && app.pid != MY_PID) {
4009 int pid = app.pid;
4010 synchronized (mPidsSelfLocked) {
4011 mPidsSelfLocked.remove(pid);
4012 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4013 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004014 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004015 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004016 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004017 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004019 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004021 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 } else {
4023 needRestart = true;
4024 }
4025 }
4026 } else {
4027 mRemovedProcesses.add(app);
4028 }
4029
4030 return needRestart;
4031 }
4032
4033 private final void processStartTimedOutLocked(ProcessRecord app) {
4034 final int pid = app.pid;
4035 boolean gone = false;
4036 synchronized (mPidsSelfLocked) {
4037 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4038 if (knownApp != null && knownApp.thread == null) {
4039 mPidsSelfLocked.remove(pid);
4040 gone = true;
4041 }
4042 }
4043
4044 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004045 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004046 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4047 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004048 mProcessNames.remove(app.processName, app.uid);
4049 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004050 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004051 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4052 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004053 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004054 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004055 // Take care of any launching providers waiting for this process.
4056 checkAppInLaunchingProvidersLocked(app, true);
4057 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004058 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004059 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004060 app.processName, app.setAdj, "start timeout");
4061 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004062 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004063 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004064 try {
4065 IBackupManager bm = IBackupManager.Stub.asInterface(
4066 ServiceManager.getService(Context.BACKUP_SERVICE));
4067 bm.agentDisconnected(app.info.packageName);
4068 } catch (RemoteException e) {
4069 // Can't happen; the backup manager is local
4070 }
4071 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004072 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004073 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004074 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004077 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 }
4079 }
4080
4081 private final boolean attachApplicationLocked(IApplicationThread thread,
4082 int pid) {
4083
4084 // Find the application record that is being attached... either via
4085 // the pid if we are running in multiple processes, or just pull the
4086 // next app record if we are emulating process with anonymous threads.
4087 ProcessRecord app;
4088 if (pid != MY_PID && pid >= 0) {
4089 synchronized (mPidsSelfLocked) {
4090 app = mPidsSelfLocked.get(pid);
4091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 } else {
4093 app = null;
4094 }
4095
4096 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004097 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004099 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004101 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 } else {
4103 try {
4104 thread.scheduleExit();
4105 } catch (Exception e) {
4106 // Ignore exceptions.
4107 }
4108 }
4109 return false;
4110 }
4111
4112 // If this application record is still attached to a previous
4113 // process, clean it up now.
4114 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004115 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 }
4117
4118 // Tell the process all about itself.
4119
Joe Onorato8a9b2202010-02-26 18:56:32 -08004120 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 TAG, "Binding process pid " + pid + " to record " + app);
4122
4123 String processName = app.processName;
4124 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004125 AppDeathRecipient adr = new AppDeathRecipient(
4126 app, pid, thread);
4127 thread.asBinder().linkToDeath(adr, 0);
4128 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 } catch (RemoteException e) {
4130 app.resetPackageList();
4131 startProcessLocked(app, "link fail", processName);
4132 return false;
4133 }
4134
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004135 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136
4137 app.thread = thread;
4138 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004139 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4140 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 app.forcingToForeground = null;
4142 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004143 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 app.debugging = false;
4145
4146 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4147
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004148 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004149 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004151 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004152 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004153 }
4154
Joe Onorato8a9b2202010-02-26 18:56:32 -08004155 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 TAG, "New app record " + app
4157 + " thread=" + thread.asBinder() + " pid=" + pid);
4158 try {
4159 int testMode = IApplicationThread.DEBUG_OFF;
4160 if (mDebugApp != null && mDebugApp.equals(processName)) {
4161 testMode = mWaitForDebugger
4162 ? IApplicationThread.DEBUG_WAIT
4163 : IApplicationThread.DEBUG_ON;
4164 app.debugging = true;
4165 if (mDebugTransient) {
4166 mDebugApp = mOrigDebugApp;
4167 mWaitForDebugger = mOrigWaitForDebugger;
4168 }
4169 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004170 String profileFile = app.instrumentationProfileFile;
4171 ParcelFileDescriptor profileFd = null;
4172 boolean profileAutoStop = false;
4173 if (mProfileApp != null && mProfileApp.equals(processName)) {
4174 mProfileProc = app;
4175 profileFile = mProfileFile;
4176 profileFd = mProfileFd;
4177 profileAutoStop = mAutoStopProfiler;
4178 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004179 boolean enableOpenGlTrace = false;
4180 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4181 enableOpenGlTrace = true;
4182 mOpenGlTraceApp = null;
4183 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004184
Christopher Tate181fafa2009-05-14 11:12:14 -07004185 // If the app is being launched for restore or full backup, set it up specially
4186 boolean isRestrictedBackupMode = false;
4187 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4188 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004189 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004190 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4191 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004192
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004193 ensurePackageDexOpt(app.instrumentationInfo != null
4194 ? app.instrumentationInfo.packageName
4195 : app.info.packageName);
4196 if (app.instrumentationClass != null) {
4197 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004198 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004199 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004200 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004201 ApplicationInfo appInfo = app.instrumentationInfo != null
4202 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004203 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004204 if (profileFd != null) {
4205 profileFd = profileFd.dup();
4206 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004207 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004208 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004209 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4210 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004211 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004212 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004213 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004214 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 } catch (Exception e) {
4216 // todo: Yikes! What should we do? For now we will try to
4217 // start another process, but that could easily get us in
4218 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004219 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220
4221 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004222 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 startProcessLocked(app, "bind fail", processName);
4224 return false;
4225 }
4226
4227 // Remove this record from the list of starting applications.
4228 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004229 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4230 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 mProcessesOnHold.remove(app);
4232
4233 boolean badApp = false;
4234 boolean didSomething = false;
4235
4236 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004237 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004238 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004239 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 && processName.equals(hr.processName)) {
4241 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004242 if (mHeadless) {
4243 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4244 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 didSomething = true;
4246 }
4247 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004248 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 + hr.intent.getComponent().flattenToShortString(), e);
4250 badApp = true;
4251 }
4252 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004253 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 }
4255 }
4256
4257 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004258 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004260 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 badApp = true;
4263 }
4264 }
4265
Christopher Tatef46723b2012-01-26 14:19:24 -08004266 // Check if a next-broadcast receiver is in this process...
4267 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004269 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004271 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
4274 }
4275
Christopher Tate181fafa2009-05-14 11:12:14 -07004276 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004277 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004278 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004279 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004280 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004281 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4282 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4283 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004284 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004285 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004286 e.printStackTrace();
4287 }
4288 }
4289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 if (badApp) {
4291 // todo: Also need to kill application to deal with all
4292 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004293 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 return false;
4295 }
4296
4297 if (!didSomething) {
4298 updateOomAdjLocked();
4299 }
4300
4301 return true;
4302 }
4303
4304 public final void attachApplication(IApplicationThread thread) {
4305 synchronized (this) {
4306 int callingPid = Binder.getCallingPid();
4307 final long origId = Binder.clearCallingIdentity();
4308 attachApplicationLocked(thread, callingPid);
4309 Binder.restoreCallingIdentity(origId);
4310 }
4311 }
4312
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004313 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004315 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4316 if (stopProfiling) {
4317 synchronized (this) {
4318 if (mProfileProc == r.app) {
4319 if (mProfileFd != null) {
4320 try {
4321 mProfileFd.close();
4322 } catch (IOException e) {
4323 }
4324 clearProfilerLocked();
4325 }
4326 }
4327 }
4328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 Binder.restoreCallingIdentity(origId);
4330 }
4331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004333 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004334 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004336
4337 synchronized (this) {
4338 updateEventDispatchingLocked();
4339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341
Dianne Hackborn661cd522011-08-22 00:26:20 -07004342 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004343 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004344 mWindowManager.showBootMessage(msg, always);
4345 }
4346
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004347 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004348 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004349 final long token = Binder.clearCallingIdentity();
4350 try {
4351 synchronized (this) {
4352 if (mLockScreenShown) {
4353 mLockScreenShown = false;
4354 comeOutOfSleepIfNeededLocked();
4355 }
4356 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004357 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004358 } finally {
4359 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004360 }
4361 }
4362
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004363 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004364 IntentFilter pkgFilter = new IntentFilter();
4365 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4366 pkgFilter.addDataScheme("package");
4367 mContext.registerReceiver(new BroadcastReceiver() {
4368 @Override
4369 public void onReceive(Context context, Intent intent) {
4370 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4371 if (pkgs != null) {
4372 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004373 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004374 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4375 setResultCode(Activity.RESULT_OK);
4376 return;
4377 }
4378 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004379 }
4380 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004381 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004382 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004383
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004384 synchronized (this) {
4385 // Ensure that any processes we had put on hold are now started
4386 // up.
4387 final int NP = mProcessesOnHold.size();
4388 if (NP > 0) {
4389 ArrayList<ProcessRecord> procs =
4390 new ArrayList<ProcessRecord>(mProcessesOnHold);
4391 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004392 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4393 + procs.get(ip));
4394 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004395 }
4396 }
4397
4398 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004399 // Start looking for apps that are abusing wake locks.
4400 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004401 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004402 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004403 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004404 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004405 for (int i=0; i<mStartedUsers.size(); i++) {
4406 UserStartedState uss = mStartedUsers.valueAt(i);
4407 if (uss.mState == UserStartedState.STATE_BOOTING) {
4408 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004409 final int userId = mStartedUsers.keyAt(i);
4410 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4411 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4412 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004413 null, null, 0, null, null,
4414 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004415 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004416 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004417 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004418 }
4419 }
4420 }
4421
4422 final void ensureBootCompleted() {
4423 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004424 boolean enableScreen;
4425 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004426 booting = mBooting;
4427 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004428 enableScreen = !mBooted;
4429 mBooted = true;
4430 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004431
4432 if (booting) {
4433 finishBooting();
4434 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004435
4436 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004437 enableScreenAfterBoot();
4438 }
4439 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004440
4441 public final void activityResumed(IBinder token) {
4442 final long origId = Binder.clearCallingIdentity();
4443 mMainStack.activityResumed(token);
4444 Binder.restoreCallingIdentity(origId);
4445 }
4446
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004447 public final void activityPaused(IBinder token) {
4448 final long origId = Binder.clearCallingIdentity();
4449 mMainStack.activityPaused(token, false);
4450 Binder.restoreCallingIdentity(origId);
4451 }
4452
4453 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4454 CharSequence description) {
4455 if (localLOGV) Slog.v(
4456 TAG, "Activity stopped: token=" + token);
4457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004458 // Refuse possible leaked file descriptors
4459 if (icicle != null && icicle.hasFileDescriptors()) {
4460 throw new IllegalArgumentException("File descriptors passed in Bundle");
4461 }
4462
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004463 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464
4465 final long origId = Binder.clearCallingIdentity();
4466
4467 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004468 r = mMainStack.isInStackLocked(token);
4469 if (r != null) {
4470 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 }
4472 }
4473
4474 if (r != null) {
4475 sendPendingThumbnail(r, null, null, null, false);
4476 }
4477
4478 trimApplications();
4479
4480 Binder.restoreCallingIdentity(origId);
4481 }
4482
4483 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004484 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004485 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 }
4487
4488 public String getCallingPackage(IBinder token) {
4489 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004490 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004491 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 }
4493 }
4494
4495 public ComponentName getCallingActivity(IBinder token) {
4496 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004497 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 return r != null ? r.intent.getComponent() : null;
4499 }
4500 }
4501
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004502 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004503 ActivityRecord r = mMainStack.isInStackLocked(token);
4504 if (r == null) {
4505 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004507 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
4509
4510 public ComponentName getActivityClassForToken(IBinder token) {
4511 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004512 ActivityRecord r = mMainStack.isInStackLocked(token);
4513 if (r == null) {
4514 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004516 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518 }
4519
4520 public String getPackageForToken(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.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 }
4528 }
4529
4530 public IIntentSender getIntentSender(int type,
4531 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004532 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004533 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004534 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004536 if (intents != null) {
4537 if (intents.length < 1) {
4538 throw new IllegalArgumentException("Intents array length must be >= 1");
4539 }
4540 for (int i=0; i<intents.length; i++) {
4541 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004542 if (intent != null) {
4543 if (intent.hasFileDescriptors()) {
4544 throw new IllegalArgumentException("File descriptors passed in Intent");
4545 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004546 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004547 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4548 throw new IllegalArgumentException(
4549 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4550 }
4551 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004552 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004553 }
4554 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004555 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004556 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004557 }
4558 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004559 if (options != null) {
4560 if (options.hasFileDescriptors()) {
4561 throw new IllegalArgumentException("File descriptors passed in options");
4562 }
4563 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 synchronized(this) {
4566 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004567 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004568 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004569 type == ActivityManager.INTENT_SENDER_BROADCAST, true,
4570 "getIntentSender", null);
4571 if (origUserId == UserHandle.USER_CURRENT) {
4572 // We don't want to evaluate this until the pending intent is
4573 // actually executed. However, we do want to always do the
4574 // security checking for it above.
4575 userId = UserHandle.USER_CURRENT;
4576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004578 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004579 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004580 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4581 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 String msg = "Permission Denial: getIntentSender() from pid="
4583 + Binder.getCallingPid()
4584 + ", uid=" + Binder.getCallingUid()
4585 + ", (need uid=" + uid + ")"
4586 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004587 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 throw new SecurityException(msg);
4589 }
4590 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004591
4592 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004593 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 } catch (RemoteException e) {
4596 throw new SecurityException(e);
4597 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004598 }
4599 }
4600
Dianne Hackborn41203752012-08-31 14:05:51 -07004601 IIntentSender getIntentSenderLocked(int type, String packageName,
4602 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004603 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4604 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004605 if (DEBUG_MU)
4606 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004607 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004608 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004609 activity = mMainStack.isInStackLocked(token);
4610 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004611 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004613 if (activity.finishing) {
4614 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004616 }
4617
4618 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4619 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4620 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4621 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4622 |PendingIntent.FLAG_UPDATE_CURRENT);
4623
4624 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4625 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004626 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004627 WeakReference<PendingIntentRecord> ref;
4628 ref = mIntentSenderRecords.get(key);
4629 PendingIntentRecord rec = ref != null ? ref.get() : null;
4630 if (rec != null) {
4631 if (!cancelCurrent) {
4632 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004633 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004634 rec.key.requestIntent.replaceExtras(intents != null ?
4635 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004636 }
4637 if (intents != null) {
4638 intents[intents.length-1] = rec.key.requestIntent;
4639 rec.key.allIntents = intents;
4640 rec.key.allResolvedTypes = resolvedTypes;
4641 } else {
4642 rec.key.allIntents = null;
4643 rec.key.allResolvedTypes = null;
4644 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646 return rec;
4647 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004648 rec.canceled = true;
4649 mIntentSenderRecords.remove(key);
4650 }
4651 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 return rec;
4653 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004654 rec = new PendingIntentRecord(this, key, callingUid);
4655 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004656 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004657 if (activity.pendingResults == null) {
4658 activity.pendingResults
4659 = new HashSet<WeakReference<PendingIntentRecord>>();
4660 }
4661 activity.pendingResults.add(rec.ref);
4662 }
4663 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 }
4665
4666 public void cancelIntentSender(IIntentSender sender) {
4667 if (!(sender instanceof PendingIntentRecord)) {
4668 return;
4669 }
4670 synchronized(this) {
4671 PendingIntentRecord rec = (PendingIntentRecord)sender;
4672 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004673 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004674 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4675 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 String msg = "Permission Denial: cancelIntentSender() from pid="
4677 + Binder.getCallingPid()
4678 + ", uid=" + Binder.getCallingUid()
4679 + " is not allowed to cancel packges "
4680 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004681 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 throw new SecurityException(msg);
4683 }
4684 } catch (RemoteException e) {
4685 throw new SecurityException(e);
4686 }
4687 cancelIntentSenderLocked(rec, true);
4688 }
4689 }
4690
4691 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4692 rec.canceled = true;
4693 mIntentSenderRecords.remove(rec.key);
4694 if (cleanActivity && rec.key.activity != null) {
4695 rec.key.activity.pendingResults.remove(rec.ref);
4696 }
4697 }
4698
4699 public String getPackageForIntentSender(IIntentSender pendingResult) {
4700 if (!(pendingResult instanceof PendingIntentRecord)) {
4701 return null;
4702 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004703 try {
4704 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4705 return res.key.packageName;
4706 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
4708 return null;
4709 }
4710
Christopher Tatec4a07d12012-04-06 14:19:13 -07004711 public int getUidForIntentSender(IIntentSender sender) {
4712 if (sender instanceof PendingIntentRecord) {
4713 try {
4714 PendingIntentRecord res = (PendingIntentRecord)sender;
4715 return res.uid;
4716 } catch (ClassCastException e) {
4717 }
4718 }
4719 return -1;
4720 }
4721
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004722 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4723 if (!(pendingResult instanceof PendingIntentRecord)) {
4724 return false;
4725 }
4726 try {
4727 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4728 if (res.key.allIntents == null) {
4729 return false;
4730 }
4731 for (int i=0; i<res.key.allIntents.length; i++) {
4732 Intent intent = res.key.allIntents[i];
4733 if (intent.getPackage() != null && intent.getComponent() != null) {
4734 return false;
4735 }
4736 }
4737 return true;
4738 } catch (ClassCastException e) {
4739 }
4740 return false;
4741 }
4742
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004743 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4744 if (!(pendingResult instanceof PendingIntentRecord)) {
4745 return false;
4746 }
4747 try {
4748 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4749 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4750 return true;
4751 }
4752 return false;
4753 } catch (ClassCastException e) {
4754 }
4755 return false;
4756 }
4757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 public void setProcessLimit(int max) {
4759 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4760 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004761 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004762 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004763 mProcessLimitOverride = max;
4764 }
4765 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 }
4767
4768 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004769 synchronized (this) {
4770 return mProcessLimitOverride;
4771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004772 }
4773
4774 void foregroundTokenDied(ForegroundToken token) {
4775 synchronized (ActivityManagerService.this) {
4776 synchronized (mPidsSelfLocked) {
4777 ForegroundToken cur
4778 = mForegroundProcesses.get(token.pid);
4779 if (cur != token) {
4780 return;
4781 }
4782 mForegroundProcesses.remove(token.pid);
4783 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4784 if (pr == null) {
4785 return;
4786 }
4787 pr.forcingToForeground = null;
4788 pr.foregroundServices = false;
4789 }
4790 updateOomAdjLocked();
4791 }
4792 }
4793
4794 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4795 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4796 "setProcessForeground()");
4797 synchronized(this) {
4798 boolean changed = false;
4799
4800 synchronized (mPidsSelfLocked) {
4801 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004802 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004803 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 return;
4805 }
4806 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4807 if (oldToken != null) {
4808 oldToken.token.unlinkToDeath(oldToken, 0);
4809 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004810 if (pr != null) {
4811 pr.forcingToForeground = null;
4812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 changed = true;
4814 }
4815 if (isForeground && token != null) {
4816 ForegroundToken newToken = new ForegroundToken() {
4817 public void binderDied() {
4818 foregroundTokenDied(this);
4819 }
4820 };
4821 newToken.pid = pid;
4822 newToken.token = token;
4823 try {
4824 token.linkToDeath(newToken, 0);
4825 mForegroundProcesses.put(pid, newToken);
4826 pr.forcingToForeground = token;
4827 changed = true;
4828 } catch (RemoteException e) {
4829 // If the process died while doing this, we will later
4830 // do the cleanup with the process death link.
4831 }
4832 }
4833 }
4834
4835 if (changed) {
4836 updateOomAdjLocked();
4837 }
4838 }
4839 }
4840
4841 // =========================================================
4842 // PERMISSIONS
4843 // =========================================================
4844
4845 static class PermissionController extends IPermissionController.Stub {
4846 ActivityManagerService mActivityManagerService;
4847 PermissionController(ActivityManagerService activityManagerService) {
4848 mActivityManagerService = activityManagerService;
4849 }
4850
4851 public boolean checkPermission(String permission, int pid, int uid) {
4852 return mActivityManagerService.checkPermission(permission, pid,
4853 uid) == PackageManager.PERMISSION_GRANTED;
4854 }
4855 }
4856
4857 /**
4858 * This can be called with or without the global lock held.
4859 */
4860 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004861 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004862 // We might be performing an operation on behalf of an indirect binder
4863 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4864 // client identity accordingly before proceeding.
4865 Identity tlsIdentity = sCallerIdentity.get();
4866 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004867 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4869 uid = tlsIdentity.uid;
4870 pid = tlsIdentity.pid;
4871 }
4872
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004873 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004874 return PackageManager.PERMISSION_GRANTED;
4875 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004876
4877 return ActivityManager.checkComponentPermission(permission, uid,
4878 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004879 }
4880
4881 /**
4882 * As the only public entry point for permissions checking, this method
4883 * can enforce the semantic that requesting a check on a null global
4884 * permission is automatically denied. (Internally a null permission
4885 * string is used when calling {@link #checkComponentPermission} in cases
4886 * when only uid-based security is needed.)
4887 *
4888 * This can be called with or without the global lock held.
4889 */
4890 public int checkPermission(String permission, int pid, int uid) {
4891 if (permission == null) {
4892 return PackageManager.PERMISSION_DENIED;
4893 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004894 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 }
4896
4897 /**
4898 * Binder IPC calls go through the public entry point.
4899 * This can be called with or without the global lock held.
4900 */
4901 int checkCallingPermission(String permission) {
4902 return checkPermission(permission,
4903 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004904 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 }
4906
4907 /**
4908 * This can be called with or without the global lock held.
4909 */
4910 void enforceCallingPermission(String permission, String func) {
4911 if (checkCallingPermission(permission)
4912 == PackageManager.PERMISSION_GRANTED) {
4913 return;
4914 }
4915
4916 String msg = "Permission Denial: " + func + " from pid="
4917 + Binder.getCallingPid()
4918 + ", uid=" + Binder.getCallingUid()
4919 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004920 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 throw new SecurityException(msg);
4922 }
4923
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004924 /**
4925 * Determine if UID is holding permissions required to access {@link Uri} in
4926 * the given {@link ProviderInfo}. Final permission checking is always done
4927 * in {@link ContentProvider}.
4928 */
4929 private final boolean checkHoldingPermissionsLocked(
4930 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004931 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4932 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004933
4934 if (pi.applicationInfo.uid == uid) {
4935 return true;
4936 } else if (!pi.exported) {
4937 return false;
4938 }
4939
4940 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4941 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004943 // check if target holds top-level <provider> permissions
4944 if (!readMet && pi.readPermission != null
4945 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4946 readMet = true;
4947 }
4948 if (!writeMet && pi.writePermission != null
4949 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4950 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004952
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004953 // track if unprotected read/write is allowed; any denied
4954 // <path-permission> below removes this ability
4955 boolean allowDefaultRead = pi.readPermission == null;
4956 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004957
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004958 // check if target holds any <path-permission> that match uri
4959 final PathPermission[] pps = pi.pathPermissions;
4960 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004961 final String path = uri.getPath();
4962 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004963 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004964 i--;
4965 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004966 if (pp.match(path)) {
4967 if (!readMet) {
4968 final String pprperm = pp.getReadPermission();
4969 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4970 + pprperm + " for " + pp.getPath()
4971 + ": match=" + pp.match(path)
4972 + " check=" + pm.checkUidPermission(pprperm, uid));
4973 if (pprperm != null) {
4974 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4975 readMet = true;
4976 } else {
4977 allowDefaultRead = false;
4978 }
4979 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004980 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004981 if (!writeMet) {
4982 final String ppwperm = pp.getWritePermission();
4983 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4984 + ppwperm + " for " + pp.getPath()
4985 + ": match=" + pp.match(path)
4986 + " check=" + pm.checkUidPermission(ppwperm, uid));
4987 if (ppwperm != null) {
4988 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4989 writeMet = true;
4990 } else {
4991 allowDefaultWrite = false;
4992 }
4993 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004994 }
4995 }
4996 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004997 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004998
4999 // grant unprotected <provider> read/write, if not blocked by
5000 // <path-permission> above
5001 if (allowDefaultRead) readMet = true;
5002 if (allowDefaultWrite) writeMet = true;
5003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005004 } catch (RemoteException e) {
5005 return false;
5006 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005007
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005008 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005009 }
5010
5011 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5012 int modeFlags) {
5013 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005014 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 return true;
5016 }
5017 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5018 if (perms == null) return false;
5019 UriPermission perm = perms.get(uri);
5020 if (perm == null) return false;
5021 return (modeFlags&perm.modeFlags) == modeFlags;
5022 }
5023
5024 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005025 enforceNotIsolatedCaller("checkUriPermission");
5026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005027 // Another redirected-binder-call permissions check as in
5028 // {@link checkComponentPermission}.
5029 Identity tlsIdentity = sCallerIdentity.get();
5030 if (tlsIdentity != null) {
5031 uid = tlsIdentity.uid;
5032 pid = tlsIdentity.pid;
5033 }
5034
5035 // Our own process gets to do everything.
5036 if (pid == MY_PID) {
5037 return PackageManager.PERMISSION_GRANTED;
5038 }
5039 synchronized(this) {
5040 return checkUriPermissionLocked(uri, uid, modeFlags)
5041 ? PackageManager.PERMISSION_GRANTED
5042 : PackageManager.PERMISSION_DENIED;
5043 }
5044 }
5045
Dianne Hackborn39792d22010-08-19 18:01:52 -07005046 /**
5047 * Check if the targetPkg can be granted permission to access uri by
5048 * the callingUid using the given modeFlags. Throws a security exception
5049 * if callingUid is not allowed to do this. Returns the uid of the target
5050 * if the URI permission grant should be performed; returns -1 if it is not
5051 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005052 * If you already know the uid of the target, you can supply it in
5053 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005054 */
5055 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005056 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5058 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5059 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005060 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 }
5062
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005063 if (targetPkg != null) {
5064 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5065 "Checking grant " + targetPkg + " permission to " + uri);
5066 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005067
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005068 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069
5070 // If this is not a content: uri, we can't do anything with it.
5071 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005072 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005073 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005074 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005075 }
5076
5077 String name = uri.getAuthority();
5078 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005079 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005080 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 if (cpr != null) {
5082 pi = cpr.info;
5083 } else {
5084 try {
5085 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005086 PackageManager.GET_URI_PERMISSION_PATTERNS,
5087 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 } catch (RemoteException ex) {
5089 }
5090 }
5091 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005092 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005093 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 }
5095
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005096 int targetUid = lastTargetUid;
5097 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005098 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005099 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005100 if (targetUid < 0) {
5101 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5102 "Can't grant URI permission no uid for: " + targetPkg);
5103 return -1;
5104 }
5105 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005106 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108 }
5109
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005110 if (targetUid >= 0) {
5111 // First... does the target actually need this permission?
5112 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5113 // No need to grant the target this permission.
5114 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5115 "Target " + targetPkg + " already has full permission to " + uri);
5116 return -1;
5117 }
5118 } else {
5119 // First... there is no target package, so can anyone access it?
5120 boolean allowed = pi.exported;
5121 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5122 if (pi.readPermission != null) {
5123 allowed = false;
5124 }
5125 }
5126 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5127 if (pi.writePermission != null) {
5128 allowed = false;
5129 }
5130 }
5131 if (allowed) {
5132 return -1;
5133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 }
5135
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005136 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 if (!pi.grantUriPermissions) {
5138 throw new SecurityException("Provider " + pi.packageName
5139 + "/" + pi.name
5140 + " does not allow granting of Uri permissions (uri "
5141 + uri + ")");
5142 }
5143 if (pi.uriPermissionPatterns != null) {
5144 final int N = pi.uriPermissionPatterns.length;
5145 boolean allowed = false;
5146 for (int i=0; i<N; i++) {
5147 if (pi.uriPermissionPatterns[i] != null
5148 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5149 allowed = true;
5150 break;
5151 }
5152 }
5153 if (!allowed) {
5154 throw new SecurityException("Provider " + pi.packageName
5155 + "/" + pi.name
5156 + " does not allow granting of permission to path of Uri "
5157 + uri);
5158 }
5159 }
5160
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005161 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005163 if (callingUid != Process.myUid()) {
5164 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5165 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5166 throw new SecurityException("Uid " + callingUid
5167 + " does not have permission to uri " + uri);
5168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 }
5170 }
5171
Dianne Hackborn39792d22010-08-19 18:01:52 -07005172 return targetUid;
5173 }
5174
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005175 public int checkGrantUriPermission(int callingUid, String targetPkg,
5176 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005177 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005178 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005179 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005180 }
5181 }
5182
Dianne Hackborn39792d22010-08-19 18:01:52 -07005183 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5184 Uri uri, int modeFlags, UriPermissionOwner owner) {
5185 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5186 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5187 if (modeFlags == 0) {
5188 return;
5189 }
5190
5191 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 // to the uri, and the target doesn't. Let's now give this to
5193 // the target.
5194
Joe Onorato8a9b2202010-02-26 18:56:32 -08005195 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005196 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 HashMap<Uri, UriPermission> targetUris
5199 = mGrantedUriPermissions.get(targetUid);
5200 if (targetUris == null) {
5201 targetUris = new HashMap<Uri, UriPermission>();
5202 mGrantedUriPermissions.put(targetUid, targetUris);
5203 }
5204
5205 UriPermission perm = targetUris.get(uri);
5206 if (perm == null) {
5207 perm = new UriPermission(targetUid, uri);
5208 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005212 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005214 } else {
5215 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5216 perm.readOwners.add(owner);
5217 owner.addReadPermission(perm);
5218 }
5219 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5220 perm.writeOwners.add(owner);
5221 owner.addWritePermission(perm);
5222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 }
5224 }
5225
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005226 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5227 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005228 if (targetPkg == null) {
5229 throw new NullPointerException("targetPkg");
5230 }
5231
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005232 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005233 if (targetUid < 0) {
5234 return;
5235 }
5236
5237 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5238 }
5239
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005240 static class NeededUriGrants extends ArrayList<Uri> {
5241 final String targetPkg;
5242 final int targetUid;
5243 final int flags;
5244
5245 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5246 targetPkg = _targetPkg;
5247 targetUid = _targetUid;
5248 flags = _flags;
5249 }
5250 }
5251
Dianne Hackborn39792d22010-08-19 18:01:52 -07005252 /**
5253 * Like checkGrantUriPermissionLocked, but takes an Intent.
5254 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005255 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5256 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005257 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005258 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5259 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005260 + " from " + intent + "; flags=0x"
5261 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5262
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005263 if (targetPkg == null) {
5264 throw new NullPointerException("targetPkg");
5265 }
5266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005268 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 }
5270 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005271 ClipData clip = intent.getClipData();
5272 if (data == null && clip == null) {
5273 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005274 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005275 if (data != null) {
5276 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5277 mode, needed != null ? needed.targetUid : -1);
5278 if (target > 0) {
5279 if (needed == null) {
5280 needed = new NeededUriGrants(targetPkg, target, mode);
5281 }
5282 needed.add(data);
5283 }
5284 }
5285 if (clip != null) {
5286 for (int i=0; i<clip.getItemCount(); i++) {
5287 Uri uri = clip.getItemAt(i).getUri();
5288 if (uri != null) {
5289 int target = -1;
5290 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5291 mode, needed != null ? needed.targetUid : -1);
5292 if (target > 0) {
5293 if (needed == null) {
5294 needed = new NeededUriGrants(targetPkg, target, mode);
5295 }
5296 needed.add(uri);
5297 }
5298 } else {
5299 Intent clipIntent = clip.getItemAt(i).getIntent();
5300 if (clipIntent != null) {
5301 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5302 callingUid, targetPkg, clipIntent, mode, needed);
5303 if (newNeeded != null) {
5304 needed = newNeeded;
5305 }
5306 }
5307 }
5308 }
5309 }
5310
5311 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005312 }
5313
5314 /**
5315 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5316 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005317 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5318 UriPermissionOwner owner) {
5319 if (needed != null) {
5320 for (int i=0; i<needed.size(); i++) {
5321 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5322 needed.get(i), needed.flags, owner);
5323 }
5324 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005325 }
5326
5327 void grantUriPermissionFromIntentLocked(int callingUid,
5328 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005329 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005330 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005331 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 return;
5333 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005334
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005335 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 }
5337
5338 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5339 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005340 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 synchronized(this) {
5342 final ProcessRecord r = getRecordForAppLocked(caller);
5343 if (r == null) {
5344 throw new SecurityException("Unable to find app for caller "
5345 + caller
5346 + " when granting permission to uri " + uri);
5347 }
5348 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005349 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 }
5351 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005352 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 }
5354
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005355 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 null);
5357 }
5358 }
5359
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005360 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5362 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5363 HashMap<Uri, UriPermission> perms
5364 = mGrantedUriPermissions.get(perm.uid);
5365 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005366 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005367 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 perms.remove(perm.uri);
5369 if (perms.size() == 0) {
5370 mGrantedUriPermissions.remove(perm.uid);
5371 }
5372 }
5373 }
5374 }
5375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5377 int modeFlags) {
5378 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5379 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5380 if (modeFlags == 0) {
5381 return;
5382 }
5383
Joe Onorato8a9b2202010-02-26 18:56:32 -08005384 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005385 "Revoking all granted permissions to " + uri);
5386
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005387 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388
5389 final String authority = uri.getAuthority();
5390 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005391 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005392 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 if (cpr != null) {
5394 pi = cpr.info;
5395 } else {
5396 try {
5397 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005398 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 } catch (RemoteException ex) {
5400 }
5401 }
5402 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005403 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 return;
5405 }
5406
5407 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005408 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 // Right now, if you are not the original owner of the permission,
5410 // you are not allowed to revoke it.
5411 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5412 throw new SecurityException("Uid " + callingUid
5413 + " does not have permission to uri " + uri);
5414 //}
5415 }
5416
5417 // Go through all of the permissions and remove any that match.
5418 final List<String> SEGMENTS = uri.getPathSegments();
5419 if (SEGMENTS != null) {
5420 final int NS = SEGMENTS.size();
5421 int N = mGrantedUriPermissions.size();
5422 for (int i=0; i<N; i++) {
5423 HashMap<Uri, UriPermission> perms
5424 = mGrantedUriPermissions.valueAt(i);
5425 Iterator<UriPermission> it = perms.values().iterator();
5426 toploop:
5427 while (it.hasNext()) {
5428 UriPermission perm = it.next();
5429 Uri targetUri = perm.uri;
5430 if (!authority.equals(targetUri.getAuthority())) {
5431 continue;
5432 }
5433 List<String> targetSegments = targetUri.getPathSegments();
5434 if (targetSegments == null) {
5435 continue;
5436 }
5437 if (targetSegments.size() < NS) {
5438 continue;
5439 }
5440 for (int j=0; j<NS; j++) {
5441 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5442 continue toploop;
5443 }
5444 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005445 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005446 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 perm.clearModes(modeFlags);
5448 if (perm.modeFlags == 0) {
5449 it.remove();
5450 }
5451 }
5452 if (perms.size() == 0) {
5453 mGrantedUriPermissions.remove(
5454 mGrantedUriPermissions.keyAt(i));
5455 N--;
5456 i--;
5457 }
5458 }
5459 }
5460 }
5461
5462 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5463 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005464 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 synchronized(this) {
5466 final ProcessRecord r = getRecordForAppLocked(caller);
5467 if (r == null) {
5468 throw new SecurityException("Unable to find app for caller "
5469 + caller
5470 + " when revoking permission to uri " + uri);
5471 }
5472 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005473 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 return;
5475 }
5476
5477 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5478 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5479 if (modeFlags == 0) {
5480 return;
5481 }
5482
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005483 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484
5485 final String authority = uri.getAuthority();
5486 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005487 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 if (cpr != null) {
5489 pi = cpr.info;
5490 } else {
5491 try {
5492 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005493 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 } catch (RemoteException ex) {
5495 }
5496 }
5497 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005498 Slog.w(TAG, "No content provider found for permission revoke: "
5499 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 return;
5501 }
5502
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005503 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 }
5505 }
5506
Dianne Hackborn7e269642010-08-25 19:50:20 -07005507 @Override
5508 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005509 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005510 synchronized(this) {
5511 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5512 return owner.getExternalTokenLocked();
5513 }
5514 }
5515
5516 @Override
5517 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5518 Uri uri, int modeFlags) {
5519 synchronized(this) {
5520 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5521 if (owner == null) {
5522 throw new IllegalArgumentException("Unknown owner: " + token);
5523 }
5524 if (fromUid != Binder.getCallingUid()) {
5525 if (Binder.getCallingUid() != Process.myUid()) {
5526 // Only system code can grant URI permissions on behalf
5527 // of other users.
5528 throw new SecurityException("nice try");
5529 }
5530 }
5531 if (targetPkg == null) {
5532 throw new IllegalArgumentException("null target");
5533 }
5534 if (uri == null) {
5535 throw new IllegalArgumentException("null uri");
5536 }
5537
5538 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5539 }
5540 }
5541
5542 @Override
5543 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5544 synchronized(this) {
5545 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5546 if (owner == null) {
5547 throw new IllegalArgumentException("Unknown owner: " + token);
5548 }
5549
5550 if (uri == null) {
5551 owner.removeUriPermissionsLocked(mode);
5552 } else {
5553 owner.removeUriPermissionLocked(uri, mode);
5554 }
5555 }
5556 }
5557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5559 synchronized (this) {
5560 ProcessRecord app =
5561 who != null ? getRecordForAppLocked(who) : null;
5562 if (app == null) return;
5563
5564 Message msg = Message.obtain();
5565 msg.what = WAIT_FOR_DEBUGGER_MSG;
5566 msg.obj = app;
5567 msg.arg1 = waiting ? 1 : 0;
5568 mHandler.sendMessage(msg);
5569 }
5570 }
5571
5572 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005573 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5574 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005576 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005577 outInfo.threshold = homeAppMem;
5578 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5579 outInfo.hiddenAppThreshold = hiddenAppMem;
5580 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005581 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005582 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5583 ProcessList.VISIBLE_APP_ADJ);
5584 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5585 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 }
5587
5588 // =========================================================
5589 // TASK MANAGEMENT
5590 // =========================================================
5591
5592 public List getTasks(int maxNum, int flags,
5593 IThumbnailReceiver receiver) {
5594 ArrayList list = new ArrayList();
5595
5596 PendingThumbnailsRecord pending = null;
5597 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005598 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599
5600 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005601 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5603 + ", receiver=" + receiver);
5604
5605 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5606 != PackageManager.PERMISSION_GRANTED) {
5607 if (receiver != null) {
5608 // If the caller wants to wait for pending thumbnails,
5609 // it ain't gonna get them.
5610 try {
5611 receiver.finished();
5612 } catch (RemoteException ex) {
5613 }
5614 }
5615 String msg = "Permission Denial: getTasks() from pid="
5616 + Binder.getCallingPid()
5617 + ", uid=" + Binder.getCallingUid()
5618 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005619 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 throw new SecurityException(msg);
5621 }
5622
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005623 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005624 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005625 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005626 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 TaskRecord curTask = null;
5628 int numActivities = 0;
5629 int numRunning = 0;
5630 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005631 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005633 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634
5635 // Initialize state for next task if needed.
5636 if (top == null ||
5637 (top.state == ActivityState.INITIALIZING
5638 && top.task == r.task)) {
5639 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 curTask = r.task;
5641 numActivities = numRunning = 0;
5642 }
5643
5644 // Add 'r' into the current task.
5645 numActivities++;
5646 if (r.app != null && r.app.thread != null) {
5647 numRunning++;
5648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649
Joe Onorato8a9b2202010-02-26 18:56:32 -08005650 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 TAG, r.intent.getComponent().flattenToShortString()
5652 + ": task=" + r.task);
5653
5654 // If the next one is a different task, generate a new
5655 // TaskInfo entry for what we have.
5656 if (next == null || next.task != curTask) {
5657 ActivityManager.RunningTaskInfo ci
5658 = new ActivityManager.RunningTaskInfo();
5659 ci.id = curTask.taskId;
5660 ci.baseActivity = r.intent.getComponent();
5661 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005662 if (top.thumbHolder != null) {
5663 ci.description = top.thumbHolder.lastDescription;
5664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 ci.numActivities = numActivities;
5666 ci.numRunning = numRunning;
5667 //System.out.println(
5668 // "#" + maxNum + ": " + " descr=" + ci.description);
5669 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005670 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 TAG, "State=" + top.state + "Idle=" + top.idle
5672 + " app=" + top.app
5673 + " thr=" + (top.app != null ? top.app.thread : null));
5674 if (top.state == ActivityState.RESUMED
5675 || top.state == ActivityState.PAUSING) {
5676 if (top.idle && top.app != null
5677 && top.app.thread != null) {
5678 topRecord = top;
5679 topThumbnail = top.app.thread;
5680 } else {
5681 top.thumbnailNeeded = true;
5682 }
5683 }
5684 if (pending == null) {
5685 pending = new PendingThumbnailsRecord(receiver);
5686 }
5687 pending.pendingRecords.add(top);
5688 }
5689 list.add(ci);
5690 maxNum--;
5691 top = null;
5692 }
5693 }
5694
5695 if (pending != null) {
5696 mPendingThumbnails.add(pending);
5697 }
5698 }
5699
Joe Onorato8a9b2202010-02-26 18:56:32 -08005700 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701
5702 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005703 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005705 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005707 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005708 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 }
5710 }
5711
5712 if (pending == null && receiver != null) {
5713 // In this case all thumbnails were available and the client
5714 // is being asked to be told when the remaining ones come in...
5715 // which is unusually, since the top-most currently running
5716 // activity should never have a canned thumbnail! Oh well.
5717 try {
5718 receiver.finished();
5719 } catch (RemoteException ex) {
5720 }
5721 }
5722
5723 return list;
5724 }
5725
5726 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005727 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005728 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5729 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 synchronized (this) {
5732 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5733 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005734 final boolean detailed = checkCallingPermission(
5735 android.Manifest.permission.GET_DETAILED_TASKS)
5736 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005738 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 final int N = mRecentTasks.size();
5741 ArrayList<ActivityManager.RecentTaskInfo> res
5742 = new ArrayList<ActivityManager.RecentTaskInfo>(
5743 maxNum < N ? maxNum : N);
5744 for (int i=0; i<N && maxNum > 0; i++) {
5745 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005746 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005747 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005748 // Return the entry if desired by the caller. We always return
5749 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005750 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005751 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5752 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005753
Dianne Hackborn905577f2011-09-07 18:31:28 -07005754 if (i == 0
5755 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 || (tr.intent == null)
5757 || ((tr.intent.getFlags()
5758 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5759 ActivityManager.RecentTaskInfo rti
5760 = new ActivityManager.RecentTaskInfo();
5761 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005762 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 rti.baseIntent = new Intent(
5764 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005765 if (!detailed) {
5766 rti.baseIntent.replaceExtras((Bundle)null);
5767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005769 rti.description = tr.lastDescription;
5770
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005771 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5772 // Check whether this activity is currently available.
5773 try {
5774 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005775 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005776 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005777 continue;
5778 }
5779 } else if (rti.baseIntent != null) {
5780 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005781 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005782 continue;
5783 }
5784 }
5785 } catch (RemoteException e) {
5786 // Will never happen.
5787 }
5788 }
5789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 res.add(rti);
5791 maxNum--;
5792 }
5793 }
5794 return res;
5795 }
5796 }
5797
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005798 private TaskRecord taskForIdLocked(int id) {
5799 final int N = mRecentTasks.size();
5800 for (int i=0; i<N; i++) {
5801 TaskRecord tr = mRecentTasks.get(i);
5802 if (tr.taskId == id) {
5803 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005804 }
5805 }
5806 return null;
5807 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005808
5809 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5810 synchronized (this) {
5811 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5812 "getTaskThumbnails()");
5813 TaskRecord tr = taskForIdLocked(id);
5814 if (tr != null) {
5815 return mMainStack.getTaskThumbnailsLocked(tr);
5816 }
5817 }
5818 return null;
5819 }
5820
Dianne Hackborn15491c62012-09-19 10:59:14 -07005821 public Bitmap getTaskTopThumbnail(int id) {
5822 synchronized (this) {
5823 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5824 "getTaskTopThumbnail()");
5825 TaskRecord tr = taskForIdLocked(id);
5826 if (tr != null) {
5827 return mMainStack.getTaskTopThumbnailLocked(tr);
5828 }
5829 }
5830 return null;
5831 }
5832
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005833 public boolean removeSubTask(int taskId, int subTaskIndex) {
5834 synchronized (this) {
5835 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5836 "removeSubTask()");
5837 long ident = Binder.clearCallingIdentity();
5838 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005839 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5840 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005841 } finally {
5842 Binder.restoreCallingIdentity(ident);
5843 }
5844 }
5845 }
5846
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005847 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5848 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005849 Intent baseIntent = new Intent(
5850 tr.intent != null ? tr.intent : tr.affinityIntent);
5851 ComponentName component = baseIntent.getComponent();
5852 if (component == null) {
5853 Slog.w(TAG, "Now component for base intent of task: " + tr);
5854 return;
5855 }
5856
5857 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005858 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005859
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005860 if (killProcesses) {
5861 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005862 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005863 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005864 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5865 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5866 for (int i=0; i<uids.size(); i++) {
5867 ProcessRecord proc = uids.valueAt(i);
5868 if (proc.userId != tr.userId) {
5869 continue;
5870 }
5871 if (!proc.pkgList.contains(pkg)) {
5872 continue;
5873 }
5874 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005875 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005876 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005877
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005878 // Kill the running processes.
5879 for (int i=0; i<procs.size(); i++) {
5880 ProcessRecord pr = procs.get(i);
5881 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5882 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005883 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005884 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005885 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005886 Process.killProcessQuiet(pr.pid);
5887 } else {
5888 pr.waitingToKill = "remove task";
5889 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005890 }
5891 }
5892 }
5893
5894 public boolean removeTask(int taskId, int flags) {
5895 synchronized (this) {
5896 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5897 "removeTask()");
5898 long ident = Binder.clearCallingIdentity();
5899 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005900 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5901 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005902 if (r != null) {
5903 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005904 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005905 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005906 } else {
5907 TaskRecord tr = null;
5908 int i=0;
5909 while (i < mRecentTasks.size()) {
5910 TaskRecord t = mRecentTasks.get(i);
5911 if (t.taskId == taskId) {
5912 tr = t;
5913 break;
5914 }
5915 i++;
5916 }
5917 if (tr != null) {
5918 if (tr.numActivities <= 0) {
5919 // Caller is just removing a recent task that is
5920 // not actively running. That is easy!
5921 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005922 cleanUpRemovedTaskLocked(tr, flags);
5923 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005924 } else {
5925 Slog.w(TAG, "removeTask: task " + taskId
5926 + " does not have activities to remove, "
5927 + " but numActivities=" + tr.numActivities
5928 + ": " + tr);
5929 }
5930 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005931 }
5932 } finally {
5933 Binder.restoreCallingIdentity(ident);
5934 }
5935 }
5936 return false;
5937 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5940 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005941 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 TaskRecord jt = startTask;
5943
5944 // First look backwards
5945 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005946 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 if (r.task != jt) {
5948 jt = r.task;
5949 if (affinity.equals(jt.affinity)) {
5950 return j;
5951 }
5952 }
5953 }
5954
5955 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005956 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 jt = startTask;
5958 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005959 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 if (r.task != jt) {
5961 if (affinity.equals(jt.affinity)) {
5962 return j;
5963 }
5964 jt = r.task;
5965 }
5966 }
5967
5968 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005969 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 return N-1;
5971 }
5972
5973 return -1;
5974 }
5975
5976 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005977 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005979 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5981 "moveTaskToFront()");
5982
5983 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005984 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5985 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005986 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005987 return;
5988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 final long origId = Binder.clearCallingIdentity();
5990 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005991 TaskRecord tr = taskForIdLocked(task);
5992 if (tr != null) {
5993 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5994 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005996 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5997 // Caller wants the home activity moved with it. To accomplish this,
5998 // we'll just move the home task to the top first.
5999 mMainStack.moveHomeToFrontLocked();
6000 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006001 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006002 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006004 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6005 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006007 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6008 mMainStack.mUserLeaving = true;
6009 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006010 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6011 // Caller wants the home activity moved with it. To accomplish this,
6012 // we'll just move the home task to the top first.
6013 mMainStack.moveHomeToFrontLocked();
6014 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006015 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 return;
6017 }
6018 }
6019 } finally {
6020 Binder.restoreCallingIdentity(origId);
6021 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006022 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 }
6024 }
6025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 public void moveTaskToBack(int task) {
6027 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6028 "moveTaskToBack()");
6029
6030 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006031 if (mMainStack.mResumedActivity != null
6032 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006033 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6034 Binder.getCallingUid(), "Task to back")) {
6035 return;
6036 }
6037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006039 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 Binder.restoreCallingIdentity(origId);
6041 }
6042 }
6043
6044 /**
6045 * Moves an activity, and all of the other activities within the same task, to the bottom
6046 * of the history stack. The activity's order within the task is unchanged.
6047 *
6048 * @param token A reference to the activity we wish to move
6049 * @param nonRoot If false then this only works if the activity is the root
6050 * of a task; if true it will work for any activity in a task.
6051 * @return Returns true if the move completed, false if not.
6052 */
6053 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006054 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 synchronized(this) {
6056 final long origId = Binder.clearCallingIdentity();
6057 int taskId = getTaskForActivityLocked(token, !nonRoot);
6058 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006059 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
6061 Binder.restoreCallingIdentity(origId);
6062 }
6063 return false;
6064 }
6065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 public void moveTaskBackwards(int task) {
6067 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6068 "moveTaskBackwards()");
6069
6070 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006071 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6072 Binder.getCallingUid(), "Task backwards")) {
6073 return;
6074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 final long origId = Binder.clearCallingIdentity();
6076 moveTaskBackwardsLocked(task);
6077 Binder.restoreCallingIdentity(origId);
6078 }
6079 }
6080
6081 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006082 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 }
6084
6085 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6086 synchronized(this) {
6087 return getTaskForActivityLocked(token, onlyRoot);
6088 }
6089 }
6090
6091 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006092 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 TaskRecord lastTask = null;
6094 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006095 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006096 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 if (!onlyRoot || lastTask != r.task) {
6098 return r.task.taskId;
6099 }
6100 return -1;
6101 }
6102 lastTask = r.task;
6103 }
6104
6105 return -1;
6106 }
6107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 // =========================================================
6109 // THUMBNAILS
6110 // =========================================================
6111
6112 public void reportThumbnail(IBinder token,
6113 Bitmap thumbnail, CharSequence description) {
6114 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6115 final long origId = Binder.clearCallingIdentity();
6116 sendPendingThumbnail(null, token, thumbnail, description, true);
6117 Binder.restoreCallingIdentity(origId);
6118 }
6119
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006120 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 Bitmap thumbnail, CharSequence description, boolean always) {
6122 TaskRecord task = null;
6123 ArrayList receivers = null;
6124
6125 //System.out.println("Send pending thumbnail: " + r);
6126
6127 synchronized(this) {
6128 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006129 r = mMainStack.isInStackLocked(token);
6130 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 return;
6132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006134 if (thumbnail == null && r.thumbHolder != null) {
6135 thumbnail = r.thumbHolder.lastThumbnail;
6136 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 }
6138 if (thumbnail == null && !always) {
6139 // If there is no thumbnail, and this entry is not actually
6140 // going away, then abort for now and pick up the next
6141 // thumbnail we get.
6142 return;
6143 }
6144 task = r.task;
6145
6146 int N = mPendingThumbnails.size();
6147 int i=0;
6148 while (i<N) {
6149 PendingThumbnailsRecord pr =
6150 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6151 //System.out.println("Looking in " + pr.pendingRecords);
6152 if (pr.pendingRecords.remove(r)) {
6153 if (receivers == null) {
6154 receivers = new ArrayList();
6155 }
6156 receivers.add(pr);
6157 if (pr.pendingRecords.size() == 0) {
6158 pr.finished = true;
6159 mPendingThumbnails.remove(i);
6160 N--;
6161 continue;
6162 }
6163 }
6164 i++;
6165 }
6166 }
6167
6168 if (receivers != null) {
6169 final int N = receivers.size();
6170 for (int i=0; i<N; i++) {
6171 try {
6172 PendingThumbnailsRecord pr =
6173 (PendingThumbnailsRecord)receivers.get(i);
6174 pr.receiver.newThumbnail(
6175 task != null ? task.taskId : -1, thumbnail, description);
6176 if (pr.finished) {
6177 pr.receiver.finished();
6178 }
6179 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006180 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 }
6182 }
6183 }
6184 }
6185
6186 // =========================================================
6187 // CONTENT PROVIDERS
6188 // =========================================================
6189
Jeff Brown10e89712011-07-08 18:52:57 -07006190 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6191 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006193 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006194 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006195 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 } catch (RemoteException ex) {
6197 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006198 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006199 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6200 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006202 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 for (int i=0; i<N; i++) {
6204 ProviderInfo cpi =
6205 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006206 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6207 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006208 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006209 // This is a singleton provider, but a user besides the
6210 // default user is asking to initialize a process it runs
6211 // in... well, no, it doesn't actually run in this process,
6212 // it runs in the process of the default user. Get rid of it.
6213 providers.remove(i);
6214 N--;
6215 continue;
6216 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006217
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006218 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006219 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006221 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006222 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006224 if (DEBUG_MU)
6225 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 app.pubProviders.put(cpi.name, cpr);
6227 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006228 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 }
6230 }
6231 return providers;
6232 }
6233
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006234 /**
6235 * Check if {@link ProcessRecord} has a possible chance at accessing the
6236 * given {@link ProviderInfo}. Final permission checking is always done
6237 * in {@link ContentProvider}.
6238 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006240 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006242 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006244 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006245 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 return null;
6247 }
6248 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006249 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 == PackageManager.PERMISSION_GRANTED) {
6251 return null;
6252 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006253
6254 PathPermission[] pps = cpi.pathPermissions;
6255 if (pps != null) {
6256 int i = pps.length;
6257 while (i > 0) {
6258 i--;
6259 PathPermission pp = pps[i];
6260 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006261 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006262 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006263 return null;
6264 }
6265 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006266 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006267 == PackageManager.PERMISSION_GRANTED) {
6268 return null;
6269 }
6270 }
6271 }
6272
Dianne Hackbornb424b632010-08-18 15:59:05 -07006273 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6274 if (perms != null) {
6275 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6276 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6277 return null;
6278 }
6279 }
6280 }
6281
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006282 String msg;
6283 if (!cpi.exported) {
6284 msg = "Permission Denial: opening provider " + cpi.name
6285 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6286 + ", uid=" + callingUid + ") that is not exported from uid "
6287 + cpi.applicationInfo.uid;
6288 } else {
6289 msg = "Permission Denial: opening provider " + cpi.name
6290 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6291 + ", uid=" + callingUid + ") requires "
6292 + cpi.readPermission + " or " + cpi.writePermission;
6293 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006294 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 return msg;
6296 }
6297
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006298 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6299 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006300 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006301 for (int i=0; i<r.conProviders.size(); i++) {
6302 ContentProviderConnection conn = r.conProviders.get(i);
6303 if (conn.provider == cpr) {
6304 if (DEBUG_PROVIDER) Slog.v(TAG,
6305 "Adding provider requested by "
6306 + r.processName + " from process "
6307 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6308 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6309 if (stable) {
6310 conn.stableCount++;
6311 conn.numStableIncs++;
6312 } else {
6313 conn.unstableCount++;
6314 conn.numUnstableIncs++;
6315 }
6316 return conn;
6317 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006318 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006319 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6320 if (stable) {
6321 conn.stableCount = 1;
6322 conn.numStableIncs = 1;
6323 } else {
6324 conn.unstableCount = 1;
6325 conn.numUnstableIncs = 1;
6326 }
6327 cpr.connections.add(conn);
6328 r.conProviders.add(conn);
6329 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006330 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006331 cpr.addExternalProcessHandleLocked(externalProcessToken);
6332 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006333 }
6334
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006335 boolean decProviderCountLocked(ContentProviderConnection conn,
6336 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6337 if (conn != null) {
6338 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006339 if (DEBUG_PROVIDER) Slog.v(TAG,
6340 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006341 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006342 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006343 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6344 if (stable) {
6345 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006346 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006347 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006348 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006349 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6350 cpr.connections.remove(conn);
6351 conn.client.conProviders.remove(conn);
6352 return true;
6353 }
6354 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006355 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006356 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006357 return false;
6358 }
6359
Amith Yamasani742a6712011-05-04 14:49:28 -07006360 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006361 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006363 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 ProviderInfo cpi = null;
6365
6366 synchronized(this) {
6367 ProcessRecord r = null;
6368 if (caller != null) {
6369 r = getRecordForAppLocked(caller);
6370 if (r == null) {
6371 throw new SecurityException(
6372 "Unable to find app for caller " + caller
6373 + " (pid=" + Binder.getCallingPid()
6374 + ") when getting content provider " + name);
6375 }
6376 }
6377
6378 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006379 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006380 boolean providerRunning = cpr != null;
6381 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006383 String msg;
6384 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6385 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 }
6387
6388 if (r != null && cpr.canRunHere(r)) {
6389 // This provider has been published or is in the process
6390 // of being published... but it is also allowed to run
6391 // in the caller's process, so don't make a connection
6392 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006393 ContentProviderHolder holder = cpr.newHolder(null);
6394 // don't give caller the provider object, it needs
6395 // to make its own.
6396 holder.provider = null;
6397 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 }
6399
6400 final long origId = Binder.clearCallingIdentity();
6401
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006402 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006404 conn = incProviderCountLocked(r, cpr, token, stable);
6405 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006406 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006407 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006408 // make sure to count it as being accessed and thus
6409 // back up on the LRU list. This is good because
6410 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006411 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006412 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006413 }
6414
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006415 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006416 if (false) {
6417 if (cpr.name.flattenToShortString().equals(
6418 "com.android.providers.calendar/.CalendarProvider2")) {
6419 Slog.v(TAG, "****************** KILLING "
6420 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006421 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006422 }
6423 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006424 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006425 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6426 // NOTE: there is still a race here where a signal could be
6427 // pending on the process even though we managed to update its
6428 // adj level. Not sure what to do about this, but at least
6429 // the race is now smaller.
6430 if (!success) {
6431 // Uh oh... it looks like the provider's process
6432 // has been killed on us. We need to wait for a new
6433 // process to be started, and make sure its death
6434 // doesn't kill our process.
6435 Slog.i(TAG,
6436 "Existing provider " + cpr.name.flattenToShortString()
6437 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006438 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006439 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006440 if (!lastRef) {
6441 // This wasn't the last ref our process had on
6442 // the provider... we have now been killed, bail.
6443 return null;
6444 }
6445 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006446 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 }
6449
6450 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006453 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006454 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006456 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006457 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006458 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 } catch (RemoteException ex) {
6460 }
6461 if (cpi == null) {
6462 return null;
6463 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006464 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6465 cpi.name, cpi.flags);
6466 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006467 userId = 0;
6468 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006469 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006470
Dianne Hackbornb424b632010-08-18 15:59:05 -07006471 String msg;
6472 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6473 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 }
6475
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006476 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006477 && !cpi.processName.equals("system")) {
6478 // If this content provider does not run in the system
6479 // process, and the system is not yet ready to run other
6480 // processes, then fail fast instead of hanging.
6481 throw new IllegalArgumentException(
6482 "Attempt to launch content provider before system ready");
6483 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006484
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006485 // Make sure that the user who owns this provider is started. If not,
6486 // we don't want to allow it to run.
6487 if (mStartedUsers.get(userId) == null) {
6488 Slog.w(TAG, "Unable to launch app "
6489 + cpi.applicationInfo.packageName + "/"
6490 + cpi.applicationInfo.uid + " for provider "
6491 + name + ": user " + userId + " is stopped");
6492 return null;
6493 }
6494
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006495 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006496 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 final boolean firstClass = cpr == null;
6498 if (firstClass) {
6499 try {
6500 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006501 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 getApplicationInfo(
6503 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006504 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006506 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 + cpi.name);
6508 return null;
6509 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006510 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006511 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 } catch (RemoteException ex) {
6513 // pm is in same process, this will never happen.
6514 }
6515 }
6516
6517 if (r != null && cpr.canRunHere(r)) {
6518 // If this is a multiprocess provider, then just return its
6519 // info and allow the caller to instantiate it. Only do
6520 // this if the provider is the same user as the caller's
6521 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006522 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 }
6524
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006525 if (DEBUG_PROVIDER) {
6526 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006527 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006528 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
6530
6531 // This is single process, and our app is now connecting to it.
6532 // See if we are already in the process of launching this
6533 // provider.
6534 final int N = mLaunchingProviders.size();
6535 int i;
6536 for (i=0; i<N; i++) {
6537 if (mLaunchingProviders.get(i) == cpr) {
6538 break;
6539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 }
6541
6542 // If the provider is not already being launched, then get it
6543 // started.
6544 if (i >= N) {
6545 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006546
6547 try {
6548 // Content provider is now in use, its package can't be stopped.
6549 try {
6550 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006551 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006552 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006553 } catch (IllegalArgumentException e) {
6554 Slog.w(TAG, "Failed trying to unstop package "
6555 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006556 }
6557
6558 ProcessRecord proc = startProcessLocked(cpi.processName,
6559 cpr.appInfo, false, 0, "content provider",
6560 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006561 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006562 if (proc == null) {
6563 Slog.w(TAG, "Unable to launch app "
6564 + cpi.applicationInfo.packageName + "/"
6565 + cpi.applicationInfo.uid + " for provider "
6566 + name + ": process is bad");
6567 return null;
6568 }
6569 cpr.launchingApp = proc;
6570 mLaunchingProviders.add(cpr);
6571 } finally {
6572 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006574 }
6575
6576 // Make sure the provider is published (the same provider class
6577 // may be published under multiple names).
6578 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006579 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006581
Amith Yamasani742a6712011-05-04 14:49:28 -07006582 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006583 conn = incProviderCountLocked(r, cpr, token, stable);
6584 if (conn != null) {
6585 conn.waiting = true;
6586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 }
6588 }
6589
6590 // Wait for the provider to be published...
6591 synchronized (cpr) {
6592 while (cpr.provider == null) {
6593 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006594 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 + cpi.applicationInfo.packageName + "/"
6596 + cpi.applicationInfo.uid + " for provider "
6597 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006598 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006599 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 cpi.applicationInfo.packageName,
6601 cpi.applicationInfo.uid, name);
6602 return null;
6603 }
6604 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006605 if (DEBUG_MU) {
6606 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6607 + cpr.launchingApp);
6608 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006609 if (conn != null) {
6610 conn.waiting = true;
6611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 cpr.wait();
6613 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006614 } finally {
6615 if (conn != null) {
6616 conn.waiting = false;
6617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619 }
6620 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006621 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 }
6623
6624 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006625 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006626 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 if (caller == null) {
6628 String msg = "null IApplicationThread when getting content provider "
6629 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006630 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 throw new SecurityException(msg);
6632 }
6633
Dianne Hackborn139748f2012-09-24 11:36:57 -07006634 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006635 false, true, "getContentProvider", null);
6636 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 }
6638
Jeff Sharkey6d515712012-09-20 16:06:08 -07006639 public ContentProviderHolder getContentProviderExternal(
6640 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006641 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6642 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006643 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006644 false, true, "getContentProvider", null);
6645 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006646 }
6647
Dianne Hackborn41203752012-08-31 14:05:51 -07006648 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6649 IBinder token, int userId) {
6650 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 }
6652
6653 /**
6654 * Drop a content provider from a ProcessRecord's bookkeeping
6655 * @param cpr
6656 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006657 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006658 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006660 ContentProviderConnection conn;
6661 try {
6662 conn = (ContentProviderConnection)connection;
6663 } catch (ClassCastException e) {
6664 String msg ="removeContentProvider: " + connection
6665 + " not a ContentProviderConnection";
6666 Slog.w(TAG, msg);
6667 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006669 if (conn == null) {
6670 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006672 if (decProviderCountLocked(conn, null, null, stable)) {
6673 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
6676 }
6677
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006678 public void removeContentProviderExternal(String name, IBinder token) {
6679 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6680 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006681 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006682 }
6683
Dianne Hackborn41203752012-08-31 14:05:51 -07006684 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006686 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 if(cpr == null) {
6688 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006689 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 return;
6691 }
6692
6693 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006694 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006695 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006696 if (localCpr.hasExternalProcessHandles()) {
6697 if (localCpr.removeExternalProcessHandleLocked(token)) {
6698 updateOomAdjLocked();
6699 } else {
6700 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6701 + " with no external reference for token: "
6702 + token + ".");
6703 }
6704 } else {
6705 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6706 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 }
6709 }
6710
6711 public final void publishContentProviders(IApplicationThread caller,
6712 List<ContentProviderHolder> providers) {
6713 if (providers == null) {
6714 return;
6715 }
6716
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006717 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006718 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006720 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006721 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 if (r == null) {
6723 throw new SecurityException(
6724 "Unable to find app for caller " + caller
6725 + " (pid=" + Binder.getCallingPid()
6726 + ") when publishing content providers");
6727 }
6728
6729 final long origId = Binder.clearCallingIdentity();
6730
6731 final int N = providers.size();
6732 for (int i=0; i<N; i++) {
6733 ContentProviderHolder src = providers.get(i);
6734 if (src == null || src.info == null || src.provider == null) {
6735 continue;
6736 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006737 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006738 if (DEBUG_MU)
6739 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006741 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006742 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 String names[] = dst.info.authority.split(";");
6744 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006745 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 }
6747
6748 int NL = mLaunchingProviders.size();
6749 int j;
6750 for (j=0; j<NL; j++) {
6751 if (mLaunchingProviders.get(j) == dst) {
6752 mLaunchingProviders.remove(j);
6753 j--;
6754 NL--;
6755 }
6756 }
6757 synchronized (dst) {
6758 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006759 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 dst.notifyAll();
6761 }
6762 updateOomAdjLocked(r);
6763 }
6764 }
6765
6766 Binder.restoreCallingIdentity(origId);
6767 }
6768 }
6769
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006770 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6771 ContentProviderConnection conn;
6772 try {
6773 conn = (ContentProviderConnection)connection;
6774 } catch (ClassCastException e) {
6775 String msg ="refContentProvider: " + connection
6776 + " not a ContentProviderConnection";
6777 Slog.w(TAG, msg);
6778 throw new IllegalArgumentException(msg);
6779 }
6780 if (conn == null) {
6781 throw new NullPointerException("connection is null");
6782 }
6783
6784 synchronized (this) {
6785 if (stable > 0) {
6786 conn.numStableIncs += stable;
6787 }
6788 stable = conn.stableCount + stable;
6789 if (stable < 0) {
6790 throw new IllegalStateException("stableCount < 0: " + stable);
6791 }
6792
6793 if (unstable > 0) {
6794 conn.numUnstableIncs += unstable;
6795 }
6796 unstable = conn.unstableCount + unstable;
6797 if (unstable < 0) {
6798 throw new IllegalStateException("unstableCount < 0: " + unstable);
6799 }
6800
6801 if ((stable+unstable) <= 0) {
6802 throw new IllegalStateException("ref counts can't go to zero here: stable="
6803 + stable + " unstable=" + unstable);
6804 }
6805 conn.stableCount = stable;
6806 conn.unstableCount = unstable;
6807 return !conn.dead;
6808 }
6809 }
6810
6811 public void unstableProviderDied(IBinder connection) {
6812 ContentProviderConnection conn;
6813 try {
6814 conn = (ContentProviderConnection)connection;
6815 } catch (ClassCastException e) {
6816 String msg ="refContentProvider: " + connection
6817 + " not a ContentProviderConnection";
6818 Slog.w(TAG, msg);
6819 throw new IllegalArgumentException(msg);
6820 }
6821 if (conn == null) {
6822 throw new NullPointerException("connection is null");
6823 }
6824
6825 // Safely retrieve the content provider associated with the connection.
6826 IContentProvider provider;
6827 synchronized (this) {
6828 provider = conn.provider.provider;
6829 }
6830
6831 if (provider == null) {
6832 // Um, yeah, we're way ahead of you.
6833 return;
6834 }
6835
6836 // Make sure the caller is being honest with us.
6837 if (provider.asBinder().pingBinder()) {
6838 // Er, no, still looks good to us.
6839 synchronized (this) {
6840 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6841 + " says " + conn + " died, but we don't agree");
6842 return;
6843 }
6844 }
6845
6846 // Well look at that! It's dead!
6847 synchronized (this) {
6848 if (conn.provider.provider != provider) {
6849 // But something changed... good enough.
6850 return;
6851 }
6852
6853 ProcessRecord proc = conn.provider.proc;
6854 if (proc == null || proc.thread == null) {
6855 // Seems like the process is already cleaned up.
6856 return;
6857 }
6858
6859 // As far as we're concerned, this is just like receiving a
6860 // death notification... just a bit prematurely.
6861 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6862 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006863 final long ident = Binder.clearCallingIdentity();
6864 try {
6865 appDiedLocked(proc, proc.pid, proc.thread);
6866 } finally {
6867 Binder.restoreCallingIdentity(ident);
6868 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006869 }
6870 }
6871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006873 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006874 synchronized (mSelf) {
6875 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6876 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006877 if (providers != null) {
6878 for (int i=providers.size()-1; i>=0; i--) {
6879 ProviderInfo pi = (ProviderInfo)providers.get(i);
6880 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6881 Slog.w(TAG, "Not installing system proc provider " + pi.name
6882 + ": not system .apk");
6883 providers.remove(i);
6884 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006885 }
6886 }
6887 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006888 if (providers != null) {
6889 mSystemThread.installSystemProviders(providers);
6890 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006891
6892 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006893
6894 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 }
6896
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006897 /**
6898 * Allows app to retrieve the MIME type of a URI without having permission
6899 * to access its content provider.
6900 *
6901 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6902 *
6903 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6904 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6905 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006906 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006907 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006908 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006909 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006910 final String name = uri.getAuthority();
6911 final long ident = Binder.clearCallingIdentity();
6912 ContentProviderHolder holder = null;
6913
6914 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006915 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006916 if (holder != null) {
6917 return holder.provider.getType(uri);
6918 }
6919 } catch (RemoteException e) {
6920 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6921 return null;
6922 } finally {
6923 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006924 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006925 }
6926 Binder.restoreCallingIdentity(ident);
6927 }
6928
6929 return null;
6930 }
6931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 // =========================================================
6933 // GLOBAL MANAGEMENT
6934 // =========================================================
6935
6936 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006937 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006938 String proc = customProcess != null ? customProcess : info.processName;
6939 BatteryStatsImpl.Uid.Proc ps = null;
6940 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006941 int uid = info.uid;
6942 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006943 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006944 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6945 uid = 0;
6946 while (true) {
6947 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6948 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6949 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6950 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006951 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006952 mNextIsolatedProcessUid++;
6953 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6954 // No process for this uid, use it.
6955 break;
6956 }
6957 stepsLeft--;
6958 if (stepsLeft <= 0) {
6959 return null;
6960 }
6961 }
6962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 synchronized (stats) {
6964 ps = stats.getProcessStatsLocked(info.uid, proc);
6965 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006966 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 }
6968
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006969 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6970 ProcessRecord app;
6971 if (!isolated) {
6972 app = getProcessRecordLocked(info.processName, info.uid);
6973 } else {
6974 app = null;
6975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006976
6977 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006978 app = newProcessRecordLocked(null, info, null, isolated);
6979 mProcessNames.put(info.processName, app.uid, app);
6980 if (isolated) {
6981 mIsolatedProcesses.put(app.uid, app);
6982 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006983 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006984 }
6985
Dianne Hackborne7f97212011-02-24 14:40:20 -08006986 // This package really, really can not be stopped.
6987 try {
6988 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006989 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006990 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006991 } catch (IllegalArgumentException e) {
6992 Slog.w(TAG, "Failed trying to unstop package "
6993 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006994 }
6995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6997 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6998 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006999 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007000 }
7001 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7002 mPersistentStartingProcesses.add(app);
7003 startProcessLocked(app, "added application", app.processName);
7004 }
7005
7006 return app;
7007 }
7008
7009 public void unhandledBack() {
7010 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7011 "unhandledBack()");
7012
7013 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007014 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007015 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016 TAG, "Performing unhandledBack(): stack size = " + count);
7017 if (count > 1) {
7018 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007019 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007020 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 Binder.restoreCallingIdentity(origId);
7022 }
7023 }
7024 }
7025
7026 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007027 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007028 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007030 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 ParcelFileDescriptor pfd = null;
7032 if (cph != null) {
7033 // We record the binder invoker's uid in thread-local storage before
7034 // going to the content provider to open the file. Later, in the code
7035 // that handles all permissions checks, we look for this uid and use
7036 // that rather than the Activity Manager's own uid. The effect is that
7037 // we do the check against the caller's permissions even though it looks
7038 // to the content provider like the Activity Manager itself is making
7039 // the request.
7040 sCallerIdentity.set(new Identity(
7041 Binder.getCallingPid(), Binder.getCallingUid()));
7042 try {
7043 pfd = cph.provider.openFile(uri, "r");
7044 } catch (FileNotFoundException e) {
7045 // do nothing; pfd will be returned null
7046 } finally {
7047 // Ensure that whatever happens, we clean up the identity state
7048 sCallerIdentity.remove();
7049 }
7050
7051 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007052 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007054 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 }
7056 return pfd;
7057 }
7058
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007059 // Actually is sleeping or shutting down or whatever else in the future
7060 // is an inactive state.
7061 public boolean isSleeping() {
7062 return mSleeping || mShuttingDown;
7063 }
7064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007066 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7067 != PackageManager.PERMISSION_GRANTED) {
7068 throw new SecurityException("Requires permission "
7069 + android.Manifest.permission.DEVICE_POWER);
7070 }
7071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007073 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007074 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007076 if (!mSleeping) {
7077 mSleeping = true;
7078 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007079
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007080 // Initialize the wake times of all processes.
7081 checkExcessivePowerUsageLocked(false);
7082 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7083 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7084 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 }
7087 }
7088
Dianne Hackborn55280a92009-05-07 15:53:46 -07007089 public boolean shutdown(int timeout) {
7090 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7091 != PackageManager.PERMISSION_GRANTED) {
7092 throw new SecurityException("Requires permission "
7093 + android.Manifest.permission.SHUTDOWN);
7094 }
7095
7096 boolean timedout = false;
7097
7098 synchronized(this) {
7099 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007100 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007101
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007102 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007103 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007104 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007105 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007106 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007107 long delay = endTime - System.currentTimeMillis();
7108 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007109 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007110 timedout = true;
7111 break;
7112 }
7113 try {
7114 this.wait();
7115 } catch (InterruptedException e) {
7116 }
7117 }
7118 }
7119 }
7120
7121 mUsageStatsService.shutdown();
7122 mBatteryStatsService.shutdown();
7123
7124 return timedout;
7125 }
7126
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007127 public final void activitySlept(IBinder token) {
7128 if (localLOGV) Slog.v(
7129 TAG, "Activity slept: token=" + token);
7130
7131 ActivityRecord r = null;
7132
7133 final long origId = Binder.clearCallingIdentity();
7134
7135 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007136 r = mMainStack.isInStackLocked(token);
7137 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007138 mMainStack.activitySleptLocked(r);
7139 }
7140 }
7141
7142 Binder.restoreCallingIdentity(origId);
7143 }
7144
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007145 private void comeOutOfSleepIfNeededLocked() {
7146 if (!mWentToSleep && !mLockScreenShown) {
7147 if (mSleeping) {
7148 mSleeping = false;
7149 mMainStack.awakeFromSleepingLocked();
7150 mMainStack.resumeTopActivityLocked(null);
7151 }
7152 }
7153 }
7154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007156 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7157 != PackageManager.PERMISSION_GRANTED) {
7158 throw new SecurityException("Requires permission "
7159 + android.Manifest.permission.DEVICE_POWER);
7160 }
7161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007162 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007163 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007164 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007165 comeOutOfSleepIfNeededLocked();
7166 }
7167 }
7168
Jeff Brownc042ee22012-05-08 13:03:42 -07007169 private void updateEventDispatchingLocked() {
7170 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7171 }
7172
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007173 public void setLockScreenShown(boolean shown) {
7174 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7175 != PackageManager.PERMISSION_GRANTED) {
7176 throw new SecurityException("Requires permission "
7177 + android.Manifest.permission.DEVICE_POWER);
7178 }
7179
7180 synchronized(this) {
7181 mLockScreenShown = shown;
7182 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 }
7184 }
7185
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007186 public void stopAppSwitches() {
7187 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7188 != PackageManager.PERMISSION_GRANTED) {
7189 throw new SecurityException("Requires permission "
7190 + android.Manifest.permission.STOP_APP_SWITCHES);
7191 }
7192
7193 synchronized(this) {
7194 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7195 + APP_SWITCH_DELAY_TIME;
7196 mDidAppSwitch = false;
7197 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7198 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7199 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7200 }
7201 }
7202
7203 public void resumeAppSwitches() {
7204 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7205 != PackageManager.PERMISSION_GRANTED) {
7206 throw new SecurityException("Requires permission "
7207 + android.Manifest.permission.STOP_APP_SWITCHES);
7208 }
7209
7210 synchronized(this) {
7211 // Note that we don't execute any pending app switches... we will
7212 // let those wait until either the timeout, or the next start
7213 // activity request.
7214 mAppSwitchesAllowedTime = 0;
7215 }
7216 }
7217
7218 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7219 String name) {
7220 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7221 return true;
7222 }
7223
7224 final int perm = checkComponentPermission(
7225 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007226 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007227 if (perm == PackageManager.PERMISSION_GRANTED) {
7228 return true;
7229 }
7230
Joe Onorato8a9b2202010-02-26 18:56:32 -08007231 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007232 return false;
7233 }
7234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 public void setDebugApp(String packageName, boolean waitForDebugger,
7236 boolean persistent) {
7237 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7238 "setDebugApp()");
7239
7240 // Note that this is not really thread safe if there are multiple
7241 // callers into it at the same time, but that's not a situation we
7242 // care about.
7243 if (persistent) {
7244 final ContentResolver resolver = mContext.getContentResolver();
7245 Settings.System.putString(
7246 resolver, Settings.System.DEBUG_APP,
7247 packageName);
7248 Settings.System.putInt(
7249 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7250 waitForDebugger ? 1 : 0);
7251 }
7252
7253 synchronized (this) {
7254 if (!persistent) {
7255 mOrigDebugApp = mDebugApp;
7256 mOrigWaitForDebugger = mWaitForDebugger;
7257 }
7258 mDebugApp = packageName;
7259 mWaitForDebugger = waitForDebugger;
7260 mDebugTransient = !persistent;
7261 if (packageName != null) {
7262 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007263 forceStopPackageLocked(packageName, -1, false, false, true, true,
7264 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 Binder.restoreCallingIdentity(origId);
7266 }
7267 }
7268 }
7269
Siva Velusamy92a8b222012-03-09 16:24:04 -08007270 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7271 synchronized (this) {
7272 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7273 if (!isDebuggable) {
7274 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7275 throw new SecurityException("Process not debuggable: " + app.packageName);
7276 }
7277 }
7278
7279 mOpenGlTraceApp = processName;
7280 }
7281 }
7282
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007283 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7284 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7285 synchronized (this) {
7286 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7287 if (!isDebuggable) {
7288 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7289 throw new SecurityException("Process not debuggable: " + app.packageName);
7290 }
7291 }
7292 mProfileApp = processName;
7293 mProfileFile = profileFile;
7294 if (mProfileFd != null) {
7295 try {
7296 mProfileFd.close();
7297 } catch (IOException e) {
7298 }
7299 mProfileFd = null;
7300 }
7301 mProfileFd = profileFd;
7302 mProfileType = 0;
7303 mAutoStopProfiler = autoStopProfiler;
7304 }
7305 }
7306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 public void setAlwaysFinish(boolean enabled) {
7308 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7309 "setAlwaysFinish()");
7310
7311 Settings.System.putInt(
7312 mContext.getContentResolver(),
7313 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7314
7315 synchronized (this) {
7316 mAlwaysFinishActivities = enabled;
7317 }
7318 }
7319
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007320 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007322 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007323 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007324 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 }
7326 }
7327
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007328 public boolean isUserAMonkey() {
7329 // For now the fact that there is a controller implies
7330 // we have a monkey.
7331 synchronized (this) {
7332 return mController != null;
7333 }
7334 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007335
7336 public void requestBugReport() {
7337 // No permission check because this can't do anything harmful --
7338 // it will just eventually cause the user to be presented with
7339 // a UI to select where the bug report goes.
7340 SystemProperties.set("ctl.start", "bugreport");
7341 }
7342
Jeff Sharkeya4620792011-05-20 15:29:23 -07007343 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007344 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7345 "registerProcessObserver()");
7346 synchronized (this) {
7347 mProcessObservers.register(observer);
7348 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007349 }
7350
7351 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007352 synchronized (this) {
7353 mProcessObservers.unregister(observer);
7354 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007355 }
7356
Daniel Sandler69a48172010-06-23 16:29:36 -04007357 public void setImmersive(IBinder token, boolean immersive) {
7358 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007359 ActivityRecord r = mMainStack.isInStackLocked(token);
7360 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007361 throw new IllegalArgumentException();
7362 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007363 r.immersive = immersive;
7364 }
7365 }
7366
7367 public boolean isImmersive(IBinder token) {
7368 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007369 ActivityRecord r = mMainStack.isInStackLocked(token);
7370 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007371 throw new IllegalArgumentException();
7372 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007373 return r.immersive;
7374 }
7375 }
7376
7377 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007378 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007379 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007380 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007381 return (r != null) ? r.immersive : false;
7382 }
7383 }
7384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007385 public final void enterSafeMode() {
7386 synchronized(this) {
7387 // It only makes sense to do this before the system is ready
7388 // and started launching other packages.
7389 if (!mSystemReady) {
7390 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007391 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 } catch (RemoteException e) {
7393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007394 }
7395 }
7396 }
7397
Jeff Brownb09abc12011-01-13 21:08:27 -08007398 public final void showSafeModeOverlay() {
7399 View v = LayoutInflater.from(mContext).inflate(
7400 com.android.internal.R.layout.safe_mode, null);
7401 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7402 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7403 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7404 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007405 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007406 lp.format = v.getBackground().getOpacity();
7407 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7408 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7409 ((WindowManager)mContext.getSystemService(
7410 Context.WINDOW_SERVICE)).addView(v, lp);
7411 }
7412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 public void noteWakeupAlarm(IIntentSender sender) {
7414 if (!(sender instanceof PendingIntentRecord)) {
7415 return;
7416 }
7417 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7418 synchronized (stats) {
7419 if (mBatteryStatsService.isOnBattery()) {
7420 mBatteryStatsService.enforceCallingPermission();
7421 PendingIntentRecord rec = (PendingIntentRecord)sender;
7422 int MY_UID = Binder.getCallingUid();
7423 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7424 BatteryStatsImpl.Uid.Pkg pkg =
7425 stats.getPackageStatsLocked(uid, rec.key.packageName);
7426 pkg.incWakeupsLocked();
7427 }
7428 }
7429 }
7430
Dianne Hackborn64825172011-03-02 21:32:58 -08007431 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007433 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007435 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007436 // XXX Note: don't acquire main activity lock here, because the window
7437 // manager calls in with its locks held.
7438
7439 boolean killed = false;
7440 synchronized (mPidsSelfLocked) {
7441 int[] types = new int[pids.length];
7442 int worstType = 0;
7443 for (int i=0; i<pids.length; i++) {
7444 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7445 if (proc != null) {
7446 int type = proc.setAdj;
7447 types[i] = type;
7448 if (type > worstType) {
7449 worstType = type;
7450 }
7451 }
7452 }
7453
Dianne Hackborn64825172011-03-02 21:32:58 -08007454 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007456 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7457 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007458 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007460
7461 // If this is not a secure call, don't let it kill processes that
7462 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007463 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7464 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007465 }
7466
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007467 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 for (int i=0; i<pids.length; i++) {
7469 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7470 if (proc == null) {
7471 continue;
7472 }
7473 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007474 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007475 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007476 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007477 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007479 proc.killedBackground = true;
7480 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007481 }
7482 }
7483 }
7484 return killed;
7485 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007486
7487 @Override
7488 public boolean killProcessesBelowForeground(String reason) {
7489 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7490 throw new SecurityException("killProcessesBelowForeground() only available to system");
7491 }
7492
7493 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7494 }
7495
7496 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7497 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7498 throw new SecurityException("killProcessesBelowAdj() only available to system");
7499 }
7500
7501 boolean killed = false;
7502 synchronized (mPidsSelfLocked) {
7503 final int size = mPidsSelfLocked.size();
7504 for (int i = 0; i < size; i++) {
7505 final int pid = mPidsSelfLocked.keyAt(i);
7506 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7507 if (proc == null) continue;
7508
7509 final int adj = proc.setAdj;
7510 if (adj > belowAdj && !proc.killedBackground) {
7511 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007512 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7513 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007514 killed = true;
7515 proc.killedBackground = true;
7516 Process.killProcessQuiet(pid);
7517 }
7518 }
7519 }
7520 return killed;
7521 }
7522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 public final void startRunning(String pkg, String cls, String action,
7524 String data) {
7525 synchronized(this) {
7526 if (mStartRunning) {
7527 return;
7528 }
7529 mStartRunning = true;
7530 mTopComponent = pkg != null && cls != null
7531 ? new ComponentName(pkg, cls) : null;
7532 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7533 mTopData = data;
7534 if (!mSystemReady) {
7535 return;
7536 }
7537 }
7538
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007539 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 }
7541
7542 private void retrieveSettings() {
7543 final ContentResolver resolver = mContext.getContentResolver();
7544 String debugApp = Settings.System.getString(
7545 resolver, Settings.System.DEBUG_APP);
7546 boolean waitForDebugger = Settings.System.getInt(
7547 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7548 boolean alwaysFinishActivities = Settings.System.getInt(
7549 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7550
7551 Configuration configuration = new Configuration();
7552 Settings.System.getConfiguration(resolver, configuration);
7553
7554 synchronized (this) {
7555 mDebugApp = mOrigDebugApp = debugApp;
7556 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7557 mAlwaysFinishActivities = alwaysFinishActivities;
7558 // This happens before any activities are started, so we can
7559 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007560 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007561 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 }
7563 }
7564
7565 public boolean testIsSystemReady() {
7566 // no need to synchronize(this) just to read & return the value
7567 return mSystemReady;
7568 }
7569
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007570 private static File getCalledPreBootReceiversFile() {
7571 File dataDir = Environment.getDataDirectory();
7572 File systemDir = new File(dataDir, "system");
7573 File fname = new File(systemDir, "called_pre_boots.dat");
7574 return fname;
7575 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007576
7577 static final int LAST_DONE_VERSION = 10000;
7578
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007579 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7580 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7581 File file = getCalledPreBootReceiversFile();
7582 FileInputStream fis = null;
7583 try {
7584 fis = new FileInputStream(file);
7585 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007586 int fvers = dis.readInt();
7587 if (fvers == LAST_DONE_VERSION) {
7588 String vers = dis.readUTF();
7589 String codename = dis.readUTF();
7590 String build = dis.readUTF();
7591 if (android.os.Build.VERSION.RELEASE.equals(vers)
7592 && android.os.Build.VERSION.CODENAME.equals(codename)
7593 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7594 int num = dis.readInt();
7595 while (num > 0) {
7596 num--;
7597 String pkg = dis.readUTF();
7598 String cls = dis.readUTF();
7599 lastDoneReceivers.add(new ComponentName(pkg, cls));
7600 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007601 }
7602 }
7603 } catch (FileNotFoundException e) {
7604 } catch (IOException e) {
7605 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7606 } finally {
7607 if (fis != null) {
7608 try {
7609 fis.close();
7610 } catch (IOException e) {
7611 }
7612 }
7613 }
7614 return lastDoneReceivers;
7615 }
7616
7617 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7618 File file = getCalledPreBootReceiversFile();
7619 FileOutputStream fos = null;
7620 DataOutputStream dos = null;
7621 try {
7622 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7623 fos = new FileOutputStream(file);
7624 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007625 dos.writeInt(LAST_DONE_VERSION);
7626 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007627 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007628 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007629 dos.writeInt(list.size());
7630 for (int i=0; i<list.size(); i++) {
7631 dos.writeUTF(list.get(i).getPackageName());
7632 dos.writeUTF(list.get(i).getClassName());
7633 }
7634 } catch (IOException e) {
7635 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7636 file.delete();
7637 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007638 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007639 if (dos != null) {
7640 try {
7641 dos.close();
7642 } catch (IOException e) {
7643 // TODO Auto-generated catch block
7644 e.printStackTrace();
7645 }
7646 }
7647 }
7648 }
7649
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007650 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 synchronized(this) {
7652 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007653 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 return;
7655 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007656
7657 // Check to see if there are any update receivers to run.
7658 if (!mDidUpdate) {
7659 if (mWaitingUpdate) {
7660 return;
7661 }
7662 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7663 List<ResolveInfo> ris = null;
7664 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007665 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007666 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007667 } catch (RemoteException e) {
7668 }
7669 if (ris != null) {
7670 for (int i=ris.size()-1; i>=0; i--) {
7671 if ((ris.get(i).activityInfo.applicationInfo.flags
7672 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7673 ris.remove(i);
7674 }
7675 }
7676 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007677
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007678 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007679
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007680 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007681 for (int i=0; i<ris.size(); i++) {
7682 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007683 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7684 if (lastDoneReceivers.contains(comp)) {
7685 ris.remove(i);
7686 i--;
7687 }
7688 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007689
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007690 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007691 for (int i=0; i<ris.size(); i++) {
7692 ActivityInfo ai = ris.get(i).activityInfo;
7693 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7694 doneReceivers.add(comp);
7695 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007696 for (int j=0; j<users.length; j++) {
7697 IIntentReceiver finisher = null;
7698 if (i == ris.size()-1 && j == users.length-1) {
7699 finisher = new IIntentReceiver.Stub() {
7700 public void performReceive(Intent intent, int resultCode,
7701 String data, Bundle extras, boolean ordered,
7702 boolean sticky, int sendingUser) {
7703 // The raw IIntentReceiver interface is called
7704 // with the AM lock held, so redispatch to
7705 // execute our code without the lock.
7706 mHandler.post(new Runnable() {
7707 public void run() {
7708 synchronized (ActivityManagerService.this) {
7709 mDidUpdate = true;
7710 }
7711 writeLastDonePreBootReceivers(doneReceivers);
7712 showBootMessage(mContext.getText(
7713 R.string.android_upgrading_complete),
7714 false);
7715 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007716 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007717 });
7718 }
7719 };
7720 }
7721 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7722 + " for user " + users[j]);
7723 broadcastIntentLocked(null, null, intent, null, finisher,
7724 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7725 users[j]);
7726 if (finisher != null) {
7727 mWaitingUpdate = true;
7728 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007729 }
7730 }
7731 }
7732 if (mWaitingUpdate) {
7733 return;
7734 }
7735 mDidUpdate = true;
7736 }
7737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 mSystemReady = true;
7739 if (!mStartRunning) {
7740 return;
7741 }
7742 }
7743
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007744 ArrayList<ProcessRecord> procsToKill = null;
7745 synchronized(mPidsSelfLocked) {
7746 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7747 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7748 if (!isAllowedWhileBooting(proc.info)){
7749 if (procsToKill == null) {
7750 procsToKill = new ArrayList<ProcessRecord>();
7751 }
7752 procsToKill.add(proc);
7753 }
7754 }
7755 }
7756
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007757 synchronized(this) {
7758 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007759 for (int i=procsToKill.size()-1; i>=0; i--) {
7760 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007761 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007762 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007763 }
7764 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007765
7766 // Now that we have cleaned up any update processes, we
7767 // are ready to start launching real processes and know that
7768 // we won't trample on them any more.
7769 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007770 }
7771
Joe Onorato8a9b2202010-02-26 18:56:32 -08007772 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007773 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 SystemClock.uptimeMillis());
7775
7776 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007777 // Make sure we have no pre-ready processes sitting around.
7778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7780 ResolveInfo ri = mContext.getPackageManager()
7781 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007782 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 CharSequence errorMsg = null;
7784 if (ri != null) {
7785 ActivityInfo ai = ri.activityInfo;
7786 ApplicationInfo app = ai.applicationInfo;
7787 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7788 mTopAction = Intent.ACTION_FACTORY_TEST;
7789 mTopData = null;
7790 mTopComponent = new ComponentName(app.packageName,
7791 ai.name);
7792 } else {
7793 errorMsg = mContext.getResources().getText(
7794 com.android.internal.R.string.factorytest_not_system);
7795 }
7796 } else {
7797 errorMsg = mContext.getResources().getText(
7798 com.android.internal.R.string.factorytest_no_action);
7799 }
7800 if (errorMsg != null) {
7801 mTopAction = null;
7802 mTopData = null;
7803 mTopComponent = null;
7804 Message msg = Message.obtain();
7805 msg.what = SHOW_FACTORY_ERROR_MSG;
7806 msg.getData().putCharSequence("msg", errorMsg);
7807 mHandler.sendMessage(msg);
7808 }
7809 }
7810 }
7811
7812 retrieveSettings();
7813
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007814 if (goingCallback != null) goingCallback.run();
7815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 synchronized (this) {
7817 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7818 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007819 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007820 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 if (apps != null) {
7822 int N = apps.size();
7823 int i;
7824 for (i=0; i<N; i++) {
7825 ApplicationInfo info
7826 = (ApplicationInfo)apps.get(i);
7827 if (info != null &&
7828 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007829 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 }
7831 }
7832 }
7833 } catch (RemoteException ex) {
7834 // pm is in same process, this will never happen.
7835 }
7836 }
7837
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007838 // Start up initial activity.
7839 mBooting = true;
7840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007842 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 Message msg = Message.obtain();
7844 msg.what = SHOW_UID_ERROR_MSG;
7845 mHandler.sendMessage(msg);
7846 }
7847 } catch (RemoteException e) {
7848 }
7849
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007850 long ident = Binder.clearCallingIdentity();
7851 try {
7852 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007853 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7854 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007855 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7856 broadcastIntentLocked(null, null, intent,
7857 null, null, 0, null, null, null,
7858 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
7859 } finally {
7860 Binder.restoreCallingIdentity(ident);
7861 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007862 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007863 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
7865 }
7866
Dan Egnorb7f03672009-12-09 16:22:32 -08007867 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007868 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007870 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007871 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 startAppProblemLocked(app);
7873 app.stopFreezingAllLocked();
7874 return handleAppCrashLocked(app);
7875 }
7876
Dan Egnorb7f03672009-12-09 16:22:32 -08007877 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007878 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007880 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007881 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7882 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 startAppProblemLocked(app);
7884 app.stopFreezingAllLocked();
7885 }
7886
7887 /**
7888 * Generate a process error record, suitable for attachment to a ProcessRecord.
7889 *
7890 * @param app The ProcessRecord in which the error occurred.
7891 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7892 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007893 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 * @param shortMsg Short message describing the crash.
7895 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007896 * @param stackTrace Full crash stack trace, may be null.
7897 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 * @return Returns a fully-formed AppErrorStateInfo record.
7899 */
7900 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007901 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 report.condition = condition;
7905 report.processName = app.processName;
7906 report.pid = app.pid;
7907 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007908 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 report.shortMsg = shortMsg;
7910 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007911 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007912
7913 return report;
7914 }
7915
Dan Egnor42471dd2010-01-07 17:25:22 -08007916 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 synchronized (this) {
7918 app.crashing = false;
7919 app.crashingReport = null;
7920 app.notResponding = false;
7921 app.notRespondingReport = null;
7922 if (app.anrDialog == fromDialog) {
7923 app.anrDialog = null;
7924 }
7925 if (app.waitDialog == fromDialog) {
7926 app.waitDialog = null;
7927 }
7928 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007929 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007930 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007931 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07007932 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007933 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 }
7936 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007937
Dan Egnorb7f03672009-12-09 16:22:32 -08007938 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007939 if (mHeadless) {
7940 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7941 return false;
7942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 long now = SystemClock.uptimeMillis();
7944
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007945 Long crashTime;
7946 if (!app.isolated) {
7947 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7948 } else {
7949 crashTime = null;
7950 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007951 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007953 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007955 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007956 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007957 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7958 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007960 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007962 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7963 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 }
7965 }
7966 if (!app.persistent) {
7967 // We don't want to start this process again until the user
7968 // explicitly does so... but for persistent process, we really
7969 // need to keep it running. If a persistent process is actually
7970 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007971 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007973 if (!app.isolated) {
7974 // XXX We don't have a way to mark isolated processes
7975 // as bad, since they don't have a peristent identity.
7976 mBadProcesses.put(app.info.processName, app.uid, now);
7977 mProcessCrashTimes.remove(app.info.processName, app.uid);
7978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007981 // Don't let services in this process be restarted and potentially
7982 // annoy the user repeatedly. Unless it is persistent, since those
7983 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007984 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007985 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 return false;
7987 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007988 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007989 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007990 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007991 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007992 // If the top running activity is from this crashing
7993 // process, then terminate it to avoid getting in a loop.
7994 Slog.w(TAG, " Force finishing activity "
7995 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007996 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007997 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007998 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08007999 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008000 // stopped, to avoid a situation where one will get
8001 // re-start our crashing activity once it gets resumed again.
8002 index--;
8003 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008004 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008005 if (r.state == ActivityState.RESUMED
8006 || r.state == ActivityState.PAUSING
8007 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008008 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008009 Slog.w(TAG, " Force finishing activity "
8010 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008011 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008012 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008013 }
8014 }
8015 }
8016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 }
8018
8019 // Bump up the crash count of any services currently running in the proc.
8020 if (app.services.size() != 0) {
8021 // Any services running in the application need to be placed
8022 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008023 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008025 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 sr.crashCount++;
8027 }
8028 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008029
8030 // If the crashing process is what we consider to be the "home process" and it has been
8031 // replaced by a third-party app, clear the package preferred activities from packages
8032 // with a home activity running in the process to prevent a repeatedly crashing app
8033 // from blocking the user to manually clear the list.
8034 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8035 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8036 Iterator it = mHomeProcess.activities.iterator();
8037 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008038 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008039 if (r.isHomeActivity) {
8040 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8041 try {
8042 ActivityThread.getPackageManager()
8043 .clearPackagePreferredActivities(r.packageName);
8044 } catch (RemoteException c) {
8045 // pm is in same process, this will never happen.
8046 }
8047 }
8048 }
8049 }
8050
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008051 if (!app.isolated) {
8052 // XXX Can't keep track of crash times for isolated processes,
8053 // because they don't have a perisistent identity.
8054 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8055 }
8056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 return true;
8058 }
8059
8060 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008061 if (app.userId == mCurrentUserId) {
8062 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8063 mContext, app.info.packageName, app.info.flags);
8064 } else {
8065 // If this app is not running under the current user, then we
8066 // can't give it a report button because that would require
8067 // launching the report UI under a different user.
8068 app.errorReportReceiver = null;
8069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 skipCurrentReceiverLocked(app);
8071 }
8072
8073 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008074 for (BroadcastQueue queue : mBroadcastQueues) {
8075 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 }
8077 }
8078
Dan Egnor60d87622009-12-16 16:32:58 -08008079 /**
8080 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8081 * The application process will exit immediately after this call returns.
8082 * @param app object of the crashing app, null for the system server
8083 * @param crashInfo describing the exception
8084 */
8085 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008086 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008087 final String processName = app == null ? "system_server"
8088 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008089
8090 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008091 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008092 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008093 crashInfo.exceptionClassName,
8094 crashInfo.exceptionMessage,
8095 crashInfo.throwFileName,
8096 crashInfo.throwLineNumber);
8097
Jeff Sharkeya353d262011-10-28 11:12:06 -07008098 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008099
8100 crashApplication(r, crashInfo);
8101 }
8102
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008103 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008104 IBinder app,
8105 int violationMask,
8106 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008107 ProcessRecord r = findAppProcess(app, "StrictMode");
8108 if (r == null) {
8109 return;
8110 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008111
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008112 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008113 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008114 boolean logIt = true;
8115 synchronized (mAlreadyLoggedViolatedStacks) {
8116 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8117 logIt = false;
8118 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008119 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008120 // the relative pain numbers, without logging all
8121 // the stack traces repeatedly. We'd want to do
8122 // likewise in the client code, which also does
8123 // dup suppression, before the Binder call.
8124 } else {
8125 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8126 mAlreadyLoggedViolatedStacks.clear();
8127 }
8128 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8129 }
8130 }
8131 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008132 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008133 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008134 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008135
8136 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8137 AppErrorResult result = new AppErrorResult();
8138 synchronized (this) {
8139 final long origId = Binder.clearCallingIdentity();
8140
8141 Message msg = Message.obtain();
8142 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8143 HashMap<String, Object> data = new HashMap<String, Object>();
8144 data.put("result", result);
8145 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008146 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008147 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008148 msg.obj = data;
8149 mHandler.sendMessage(msg);
8150
8151 Binder.restoreCallingIdentity(origId);
8152 }
8153 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008154 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008155 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008156 }
8157
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008158 // Depending on the policy in effect, there could be a bunch of
8159 // these in quick succession so we try to batch these together to
8160 // minimize disk writes, number of dropbox entries, and maximize
8161 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008162 private void logStrictModeViolationToDropBox(
8163 ProcessRecord process,
8164 StrictMode.ViolationInfo info) {
8165 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008166 return;
8167 }
8168 final boolean isSystemApp = process == null ||
8169 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8170 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008171 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008172 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8173 final DropBoxManager dbox = (DropBoxManager)
8174 mContext.getSystemService(Context.DROPBOX_SERVICE);
8175
8176 // Exit early if the dropbox isn't configured to accept this report type.
8177 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8178
8179 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008180 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008181 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8182 synchronized (sb) {
8183 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008184 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008185 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8186 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008187 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8188 if (info.violationNumThisLoop != 0) {
8189 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8190 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008191 if (info.numAnimationsRunning != 0) {
8192 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8193 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008194 if (info.broadcastIntentAction != null) {
8195 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8196 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008197 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008198 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008199 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008200 if (info.numInstances != -1) {
8201 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8202 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008203 if (info.tags != null) {
8204 for (String tag : info.tags) {
8205 sb.append("Span-Tag: ").append(tag).append("\n");
8206 }
8207 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008208 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008209 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8210 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008211 }
8212 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008213
8214 // Only buffer up to ~64k. Various logging bits truncate
8215 // things at 128k.
8216 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008217 }
8218
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008219 // Flush immediately if the buffer's grown too large, or this
8220 // is a non-system app. Non-system apps are isolated with a
8221 // different tag & policy and not batched.
8222 //
8223 // Batching is useful during internal testing with
8224 // StrictMode settings turned up high. Without batching,
8225 // thousands of separate files could be created on boot.
8226 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008227 new Thread("Error dump: " + dropboxTag) {
8228 @Override
8229 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008230 String report;
8231 synchronized (sb) {
8232 report = sb.toString();
8233 sb.delete(0, sb.length());
8234 sb.trimToSize();
8235 }
8236 if (report.length() != 0) {
8237 dbox.addText(dropboxTag, report);
8238 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008239 }
8240 }.start();
8241 return;
8242 }
8243
8244 // System app batching:
8245 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008246 // An existing dropbox-writing thread is outstanding, so
8247 // we don't need to start it up. The existing thread will
8248 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008249 return;
8250 }
8251
8252 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8253 // (After this point, we shouldn't access AMS internal data structures.)
8254 new Thread("Error dump: " + dropboxTag) {
8255 @Override
8256 public void run() {
8257 // 5 second sleep to let stacks arrive and be batched together
8258 try {
8259 Thread.sleep(5000); // 5 seconds
8260 } catch (InterruptedException e) {}
8261
8262 String errorReport;
8263 synchronized (mStrictModeBuffer) {
8264 errorReport = mStrictModeBuffer.toString();
8265 if (errorReport.length() == 0) {
8266 return;
8267 }
8268 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8269 mStrictModeBuffer.trimToSize();
8270 }
8271 dbox.addText(dropboxTag, errorReport);
8272 }
8273 }.start();
8274 }
8275
Dan Egnor60d87622009-12-16 16:32:58 -08008276 /**
8277 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8278 * @param app object of the crashing app, null for the system server
8279 * @param tag reported by the caller
8280 * @param crashInfo describing the context of the error
8281 * @return true if the process should exit immediately (WTF is fatal)
8282 */
8283 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008284 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008285 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008286 final String processName = app == null ? "system_server"
8287 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008288
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008289 EventLog.writeEvent(EventLogTags.AM_WTF,
8290 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008291 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008292 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008293 tag, crashInfo.exceptionMessage);
8294
Jeff Sharkeya353d262011-10-28 11:12:06 -07008295 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008296
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008297 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008298 Settings.Global.getInt(mContext.getContentResolver(),
8299 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008300 crashApplication(r, crashInfo);
8301 return true;
8302 } else {
8303 return false;
8304 }
8305 }
8306
8307 /**
8308 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8309 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8310 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008311 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008312 if (app == null) {
8313 return null;
8314 }
8315
8316 synchronized (this) {
8317 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8318 final int NA = apps.size();
8319 for (int ia=0; ia<NA; ia++) {
8320 ProcessRecord p = apps.valueAt(ia);
8321 if (p.thread != null && p.thread.asBinder() == app) {
8322 return p;
8323 }
8324 }
8325 }
8326
Dianne Hackborncb44d962011-03-10 17:02:27 -08008327 Slog.w(TAG, "Can't find mystery application for " + reason
8328 + " from pid=" + Binder.getCallingPid()
8329 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008330 return null;
8331 }
8332 }
8333
8334 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008335 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8336 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008337 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008338 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8339 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008340 // Watchdog thread ends up invoking this function (with
8341 // a null ProcessRecord) to add the stack file to dropbox.
8342 // Do not acquire a lock on this (am) in such cases, as it
8343 // could cause a potential deadlock, if and when watchdog
8344 // is invoked due to unavailability of lock on am and it
8345 // would prevent watchdog from killing system_server.
8346 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008347 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008348 return;
8349 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008350 // Note: ProcessRecord 'process' is guarded by the service
8351 // instance. (notably process.pkgList, which could otherwise change
8352 // concurrently during execution of this method)
8353 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008354 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008355 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008356 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008357 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8358 for (String pkg : process.pkgList) {
8359 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008360 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008361 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008362 if (pi != null) {
8363 sb.append(" v").append(pi.versionCode);
8364 if (pi.versionName != null) {
8365 sb.append(" (").append(pi.versionName).append(")");
8366 }
8367 }
8368 } catch (RemoteException e) {
8369 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008370 }
Dan Egnora455d192010-03-12 08:52:28 -08008371 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008372 }
Dan Egnora455d192010-03-12 08:52:28 -08008373 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008374 }
8375
8376 private static String processClass(ProcessRecord process) {
8377 if (process == null || process.pid == MY_PID) {
8378 return "system_server";
8379 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8380 return "system_app";
8381 } else {
8382 return "data_app";
8383 }
8384 }
8385
8386 /**
8387 * Write a description of an error (crash, WTF, ANR) to the drop box.
8388 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8389 * @param process which caused the error, null means the system server
8390 * @param activity which triggered the error, null if unknown
8391 * @param parent activity related to the error, null if unknown
8392 * @param subject line related to the error, null if absent
8393 * @param report in long form describing the error, null if absent
8394 * @param logFile to include in the report, null if none
8395 * @param crashInfo giving an application stack trace, null if absent
8396 */
8397 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008398 ProcessRecord process, String processName, ActivityRecord activity,
8399 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008400 final String report, final File logFile,
8401 final ApplicationErrorReport.CrashInfo crashInfo) {
8402 // NOTE -- this must never acquire the ActivityManagerService lock,
8403 // otherwise the watchdog may be prevented from resetting the system.
8404
8405 final String dropboxTag = processClass(process) + "_" + eventType;
8406 final DropBoxManager dbox = (DropBoxManager)
8407 mContext.getSystemService(Context.DROPBOX_SERVICE);
8408
8409 // Exit early if the dropbox isn't configured to accept this report type.
8410 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8411
8412 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008413 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008414 if (activity != null) {
8415 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8416 }
8417 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8418 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8419 }
8420 if (parent != null && parent != activity) {
8421 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8422 }
8423 if (subject != null) {
8424 sb.append("Subject: ").append(subject).append("\n");
8425 }
8426 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008427 if (Debug.isDebuggerConnected()) {
8428 sb.append("Debugger: Connected\n");
8429 }
Dan Egnora455d192010-03-12 08:52:28 -08008430 sb.append("\n");
8431
8432 // Do the rest in a worker thread to avoid blocking the caller on I/O
8433 // (After this point, we shouldn't access AMS internal data structures.)
8434 Thread worker = new Thread("Error dump: " + dropboxTag) {
8435 @Override
8436 public void run() {
8437 if (report != null) {
8438 sb.append(report);
8439 }
8440 if (logFile != null) {
8441 try {
8442 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8443 } catch (IOException e) {
8444 Slog.e(TAG, "Error reading " + logFile, e);
8445 }
8446 }
8447 if (crashInfo != null && crashInfo.stackTrace != null) {
8448 sb.append(crashInfo.stackTrace);
8449 }
8450
Jeff Sharkey625239a2012-09-26 22:03:49 -07008451 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8452 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008453 if (lines > 0) {
8454 sb.append("\n");
8455
8456 // Merge several logcat streams, and take the last N lines
8457 InputStreamReader input = null;
8458 try {
8459 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8460 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8461 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8462
8463 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8464 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8465 input = new InputStreamReader(logcat.getInputStream());
8466
8467 int num;
8468 char[] buf = new char[8192];
8469 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8470 } catch (IOException e) {
8471 Slog.e(TAG, "Error running logcat", e);
8472 } finally {
8473 if (input != null) try { input.close(); } catch (IOException e) {}
8474 }
8475 }
8476
8477 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008478 }
Dan Egnora455d192010-03-12 08:52:28 -08008479 };
8480
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008481 if (process == null) {
8482 // If process is null, we are being called from some internal code
8483 // and may be about to die -- run this synchronously.
8484 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008485 } else {
8486 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008487 }
8488 }
8489
8490 /**
8491 * Bring up the "unexpected error" dialog box for a crashing app.
8492 * Deal with edge cases (intercepts from instrumented applications,
8493 * ActivityController, error intent receivers, that sort of thing).
8494 * @param r the application crashing
8495 * @param crashInfo describing the failure
8496 */
8497 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008498 long timeMillis = System.currentTimeMillis();
8499 String shortMsg = crashInfo.exceptionClassName;
8500 String longMsg = crashInfo.exceptionMessage;
8501 String stackTrace = crashInfo.stackTrace;
8502 if (shortMsg != null && longMsg != null) {
8503 longMsg = shortMsg + ": " + longMsg;
8504 } else if (shortMsg != null) {
8505 longMsg = shortMsg;
8506 }
8507
Dan Egnor60d87622009-12-16 16:32:58 -08008508 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008510 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 try {
8512 String name = r != null ? r.processName : null;
8513 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008514 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008515 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008516 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 + " at watcher's request");
8518 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008519 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 }
8521 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008522 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 }
8524 }
8525
8526 final long origId = Binder.clearCallingIdentity();
8527
8528 // If this process is running instrumentation, finish it.
8529 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008530 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008532 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8533 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 Bundle info = new Bundle();
8535 info.putString("shortMsg", shortMsg);
8536 info.putString("longMsg", longMsg);
8537 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8538 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008539 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008540 }
8541
Dan Egnor60d87622009-12-16 16:32:58 -08008542 // If we can't identify the process or it's already exceeded its crash quota,
8543 // quit right away without showing a crash dialog.
8544 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008546 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 }
8548
8549 Message msg = Message.obtain();
8550 msg.what = SHOW_ERROR_MSG;
8551 HashMap data = new HashMap();
8552 data.put("result", result);
8553 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 msg.obj = data;
8555 mHandler.sendMessage(msg);
8556
8557 Binder.restoreCallingIdentity(origId);
8558 }
8559
8560 int res = result.get();
8561
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008562 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008564 if (r != null && !r.isolated) {
8565 // XXX Can't keep track of crash time for isolated processes,
8566 // since they don't have a persistent identity.
8567 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 SystemClock.uptimeMillis());
8569 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008570 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008571 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008572 }
8573 }
8574
8575 if (appErrorIntent != null) {
8576 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008577 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008578 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008579 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008583
8584 Intent createAppErrorIntentLocked(ProcessRecord r,
8585 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8586 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008587 if (report == null) {
8588 return null;
8589 }
8590 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8591 result.setComponent(r.errorReportReceiver);
8592 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8593 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8594 return result;
8595 }
8596
Dan Egnorb7f03672009-12-09 16:22:32 -08008597 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8598 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008599 if (r.errorReportReceiver == null) {
8600 return null;
8601 }
8602
8603 if (!r.crashing && !r.notResponding) {
8604 return null;
8605 }
8606
Dan Egnorb7f03672009-12-09 16:22:32 -08008607 ApplicationErrorReport report = new ApplicationErrorReport();
8608 report.packageName = r.info.packageName;
8609 report.installerPackageName = r.errorReportReceiver.getPackageName();
8610 report.processName = r.processName;
8611 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008612 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008613
Dan Egnorb7f03672009-12-09 16:22:32 -08008614 if (r.crashing) {
8615 report.type = ApplicationErrorReport.TYPE_CRASH;
8616 report.crashInfo = crashInfo;
8617 } else if (r.notResponding) {
8618 report.type = ApplicationErrorReport.TYPE_ANR;
8619 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008620
Dan Egnorb7f03672009-12-09 16:22:32 -08008621 report.anrInfo.activity = r.notRespondingReport.tag;
8622 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8623 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008624 }
8625
Dan Egnorb7f03672009-12-09 16:22:32 -08008626 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008627 }
8628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008630 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 // assume our apps are happy - lazy create the list
8632 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8633
Dianne Hackborn0c380492012-08-20 17:23:30 -07008634 final boolean allUsers = ActivityManager.checkUidPermission(
8635 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8636 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8637 int userId = UserHandle.getUserId(Binder.getCallingUid());
8638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 synchronized (this) {
8640
8641 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008642 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8643 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008644 if (!allUsers && app.userId != userId) {
8645 continue;
8646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008647 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8648 // This one's in trouble, so we'll generate a report for it
8649 // crashes are higher priority (in case there's a crash *and* an anr)
8650 ActivityManager.ProcessErrorStateInfo report = null;
8651 if (app.crashing) {
8652 report = app.crashingReport;
8653 } else if (app.notResponding) {
8654 report = app.notRespondingReport;
8655 }
8656
8657 if (report != null) {
8658 if (errList == null) {
8659 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8660 }
8661 errList.add(report);
8662 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008663 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 " crashing = " + app.crashing +
8665 " notResponding = " + app.notResponding);
8666 }
8667 }
8668 }
8669 }
8670
8671 return errList;
8672 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008673
8674 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008675 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008676 if (currApp != null) {
8677 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8678 }
8679 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008680 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8681 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008682 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8683 if (currApp != null) {
8684 currApp.lru = 0;
8685 }
8686 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008687 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008688 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8689 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8690 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8691 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8692 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8693 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8694 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8695 } else {
8696 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8697 }
8698 }
8699
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008700 private void fillInProcMemInfo(ProcessRecord app,
8701 ActivityManager.RunningAppProcessInfo outInfo) {
8702 outInfo.pid = app.pid;
8703 outInfo.uid = app.info.uid;
8704 if (mHeavyWeightProcess == app) {
8705 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8706 }
8707 if (app.persistent) {
8708 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8709 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008710 if (app.hasActivities) {
8711 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8712 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008713 outInfo.lastTrimLevel = app.trimMemoryLevel;
8714 int adj = app.curAdj;
8715 outInfo.importance = oomAdjToImportance(adj, outInfo);
8716 outInfo.importanceReasonCode = app.adjTypeCode;
8717 }
8718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008720 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 // Lazy instantiation of list
8722 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008723 final boolean allUsers = ActivityManager.checkUidPermission(
8724 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8725 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8726 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 synchronized (this) {
8728 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008729 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8730 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008731 if (!allUsers && app.userId != userId) {
8732 continue;
8733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008734 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8735 // Generate process state info for running application
8736 ActivityManager.RunningAppProcessInfo currApp =
8737 new ActivityManager.RunningAppProcessInfo(app.processName,
8738 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008739 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008740 if (app.adjSource instanceof ProcessRecord) {
8741 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008742 currApp.importanceReasonImportance = oomAdjToImportance(
8743 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008744 } else if (app.adjSource instanceof ActivityRecord) {
8745 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008746 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8747 }
8748 if (app.adjTarget instanceof ComponentName) {
8749 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8750 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008751 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 // + " lru=" + currApp.lru);
8753 if (runList == null) {
8754 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8755 }
8756 runList.add(currApp);
8757 }
8758 }
8759 }
8760 return runList;
8761 }
8762
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008763 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008764 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008765 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8766 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8767 if (runningApps != null && runningApps.size() > 0) {
8768 Set<String> extList = new HashSet<String>();
8769 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8770 if (app.pkgList != null) {
8771 for (String pkg : app.pkgList) {
8772 extList.add(pkg);
8773 }
8774 }
8775 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008776 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008777 for (String pkg : extList) {
8778 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008779 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008780 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8781 retList.add(info);
8782 }
8783 } catch (RemoteException e) {
8784 }
8785 }
8786 }
8787 return retList;
8788 }
8789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008791 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8792 enforceNotIsolatedCaller("getMyMemoryState");
8793 synchronized (this) {
8794 ProcessRecord proc;
8795 synchronized (mPidsSelfLocked) {
8796 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8797 }
8798 fillInProcMemInfo(proc, outInfo);
8799 }
8800 }
8801
8802 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008804 if (checkCallingPermission(android.Manifest.permission.DUMP)
8805 != PackageManager.PERMISSION_GRANTED) {
8806 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8807 + Binder.getCallingPid()
8808 + ", uid=" + Binder.getCallingUid()
8809 + " without permission "
8810 + android.Manifest.permission.DUMP);
8811 return;
8812 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008813
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008814 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008815 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008816 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008817
8818 int opti = 0;
8819 while (opti < args.length) {
8820 String opt = args[opti];
8821 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8822 break;
8823 }
8824 opti++;
8825 if ("-a".equals(opt)) {
8826 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008827 } else if ("-c".equals(opt)) {
8828 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008829 } else if ("-h".equals(opt)) {
8830 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008831 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008832 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008833 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008834 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8835 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8836 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008837 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008838 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008839 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008840 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008841 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008842 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008843 pw.println(" all: dump all activities");
8844 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008845 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008846 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8847 pw.println(" a partial substring in a component name, a");
8848 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008849 pw.println(" -a: include all available server state.");
8850 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 } else {
8853 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008854 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008855 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008856
8857 long origId = Binder.clearCallingIdentity();
8858 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008859 // Is the caller requesting to dump a particular piece of data?
8860 if (opti < args.length) {
8861 String cmd = args[opti];
8862 opti++;
8863 if ("activities".equals(cmd) || "a".equals(cmd)) {
8864 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008865 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008867 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008868 String[] newArgs;
8869 String name;
8870 if (opti >= args.length) {
8871 name = null;
8872 newArgs = EMPTY_STRING_ARRAY;
8873 } else {
8874 name = args[opti];
8875 opti++;
8876 newArgs = new String[args.length - opti];
8877 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8878 args.length - opti);
8879 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008880 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008881 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008882 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008883 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008884 String[] newArgs;
8885 String name;
8886 if (opti >= args.length) {
8887 name = null;
8888 newArgs = EMPTY_STRING_ARRAY;
8889 } else {
8890 name = args[opti];
8891 opti++;
8892 newArgs = new String[args.length - opti];
8893 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8894 args.length - opti);
8895 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008896 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008897 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008899 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008900 String[] newArgs;
8901 String name;
8902 if (opti >= args.length) {
8903 name = null;
8904 newArgs = EMPTY_STRING_ARRAY;
8905 } else {
8906 name = args[opti];
8907 opti++;
8908 newArgs = new String[args.length - opti];
8909 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8910 args.length - opti);
8911 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008912 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008913 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008914 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008915 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8916 synchronized (this) {
8917 dumpOomLocked(fd, pw, args, opti, true);
8918 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008919 } else if ("provider".equals(cmd)) {
8920 String[] newArgs;
8921 String name;
8922 if (opti >= args.length) {
8923 name = null;
8924 newArgs = EMPTY_STRING_ARRAY;
8925 } else {
8926 name = args[opti];
8927 opti++;
8928 newArgs = new String[args.length - opti];
8929 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8930 }
8931 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8932 pw.println("No providers match: " + name);
8933 pw.println("Use -h for help.");
8934 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8936 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008937 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008938 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008939 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008940 String[] newArgs;
8941 String name;
8942 if (opti >= args.length) {
8943 name = null;
8944 newArgs = EMPTY_STRING_ARRAY;
8945 } else {
8946 name = args[opti];
8947 opti++;
8948 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8950 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008951 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008952 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008953 pw.println("No services match: " + name);
8954 pw.println("Use -h for help.");
8955 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008956 } else if ("package".equals(cmd)) {
8957 String[] newArgs;
8958 if (opti >= args.length) {
8959 pw.println("package: no package name specified");
8960 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008961 } else {
8962 dumpPackage = args[opti];
8963 opti++;
8964 newArgs = new String[args.length - opti];
8965 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8966 args.length - opti);
8967 args = newArgs;
8968 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008969 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008970 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008971 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8972 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008973 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008974 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008975 } else {
8976 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008977 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8978 pw.println("Bad activity command, or no activities match: " + cmd);
8979 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008980 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008981 }
8982 if (!more) {
8983 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008984 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008986 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008987
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008988 // No piece of data specified, dump everything.
8989 synchronized (this) {
8990 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 if (needSep) {
8993 pw.println(" ");
8994 }
8995 if (dumpAll) {
8996 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008998 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008999 if (needSep) {
9000 pw.println(" ");
9001 }
9002 if (dumpAll) {
9003 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009004 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009005 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 if (needSep) {
9007 pw.println(" ");
9008 }
9009 if (dumpAll) {
9010 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009012 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 if (needSep) {
9014 pw.println(" ");
9015 }
9016 if (dumpAll) {
9017 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009019 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 if (needSep) {
9021 pw.println(" ");
9022 }
9023 if (dumpAll) {
9024 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009025 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009026 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009027 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009028 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009029 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009030
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009031 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009032 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009033 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9034 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9036 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009037 pw.println(" ");
9038 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009039 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9040 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009041 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009044 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009045 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009047 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009048 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009049 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009050 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009052 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009053 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9054 pw.println(" ");
9055 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009056 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009057 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009058 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009059 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009060 pw.println(" ");
9061 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009062 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009063 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009066 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009067 if (mMainStack.mPausingActivity != null) {
9068 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009069 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009070 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009071 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009072 if (dumpAll) {
9073 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9074 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009075 pw.println(" mDismissKeyguardOnNextActivity: "
9076 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009079 if (mRecentTasks.size() > 0) {
9080 pw.println();
9081 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009082
9083 final int N = mRecentTasks.size();
9084 for (int i=0; i<N; i++) {
9085 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009086 if (dumpPackage != null) {
9087 if (tr.realActivity == null ||
9088 !dumpPackage.equals(tr.realActivity)) {
9089 continue;
9090 }
9091 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009092 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9093 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009094 if (dumpAll) {
9095 mRecentTasks.get(i).dump(pw, " ");
9096 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097 }
9098 }
9099
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009100 if (dumpAll) {
9101 pw.println(" ");
9102 pw.println(" mCurTask: " + mCurTask);
9103 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009104
9105 return true;
9106 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009107
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009108 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009109 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009110 boolean needSep = false;
9111 int numPers = 0;
9112
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009113 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9114
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009115 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009116 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9117 final int NA = procs.size();
9118 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009119 ProcessRecord r = procs.valueAt(ia);
9120 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9121 continue;
9122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 if (!needSep) {
9124 pw.println(" All known processes:");
9125 needSep = true;
9126 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009127 pw.print(r.persistent ? " *PERS*" : " *APP*");
9128 pw.print(" UID "); pw.print(procs.keyAt(ia));
9129 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009130 r.dump(pw, " ");
9131 if (r.persistent) {
9132 numPers++;
9133 }
9134 }
9135 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009136 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009137
9138 if (mIsolatedProcesses.size() > 0) {
9139 if (needSep) pw.println(" ");
9140 needSep = true;
9141 pw.println(" Isolated process list (sorted by uid):");
9142 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9143 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9144 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9145 continue;
9146 }
9147 pw.println(String.format("%sIsolated #%2d: %s",
9148 " ", i, r.toString()));
9149 }
9150 }
9151
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009152 if (mLruProcesses.size() > 0) {
9153 if (needSep) pw.println(" ");
9154 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009155 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009156 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009157 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 needSep = true;
9159 }
9160
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009161 if (dumpAll) {
9162 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009163 boolean printed = false;
9164 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9165 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9166 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9167 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009168 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009169 if (!printed) {
9170 if (needSep) pw.println(" ");
9171 needSep = true;
9172 pw.println(" PID mappings:");
9173 printed = true;
9174 }
9175 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9176 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177 }
9178 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009179 }
9180
9181 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009182 synchronized (mPidsSelfLocked) {
9183 boolean printed = false;
9184 for (int i=0; i<mForegroundProcesses.size(); i++) {
9185 ProcessRecord r = mPidsSelfLocked.get(
9186 mForegroundProcesses.valueAt(i).pid);
9187 if (dumpPackage != null && (r == null
9188 || !dumpPackage.equals(r.info.packageName))) {
9189 continue;
9190 }
9191 if (!printed) {
9192 if (needSep) pw.println(" ");
9193 needSep = true;
9194 pw.println(" Foreground Processes:");
9195 printed = true;
9196 }
9197 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9198 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009201 }
9202
9203 if (mPersistentStartingProcesses.size() > 0) {
9204 if (needSep) pw.println(" ");
9205 needSep = true;
9206 pw.println(" Persisent processes that are starting:");
9207 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009208 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009211 if (mRemovedProcesses.size() > 0) {
9212 if (needSep) pw.println(" ");
9213 needSep = true;
9214 pw.println(" Processes that are being removed:");
9215 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009216 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009217 }
9218
9219 if (mProcessesOnHold.size() > 0) {
9220 if (needSep) pw.println(" ");
9221 needSep = true;
9222 pw.println(" Processes that are on old until the system is ready:");
9223 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009224 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009226
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009227 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009228
9229 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009230 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009231 long now = SystemClock.uptimeMillis();
9232 for (Map.Entry<String, SparseArray<Long>> procs
9233 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009234 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009235 SparseArray<Long> uids = procs.getValue();
9236 final int N = uids.size();
9237 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009238 int puid = uids.keyAt(i);
9239 ProcessRecord r = mProcessNames.get(pname, puid);
9240 if (dumpPackage != null && (r == null
9241 || !dumpPackage.equals(r.info.packageName))) {
9242 continue;
9243 }
9244 if (!printed) {
9245 if (needSep) pw.println(" ");
9246 needSep = true;
9247 pw.println(" Time since processes crashed:");
9248 printed = true;
9249 }
9250 pw.print(" Process "); pw.print(pname);
9251 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009252 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009253 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9254 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009255 }
9256 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009258
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009259 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009260 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009261 for (Map.Entry<String, SparseArray<Long>> procs
9262 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009263 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 SparseArray<Long> uids = procs.getValue();
9265 final int N = uids.size();
9266 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009267 int puid = uids.keyAt(i);
9268 ProcessRecord r = mProcessNames.get(pname, puid);
9269 if (dumpPackage != null && (r == null
9270 || !dumpPackage.equals(r.info.packageName))) {
9271 continue;
9272 }
9273 if (!printed) {
9274 if (needSep) pw.println(" ");
9275 needSep = true;
9276 pw.println(" Bad processes:");
9277 }
9278 pw.print(" Bad process "); pw.print(pname);
9279 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009280 pw.print(": crashed at time ");
9281 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 }
9283 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009285
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009286 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009287 pw.println(" mStartedUsers:");
9288 for (int i=0; i<mStartedUsers.size(); i++) {
9289 UserStartedState uss = mStartedUsers.valueAt(i);
9290 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009291 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009292 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009293 pw.print(" mUserLru: [");
9294 for (int i=0; i<mUserLru.size(); i++) {
9295 if (i > 0) pw.print(", ");
9296 pw.print(mUserLru.get(i));
9297 }
9298 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009299 if (dumpAll) {
9300 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9301 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009302 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009303 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009304 if (dumpAll) {
9305 StringBuilder sb = new StringBuilder(128);
9306 sb.append(" mPreviousProcessVisibleTime: ");
9307 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9308 pw.println(sb);
9309 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009310 if (mHeavyWeightProcess != null) {
9311 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9312 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009314 if (dumpAll) {
9315 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009316 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009317 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009318 for (Map.Entry<String, Integer> entry
9319 : mCompatModePackages.getPackages().entrySet()) {
9320 String pkg = entry.getKey();
9321 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009322 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9323 continue;
9324 }
9325 if (!printed) {
9326 pw.println(" mScreenCompatPackages:");
9327 printed = true;
9328 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009329 pw.print(" "); pw.print(pkg); pw.print(": ");
9330 pw.print(mode); pw.println();
9331 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009332 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009333 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009334 if (mSleeping || mWentToSleep || mLockScreenShown) {
9335 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9336 + " mLockScreenShown " + mLockScreenShown);
9337 }
9338 if (mShuttingDown) {
9339 pw.println(" mShuttingDown=" + mShuttingDown);
9340 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009341 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9342 || mOrigWaitForDebugger) {
9343 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9344 + " mDebugTransient=" + mDebugTransient
9345 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9346 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009347 if (mOpenGlTraceApp != null) {
9348 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9349 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009350 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9351 || mProfileFd != null) {
9352 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9353 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9354 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9355 + mAutoStopProfiler);
9356 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357 if (mAlwaysFinishActivities || mController != null) {
9358 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9359 + " mController=" + mController);
9360 }
9361 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009364 + " mProcessesReady=" + mProcessesReady
9365 + " mSystemReady=" + mSystemReady);
9366 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 + " mBooted=" + mBooted
9368 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009369 pw.print(" mLastPowerCheckRealtime=");
9370 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9371 pw.println("");
9372 pw.print(" mLastPowerCheckUptime=");
9373 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9374 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009375 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9376 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009377 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009378 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9379 + " mNumHiddenProcs=" + mNumHiddenProcs
9380 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009381 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009383
9384 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 }
9386
Dianne Hackborn287952c2010-09-22 22:34:31 -07009387 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009388 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009389 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009390 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009391 long now = SystemClock.uptimeMillis();
9392 for (int i=0; i<mProcessesToGc.size(); i++) {
9393 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009394 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9395 continue;
9396 }
9397 if (!printed) {
9398 if (needSep) pw.println(" ");
9399 needSep = true;
9400 pw.println(" Processes that are waiting to GC:");
9401 printed = true;
9402 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009403 pw.print(" Process "); pw.println(proc);
9404 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9405 pw.print(", last gced=");
9406 pw.print(now-proc.lastRequestedGc);
9407 pw.print(" ms ago, last lowMem=");
9408 pw.print(now-proc.lastLowMemory);
9409 pw.println(" ms ago");
9410
9411 }
9412 }
9413 return needSep;
9414 }
9415
9416 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9417 int opti, boolean dumpAll) {
9418 boolean needSep = false;
9419
9420 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009421 if (needSep) pw.println(" ");
9422 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009423 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009424 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009425 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009426 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9427 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9428 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9429 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9430 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009431 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009432 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009433 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009434 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009435 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009436 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009437
9438 if (needSep) pw.println(" ");
9439 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009440 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009441 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009442 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009443 needSep = true;
9444 }
9445
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009446 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009447
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009448 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009449 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009450 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009451 if (mHeavyWeightProcess != null) {
9452 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9453 }
9454
9455 return true;
9456 }
9457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009458 /**
9459 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009460 * - no provider specified: dump all the providers
9461 * - a flattened component name that matched an existing provider was specified as the
9462 * first arg: dump that one provider
9463 * - the first arg isn't the flattened component name of an existing provider:
9464 * dump all providers whose component contains the first arg as a substring
9465 */
9466 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9467 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009468 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009469 }
9470
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009471 static class ItemMatcher {
9472 ArrayList<ComponentName> components;
9473 ArrayList<String> strings;
9474 ArrayList<Integer> objects;
9475 boolean all;
9476
9477 ItemMatcher() {
9478 all = true;
9479 }
9480
9481 void build(String name) {
9482 ComponentName componentName = ComponentName.unflattenFromString(name);
9483 if (componentName != null) {
9484 if (components == null) {
9485 components = new ArrayList<ComponentName>();
9486 }
9487 components.add(componentName);
9488 all = false;
9489 } else {
9490 int objectId = 0;
9491 // Not a '/' separated full component name; maybe an object ID?
9492 try {
9493 objectId = Integer.parseInt(name, 16);
9494 if (objects == null) {
9495 objects = new ArrayList<Integer>();
9496 }
9497 objects.add(objectId);
9498 all = false;
9499 } catch (RuntimeException e) {
9500 // Not an integer; just do string match.
9501 if (strings == null) {
9502 strings = new ArrayList<String>();
9503 }
9504 strings.add(name);
9505 all = false;
9506 }
9507 }
9508 }
9509
9510 int build(String[] args, int opti) {
9511 for (; opti<args.length; opti++) {
9512 String name = args[opti];
9513 if ("--".equals(name)) {
9514 return opti+1;
9515 }
9516 build(name);
9517 }
9518 return opti;
9519 }
9520
9521 boolean match(Object object, ComponentName comp) {
9522 if (all) {
9523 return true;
9524 }
9525 if (components != null) {
9526 for (int i=0; i<components.size(); i++) {
9527 if (components.get(i).equals(comp)) {
9528 return true;
9529 }
9530 }
9531 }
9532 if (objects != null) {
9533 for (int i=0; i<objects.size(); i++) {
9534 if (System.identityHashCode(object) == objects.get(i)) {
9535 return true;
9536 }
9537 }
9538 }
9539 if (strings != null) {
9540 String flat = comp.flattenToString();
9541 for (int i=0; i<strings.size(); i++) {
9542 if (flat.contains(strings.get(i))) {
9543 return true;
9544 }
9545 }
9546 }
9547 return false;
9548 }
9549 }
9550
Dianne Hackborn625ac272010-09-17 18:29:22 -07009551 /**
9552 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009553 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009554 * - the cmd arg isn't the flattened component name of an existing activity:
9555 * dump all activity whose component contains the cmd as a substring
9556 * - A hex number of the ActivityRecord object instance.
9557 */
9558 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9559 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009560 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009561
9562 if ("all".equals(name)) {
9563 synchronized (this) {
9564 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009565 activities.add(r1);
9566 }
9567 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009568 } else if ("top".equals(name)) {
9569 synchronized (this) {
9570 final int N = mMainStack.mHistory.size();
9571 if (N > 0) {
9572 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9573 }
9574 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009575 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009576 ItemMatcher matcher = new ItemMatcher();
9577 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578
9579 synchronized (this) {
9580 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009581 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009582 activities.add(r1);
9583 }
9584 }
9585 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009586 }
9587
9588 if (activities.size() <= 0) {
9589 return false;
9590 }
9591
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009592 String[] newArgs = new String[args.length - opti];
9593 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9594
Dianne Hackborn30d71892010-12-11 10:37:55 -08009595 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009596 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009597 for (int i=activities.size()-1; i>=0; i--) {
9598 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009599 if (needSep) {
9600 pw.println();
9601 }
9602 needSep = true;
9603 synchronized (this) {
9604 if (lastTask != r.task) {
9605 lastTask = r.task;
9606 pw.print("TASK "); pw.print(lastTask.affinity);
9607 pw.print(" id="); pw.println(lastTask.taskId);
9608 if (dumpAll) {
9609 lastTask.dump(pw, " ");
9610 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009611 }
9612 }
9613 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009614 }
9615 return true;
9616 }
9617
9618 /**
9619 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9620 * there is a thread associated with the activity.
9621 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009622 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009623 final ActivityRecord r, String[] args, boolean dumpAll) {
9624 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009625 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009626 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9627 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9628 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009629 if (r.app != null) pw.println(r.app.pid);
9630 else pw.println("(not running)");
9631 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009632 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009633 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009634 }
9635 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009636 // flush anything that is already in the PrintWriter since the thread is going
9637 // to write to the file descriptor directly
9638 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009639 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009640 TransferPipe tp = new TransferPipe();
9641 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009642 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9643 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009644 tp.go(fd);
9645 } finally {
9646 tp.kill();
9647 }
9648 } catch (IOException e) {
9649 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009650 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009651 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009652 }
9653 }
9654 }
9655
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009656 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009657 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009658 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009659 boolean onlyHistory = false;
9660
9661 if ("history".equals(dumpPackage)) {
9662 onlyHistory = true;
9663 dumpPackage = null;
9664 }
9665
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009666 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009667 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009668 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009669 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009670 Iterator it = mRegisteredReceivers.values().iterator();
9671 while (it.hasNext()) {
9672 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009673 if (dumpPackage != null && (r.app == null ||
9674 !dumpPackage.equals(r.app.info.packageName))) {
9675 continue;
9676 }
9677 if (!printed) {
9678 pw.println(" Registered Receivers:");
9679 needSep = true;
9680 printed = true;
9681 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009682 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009683 r.dump(pw, " ");
9684 }
9685 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009686
9687 if (mReceiverResolver.dump(pw, needSep ?
9688 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9689 " ", dumpPackage, false)) {
9690 needSep = true;
9691 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009692 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009693
9694 for (BroadcastQueue q : mBroadcastQueues) {
9695 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009698 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009699
Dianne Hackborn786b4402012-08-27 15:14:02 -07009700 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009701 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9702 if (needSep) {
9703 pw.println();
9704 }
9705 needSep = true;
9706 pw.print(" Sticky broadcasts for user ");
9707 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9708 StringBuilder sb = new StringBuilder(128);
9709 for (Map.Entry<String, ArrayList<Intent>> ent
9710 : mStickyBroadcasts.valueAt(user).entrySet()) {
9711 pw.print(" * Sticky action "); pw.print(ent.getKey());
9712 if (dumpAll) {
9713 pw.println(":");
9714 ArrayList<Intent> intents = ent.getValue();
9715 final int N = intents.size();
9716 for (int i=0; i<N; i++) {
9717 sb.setLength(0);
9718 sb.append(" Intent: ");
9719 intents.get(i).toShortString(sb, false, true, false, false);
9720 pw.println(sb.toString());
9721 Bundle bundle = intents.get(i).getExtras();
9722 if (bundle != null) {
9723 pw.print(" ");
9724 pw.println(bundle.toString());
9725 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009726 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009727 } else {
9728 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009729 }
9730 }
9731 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009732 }
9733
Dianne Hackborn786b4402012-08-27 15:14:02 -07009734 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009735 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009736 for (BroadcastQueue queue : mBroadcastQueues) {
9737 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9738 + queue.mBroadcastsScheduled);
9739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009740 pw.println(" mHandler:");
9741 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009742 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009744
9745 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746 }
9747
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009748 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009749 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009750 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009752 ItemMatcher matcher = new ItemMatcher();
9753 matcher.build(args, opti);
9754
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009755 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009756
9757 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009758
9759 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009760 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009761 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009762 ContentProviderRecord r = mLaunchingProviders.get(i);
9763 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9764 continue;
9765 }
9766 if (!printed) {
9767 if (needSep) pw.println(" ");
9768 needSep = true;
9769 pw.println(" Launching content providers:");
9770 printed = true;
9771 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009772 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009773 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009774 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009775 }
9776
9777 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009778 if (needSep) pw.println();
9779 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009780 pw.println("Granted Uri Permissions:");
9781 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9782 int uid = mGrantedUriPermissions.keyAt(i);
9783 HashMap<Uri, UriPermission> perms
9784 = mGrantedUriPermissions.valueAt(i);
9785 pw.print(" * UID "); pw.print(uid);
9786 pw.println(" holds:");
9787 for (UriPermission perm : perms.values()) {
9788 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009789 if (dumpAll) {
9790 perm.dump(pw, " ");
9791 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009792 }
9793 }
9794 needSep = true;
9795 }
9796
9797 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009798 }
9799
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009800 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009801 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009802 boolean needSep = false;
9803
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009804 if (mIntentSenderRecords.size() > 0) {
9805 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009806 Iterator<WeakReference<PendingIntentRecord>> it
9807 = mIntentSenderRecords.values().iterator();
9808 while (it.hasNext()) {
9809 WeakReference<PendingIntentRecord> ref = it.next();
9810 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009811 if (dumpPackage != null && (rec == null
9812 || !dumpPackage.equals(rec.key.packageName))) {
9813 continue;
9814 }
9815 if (!printed) {
9816 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9817 printed = true;
9818 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009819 needSep = true;
9820 if (rec != null) {
9821 pw.print(" * "); pw.println(rec);
9822 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009823 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009824 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009825 } else {
9826 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009827 }
9828 }
9829 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009830
9831 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 }
9833
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009834 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009835 String prefix, String label, boolean complete, boolean brief, boolean client,
9836 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009838 boolean needNL = false;
9839 final String innerPrefix = prefix + " ";
9840 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009842 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009843 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9844 continue;
9845 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009846 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 if (needNL) {
9848 pw.println(" ");
9849 needNL = false;
9850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009851 if (lastTask != r.task) {
9852 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009853 pw.print(prefix);
9854 pw.print(full ? "* " : " ");
9855 pw.println(lastTask);
9856 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009857 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009858 } else if (complete) {
9859 // Complete + brief == give a summary. Isn't that obvious?!?
9860 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009861 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009862 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009863 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009865 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009866 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9867 pw.print(" #"); pw.print(i); pw.print(": ");
9868 pw.println(r);
9869 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009870 r.dump(pw, innerPrefix);
9871 } else if (complete) {
9872 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009873 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009874 if (r.app != null) {
9875 pw.print(innerPrefix); pw.println(r.app);
9876 }
9877 }
9878 if (client && r.app != null && r.app.thread != null) {
9879 // flush anything that is already in the PrintWriter since the thread is going
9880 // to write to the file descriptor directly
9881 pw.flush();
9882 try {
9883 TransferPipe tp = new TransferPipe();
9884 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009885 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9886 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009887 // Short timeout, since blocking here can
9888 // deadlock with the application.
9889 tp.go(fd, 2000);
9890 } finally {
9891 tp.kill();
9892 }
9893 } catch (IOException e) {
9894 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9895 } catch (RemoteException e) {
9896 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9897 }
9898 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009900 }
9901 }
9902
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009903 private static String buildOomTag(String prefix, String space, int val, int base) {
9904 if (val == base) {
9905 if (space == null) return prefix;
9906 return prefix + " ";
9907 }
9908 return prefix + "+" + Integer.toString(val-base);
9909 }
9910
9911 private static final int dumpProcessList(PrintWriter pw,
9912 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009913 String prefix, String normalLabel, String persistentLabel,
9914 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009916 final int N = list.size()-1;
9917 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009918 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009919 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9920 continue;
9921 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009922 pw.println(String.format("%s%s #%2d: %s",
9923 prefix, (r.persistent ? persistentLabel : normalLabel),
9924 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009925 if (r.persistent) {
9926 numPers++;
9927 }
9928 }
9929 return numPers;
9930 }
9931
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009932 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009933 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009934 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009935 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009936
Dianne Hackborn905577f2011-09-07 18:31:28 -07009937 ArrayList<Pair<ProcessRecord, Integer>> list
9938 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9939 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009940 ProcessRecord r = origList.get(i);
9941 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9942 continue;
9943 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009944 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9945 }
9946
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009947 if (list.size() <= 0) {
9948 return false;
9949 }
9950
Dianne Hackborn905577f2011-09-07 18:31:28 -07009951 Comparator<Pair<ProcessRecord, Integer>> comparator
9952 = new Comparator<Pair<ProcessRecord, Integer>>() {
9953 @Override
9954 public int compare(Pair<ProcessRecord, Integer> object1,
9955 Pair<ProcessRecord, Integer> object2) {
9956 if (object1.first.setAdj != object2.first.setAdj) {
9957 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9958 }
9959 if (object1.second.intValue() != object2.second.intValue()) {
9960 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9961 }
9962 return 0;
9963 }
9964 };
9965
9966 Collections.sort(list, comparator);
9967
Dianne Hackborn287952c2010-09-22 22:34:31 -07009968 final long curRealtime = SystemClock.elapsedRealtime();
9969 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9970 final long curUptime = SystemClock.uptimeMillis();
9971 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9972
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009973 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009974 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009975 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009976 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009977 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009978 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9979 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009980 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9981 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009982 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9983 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009984 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9985 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009986 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009987 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009988 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9989 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9990 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9991 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9992 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9993 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9994 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9995 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009996 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9997 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009998 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9999 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010000 } else {
10001 oomAdj = Integer.toString(r.setAdj);
10002 }
10003 String schedGroup;
10004 switch (r.setSchedGroup) {
10005 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10006 schedGroup = "B";
10007 break;
10008 case Process.THREAD_GROUP_DEFAULT:
10009 schedGroup = "F";
10010 break;
10011 default:
10012 schedGroup = Integer.toString(r.setSchedGroup);
10013 break;
10014 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010015 String foreground;
10016 if (r.foregroundActivities) {
10017 foreground = "A";
10018 } else if (r.foregroundServices) {
10019 foreground = "S";
10020 } else {
10021 foreground = " ";
10022 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010023 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010024 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010025 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10026 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010027 if (r.adjSource != null || r.adjTarget != null) {
10028 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010029 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010030 if (r.adjTarget instanceof ComponentName) {
10031 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10032 } else if (r.adjTarget != null) {
10033 pw.print(r.adjTarget.toString());
10034 } else {
10035 pw.print("{null}");
10036 }
10037 pw.print("<=");
10038 if (r.adjSource instanceof ProcessRecord) {
10039 pw.print("Proc{");
10040 pw.print(((ProcessRecord)r.adjSource).toShortString());
10041 pw.println("}");
10042 } else if (r.adjSource != null) {
10043 pw.println(r.adjSource.toString());
10044 } else {
10045 pw.println("{null}");
10046 }
10047 }
10048 if (inclDetails) {
10049 pw.print(prefix);
10050 pw.print(" ");
10051 pw.print("oom: max="); pw.print(r.maxAdj);
10052 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010053 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010054 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010055 pw.print(" curRaw="); pw.print(r.curRawAdj);
10056 pw.print(" setRaw="); pw.print(r.setRawAdj);
10057 pw.print(" cur="); pw.print(r.curAdj);
10058 pw.print(" set="); pw.println(r.setAdj);
10059 pw.print(prefix);
10060 pw.print(" ");
10061 pw.print("keeping="); pw.print(r.keeping);
10062 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010063 pw.print(" empty="); pw.print(r.empty);
10064 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010065
10066 if (!r.keeping) {
10067 if (r.lastWakeTime != 0) {
10068 long wtime;
10069 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10070 synchronized (stats) {
10071 wtime = stats.getProcessWakeTime(r.info.uid,
10072 r.pid, curRealtime);
10073 }
10074 long timeUsed = wtime - r.lastWakeTime;
10075 pw.print(prefix);
10076 pw.print(" ");
10077 pw.print("keep awake over ");
10078 TimeUtils.formatDuration(realtimeSince, pw);
10079 pw.print(" used ");
10080 TimeUtils.formatDuration(timeUsed, pw);
10081 pw.print(" (");
10082 pw.print((timeUsed*100)/realtimeSince);
10083 pw.println("%)");
10084 }
10085 if (r.lastCpuTime != 0) {
10086 long timeUsed = r.curCpuTime - r.lastCpuTime;
10087 pw.print(prefix);
10088 pw.print(" ");
10089 pw.print("run cpu over ");
10090 TimeUtils.formatDuration(uptimeSince, pw);
10091 pw.print(" used ");
10092 TimeUtils.formatDuration(timeUsed, pw);
10093 pw.print(" (");
10094 pw.print((timeUsed*100)/uptimeSince);
10095 pw.println("%)");
10096 }
10097 }
10098 }
10099 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010100 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010101 }
10102
Dianne Hackbornb437e092011-08-05 17:50:29 -070010103 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010104 ArrayList<ProcessRecord> procs;
10105 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010106 if (args != null && args.length > start
10107 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010108 procs = new ArrayList<ProcessRecord>();
10109 int pid = -1;
10110 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010111 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010112 } catch (NumberFormatException e) {
10113
10114 }
10115 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10116 ProcessRecord proc = mLruProcesses.get(i);
10117 if (proc.pid == pid) {
10118 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010119 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010120 procs.add(proc);
10121 }
10122 }
10123 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010124 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010125 return null;
10126 }
10127 } else {
10128 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10129 }
10130 }
10131 return procs;
10132 }
10133
10134 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10135 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010136 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010137 if (procs == null) {
10138 return;
10139 }
10140
10141 long uptime = SystemClock.uptimeMillis();
10142 long realtime = SystemClock.elapsedRealtime();
10143 pw.println("Applications Graphics Acceleration Info:");
10144 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10145
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010146 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10147 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010148 if (r.thread != null) {
10149 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10150 pw.flush();
10151 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010152 TransferPipe tp = new TransferPipe();
10153 try {
10154 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10155 tp.go(fd);
10156 } finally {
10157 tp.kill();
10158 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010159 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010160 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010161 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010162 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010163 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010164 pw.flush();
10165 }
10166 }
10167 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010168 }
10169
Jeff Brown6754ba22011-12-14 20:20:01 -080010170 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10171 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10172 if (procs == null) {
10173 return;
10174 }
10175
10176 pw.println("Applications Database Info:");
10177
10178 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10179 ProcessRecord r = procs.get(i);
10180 if (r.thread != null) {
10181 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10182 pw.flush();
10183 try {
10184 TransferPipe tp = new TransferPipe();
10185 try {
10186 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10187 tp.go(fd);
10188 } finally {
10189 tp.kill();
10190 }
10191 } catch (IOException e) {
10192 pw.println("Failure while dumping the app: " + r);
10193 pw.flush();
10194 } catch (RemoteException e) {
10195 pw.println("Got a RemoteException while dumping the app " + r);
10196 pw.flush();
10197 }
10198 }
10199 }
10200 }
10201
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010202 final static class MemItem {
10203 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010204 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010205 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010206 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010207 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010208
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010209 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010210 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010211 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010212 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010213 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010214 }
10215 }
10216
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010217 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010218 boolean sort) {
10219 if (sort) {
10220 Collections.sort(items, new Comparator<MemItem>() {
10221 @Override
10222 public int compare(MemItem lhs, MemItem rhs) {
10223 if (lhs.pss < rhs.pss) {
10224 return 1;
10225 } else if (lhs.pss > rhs.pss) {
10226 return -1;
10227 }
10228 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010229 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010230 });
10231 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010232
10233 for (int i=0; i<items.size(); i++) {
10234 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010235 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010236 if (mi.subitems != null) {
10237 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10238 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010239 }
10240 }
10241
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010242 // These are in KB.
10243 static final long[] DUMP_MEM_BUCKETS = new long[] {
10244 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10245 120*1024, 160*1024, 200*1024,
10246 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10247 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10248 };
10249
Dianne Hackborn672342c2011-11-29 11:29:02 -080010250 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10251 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010252 int start = label.lastIndexOf('.');
10253 if (start >= 0) start++;
10254 else start = 0;
10255 int end = label.length();
10256 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10257 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10258 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10259 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010260 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010261 out.append(label, start, end);
10262 return;
10263 }
10264 }
10265 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010266 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010267 out.append(label, start, end);
10268 }
10269
10270 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10271 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10272 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10273 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10274 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10275 };
10276 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10277 "System", "Persistent", "Foreground",
10278 "Visible", "Perceptible", "Heavy Weight",
10279 "Backup", "A Services", "Home", "Previous",
10280 "B Services", "Background"
10281 };
10282
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010283 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010284 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010285 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010286 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010287 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010288
10289 int opti = 0;
10290 while (opti < args.length) {
10291 String opt = args[opti];
10292 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10293 break;
10294 }
10295 opti++;
10296 if ("-a".equals(opt)) {
10297 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010298 } else if ("--oom".equals(opt)) {
10299 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010300 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010301 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010302 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010303 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010304 pw.println("If [process] is specified it can be the name or ");
10305 pw.println("pid of a specific process to dump.");
10306 return;
10307 } else {
10308 pw.println("Unknown argument: " + opt + "; use -h for help");
10309 }
10310 }
10311
10312 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010313 if (procs == null) {
10314 return;
10315 }
10316
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010317 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010318 long uptime = SystemClock.uptimeMillis();
10319 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320
10321 if (procs.size() == 1 || isCheckinRequest) {
10322 dumpAll = true;
10323 }
10324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010325 if (isCheckinRequest) {
10326 // short checkin version
10327 pw.println(uptime + "," + realtime);
10328 pw.flush();
10329 } else {
10330 pw.println("Applications Memory Usage (kB):");
10331 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10332 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010333
Dianne Hackbornb437e092011-08-05 17:50:29 -070010334 String[] innerArgs = new String[args.length-opti];
10335 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10336
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010337 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10338 long nativePss=0, dalvikPss=0, otherPss=0;
10339 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10340
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010341 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10342 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10343 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010344
10345 long totalPss = 0;
10346
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010347 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10348 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010351 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10352 pw.flush();
10353 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010354 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010355 if (dumpAll) {
10356 try {
10357 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10358 } catch (RemoteException e) {
10359 if (!isCheckinRequest) {
10360 pw.println("Got RemoteException!");
10361 pw.flush();
10362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010364 } else {
10365 mi = new Debug.MemoryInfo();
10366 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010368
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010369 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010370 long myTotalPss = mi.getTotalPss();
10371 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010372 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010373 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010374 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010375
10376 nativePss += mi.nativePss;
10377 dalvikPss += mi.dalvikPss;
10378 otherPss += mi.otherPss;
10379 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10380 long mem = mi.getOtherPss(j);
10381 miscPss[j] += mem;
10382 otherPss -= mem;
10383 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010384
10385 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010386 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10387 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010388 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010389 if (oomProcs[oomIndex] == null) {
10390 oomProcs[oomIndex] = new ArrayList<MemItem>();
10391 }
10392 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010393 break;
10394 }
10395 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 }
10398 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010399
10400 if (!isCheckinRequest && procs.size() > 1) {
10401 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10402
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010403 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10404 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10405 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010406 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010407 String label = Debug.MemoryInfo.getOtherLabel(j);
10408 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010409 }
10410
Dianne Hackbornb437e092011-08-05 17:50:29 -070010411 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10412 for (int j=0; j<oomPss.length; j++) {
10413 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010414 String label = DUMP_MEM_OOM_LABEL[j];
10415 MemItem item = new MemItem(label, label, oomPss[j],
10416 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010417 item.subitems = oomProcs[j];
10418 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010419 }
10420 }
10421
Dianne Hackborn672342c2011-11-29 11:29:02 -080010422 if (outTag != null || outStack != null) {
10423 if (outTag != null) {
10424 appendMemBucket(outTag, totalPss, "total", false);
10425 }
10426 if (outStack != null) {
10427 appendMemBucket(outStack, totalPss, "total", true);
10428 }
10429 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010430 for (int i=0; i<oomMems.size(); i++) {
10431 MemItem miCat = oomMems.get(i);
10432 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10433 continue;
10434 }
10435 if (miCat.id < ProcessList.SERVICE_ADJ
10436 || miCat.id == ProcessList.HOME_APP_ADJ
10437 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010438 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10439 outTag.append(" / ");
10440 }
10441 if (outStack != null) {
10442 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10443 if (firstLine) {
10444 outStack.append(":");
10445 firstLine = false;
10446 }
10447 outStack.append("\n\t at ");
10448 } else {
10449 outStack.append("$");
10450 }
10451 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010452 for (int j=0; j<miCat.subitems.size(); j++) {
10453 MemItem mi = miCat.subitems.get(j);
10454 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010455 if (outTag != null) {
10456 outTag.append(" ");
10457 }
10458 if (outStack != null) {
10459 outStack.append("$");
10460 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010461 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010462 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10463 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10464 }
10465 if (outStack != null) {
10466 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10467 }
10468 }
10469 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10470 outStack.append("(");
10471 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10472 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10473 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10474 outStack.append(":");
10475 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10476 }
10477 }
10478 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010479 }
10480 }
10481 }
10482 }
10483
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010484 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010485 pw.println();
10486 pw.println("Total PSS by process:");
10487 dumpMemItems(pw, " ", procMems, true);
10488 pw.println();
10489 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010490 pw.println("Total PSS by OOM adjustment:");
10491 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010492 if (!oomOnly) {
10493 PrintWriter out = categoryPw != null ? categoryPw : pw;
10494 out.println();
10495 out.println("Total PSS by category:");
10496 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010497 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010498 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010499 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010500 final int[] SINGLE_LONG_FORMAT = new int[] {
10501 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10502 };
10503 long[] longOut = new long[1];
10504 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10505 SINGLE_LONG_FORMAT, null, longOut, null);
10506 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10507 longOut[0] = 0;
10508 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10509 SINGLE_LONG_FORMAT, null, longOut, null);
10510 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10511 longOut[0] = 0;
10512 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10513 SINGLE_LONG_FORMAT, null, longOut, null);
10514 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10515 longOut[0] = 0;
10516 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10517 SINGLE_LONG_FORMAT, null, longOut, null);
10518 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10519 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10520 pw.print(shared); pw.println(" kB");
10521 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10522 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010524 }
10525
10526 /**
10527 * Searches array of arguments for the specified string
10528 * @param args array of argument strings
10529 * @param value value to search for
10530 * @return true if the value is contained in the array
10531 */
10532 private static boolean scanArgs(String[] args, String value) {
10533 if (args != null) {
10534 for (String arg : args) {
10535 if (value.equals(arg)) {
10536 return true;
10537 }
10538 }
10539 }
10540 return false;
10541 }
10542
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010543 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10544 ContentProviderRecord cpr, boolean always) {
10545 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10546
10547 if (!inLaunching || always) {
10548 synchronized (cpr) {
10549 cpr.launchingApp = null;
10550 cpr.notifyAll();
10551 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010552 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010553 String names[] = cpr.info.authority.split(";");
10554 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010555 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010556 }
10557 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010558
10559 for (int i=0; i<cpr.connections.size(); i++) {
10560 ContentProviderConnection conn = cpr.connections.get(i);
10561 if (conn.waiting) {
10562 // If this connection is waiting for the provider, then we don't
10563 // need to mess with its process unless we are always removing
10564 // or for some reason the provider is not currently launching.
10565 if (inLaunching && !always) {
10566 continue;
10567 }
10568 }
10569 ProcessRecord capp = conn.client;
10570 conn.dead = true;
10571 if (conn.stableCount > 0) {
10572 if (!capp.persistent && capp.thread != null
10573 && capp.pid != 0
10574 && capp.pid != MY_PID) {
10575 Slog.i(TAG, "Kill " + capp.processName
10576 + " (pid " + capp.pid + "): provider " + cpr.info.name
10577 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010578 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010579 capp.processName, capp.setAdj, "dying provider "
10580 + cpr.name.toShortString());
10581 Process.killProcessQuiet(capp.pid);
10582 }
10583 } else if (capp.thread != null && conn.provider.provider != null) {
10584 try {
10585 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10586 } catch (RemoteException e) {
10587 }
10588 // In the protocol here, we don't expect the client to correctly
10589 // clean up this connection, we'll just remove it.
10590 cpr.connections.remove(i);
10591 conn.client.conProviders.remove(conn);
10592 }
10593 }
10594
10595 if (inLaunching && always) {
10596 mLaunchingProviders.remove(cpr);
10597 }
10598 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 }
10600
10601 /**
10602 * Main code for cleaning up a process when it has gone away. This is
10603 * called both as a result of the process dying, or directly when stopping
10604 * a process when running in single process mode.
10605 */
10606 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010607 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010609 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010610 }
10611
Dianne Hackborn36124872009-10-08 16:22:03 -070010612 mProcessesToGc.remove(app);
10613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 // Dismiss any open dialogs.
10615 if (app.crashDialog != null) {
10616 app.crashDialog.dismiss();
10617 app.crashDialog = null;
10618 }
10619 if (app.anrDialog != null) {
10620 app.anrDialog.dismiss();
10621 app.anrDialog = null;
10622 }
10623 if (app.waitDialog != null) {
10624 app.waitDialog.dismiss();
10625 app.waitDialog = null;
10626 }
10627
10628 app.crashing = false;
10629 app.notResponding = false;
10630
10631 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010632 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 app.thread = null;
10634 app.forcingToForeground = null;
10635 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010636 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010637 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010638 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010640 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641
10642 boolean restart = false;
10643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010644 // Remove published content providers.
10645 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010646 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010647 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010648 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010649
10650 final boolean always = app.bad || !allowRestart;
10651 if (removeDyingProviderLocked(app, cpr, always) || always) {
10652 // We left the provider in the launching list, need to
10653 // restart it.
10654 restart = true;
10655 }
10656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010658 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010659 }
10660 app.pubProviders.clear();
10661 }
10662
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010663 // Take care of any launching providers waiting for this process.
10664 if (checkAppInLaunchingProvidersLocked(app, false)) {
10665 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 // Unregister from connected content providers.
10669 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010670 for (int i=0; i<app.conProviders.size(); i++) {
10671 ContentProviderConnection conn = app.conProviders.get(i);
10672 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 }
10674 app.conProviders.clear();
10675 }
10676
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010677 // At this point there may be remaining entries in mLaunchingProviders
10678 // where we were the only one waiting, so they are no longer of use.
10679 // Look for these and clean up if found.
10680 // XXX Commented out for now. Trying to figure out a way to reproduce
10681 // the actual situation to identify what is actually going on.
10682 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010683 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010684 ContentProviderRecord cpr = (ContentProviderRecord)
10685 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010686 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010687 synchronized (cpr) {
10688 cpr.launchingApp = null;
10689 cpr.notifyAll();
10690 }
10691 }
10692 }
10693 }
10694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010695 skipCurrentReceiverLocked(app);
10696
10697 // Unregister any receivers.
10698 if (app.receivers.size() > 0) {
10699 Iterator<ReceiverList> it = app.receivers.iterator();
10700 while (it.hasNext()) {
10701 removeReceiverLocked(it.next());
10702 }
10703 app.receivers.clear();
10704 }
10705
Christopher Tate181fafa2009-05-14 11:12:14 -070010706 // If the app is undergoing backup, tell the backup manager about it
10707 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010708 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10709 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010710 try {
10711 IBackupManager bm = IBackupManager.Stub.asInterface(
10712 ServiceManager.getService(Context.BACKUP_SERVICE));
10713 bm.agentDisconnected(app.info.packageName);
10714 } catch (RemoteException e) {
10715 // can't happen; backup manager is local
10716 }
10717 }
10718
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010719 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10720 ProcessChangeItem item = mPendingProcessChanges.get(i);
10721 if (item.pid == app.pid) {
10722 mPendingProcessChanges.remove(i);
10723 mAvailProcessChanges.add(item);
10724 }
10725 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010726 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728 // If the caller is restarting this app, then leave it in its
10729 // current lists and let the caller take care of it.
10730 if (restarting) {
10731 return;
10732 }
10733
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010734 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010735 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010737 mProcessNames.remove(app.processName, app.uid);
10738 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010739 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010740 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10741 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010742 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010744 } else if (!app.removed) {
10745 // This app is persistent, so we need to keep its record around.
10746 // If it is not already on the pending app list, add it there
10747 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010748 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10749 mPersistentStartingProcesses.add(app);
10750 restart = true;
10751 }
10752 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010753 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010754 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 mProcessesOnHold.remove(app);
10756
The Android Open Source Project4df24232009-03-05 14:34:35 -080010757 if (app == mHomeProcess) {
10758 mHomeProcess = null;
10759 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010760 if (app == mPreviousProcess) {
10761 mPreviousProcess = null;
10762 }
10763
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010764 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 // We have components that still need to be running in the
10766 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010767 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010768 startProcessLocked(app, "restart", app.processName);
10769 } else if (app.pid > 0 && app.pid != MY_PID) {
10770 // Goodbye!
10771 synchronized (mPidsSelfLocked) {
10772 mPidsSelfLocked.remove(app.pid);
10773 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10774 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010775 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 }
10777 }
10778
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010779 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10780 // Look through the content providers we are waiting to have launched,
10781 // and if any run in this process then either schedule a restart of
10782 // the process or kill the client waiting for it if this process has
10783 // gone bad.
10784 int NL = mLaunchingProviders.size();
10785 boolean restart = false;
10786 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010787 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010788 if (cpr.launchingApp == app) {
10789 if (!alwaysBad && !app.bad) {
10790 restart = true;
10791 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010792 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010793 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010794 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010795 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010796 }
10797 }
10798 }
10799 return restart;
10800 }
10801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 // =========================================================
10803 // SERVICES
10804 // =========================================================
10805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010806 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10807 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010808 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010810 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010811 }
10812 }
10813
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010814 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010815 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010816 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010817 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010818 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010819 }
10820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010822 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010823 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 // Refuse possible leaked file descriptors
10825 if (service != null && service.hasFileDescriptors() == true) {
10826 throw new IllegalArgumentException("File descriptors passed in Intent");
10827 }
10828
Amith Yamasani742a6712011-05-04 14:49:28 -070010829 if (DEBUG_SERVICE)
10830 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 synchronized(this) {
10832 final int callingPid = Binder.getCallingPid();
10833 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010834 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010835 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010836 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010837 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 Binder.restoreCallingIdentity(origId);
10839 return res;
10840 }
10841 }
10842
10843 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010844 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010846 if (DEBUG_SERVICE)
10847 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010849 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010850 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 Binder.restoreCallingIdentity(origId);
10852 return res;
10853 }
10854 }
10855
10856 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010857 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010858 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 // Refuse possible leaked file descriptors
10860 if (service != null && service.hasFileDescriptors() == true) {
10861 throw new IllegalArgumentException("File descriptors passed in Intent");
10862 }
10863
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010864 checkValidCaller(Binder.getCallingUid(), userId);
10865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010867 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 }
10870
10871 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010872 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 // Refuse possible leaked file descriptors
10874 if (service != null && service.hasFileDescriptors() == true) {
10875 throw new IllegalArgumentException("File descriptors passed in Intent");
10876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010877 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010878 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 }
10881
10882 public boolean stopServiceToken(ComponentName className, IBinder token,
10883 int startId) {
10884 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010885 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 }
10888
10889 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010890 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010892 mServices.setServiceForegroundLocked(className, token, id, notification,
10893 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 }
10895 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010896
Dianne Hackborn41203752012-08-31 14:05:51 -070010897 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10898 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010899 final int callingUserId = UserHandle.getUserId(callingUid);
10900 if (callingUserId != userId) {
10901 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10902 if ((requireFull || checkComponentPermission(
10903 android.Manifest.permission.INTERACT_ACROSS_USERS,
10904 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10905 && checkComponentPermission(
10906 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10907 callingPid, callingUid, -1, true)
10908 != PackageManager.PERMISSION_GRANTED) {
10909 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10910 // In this case, they would like to just execute as their
10911 // owner user instead of failing.
10912 userId = callingUserId;
10913 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010914 StringBuilder builder = new StringBuilder(128);
10915 builder.append("Permission Denial: ");
10916 builder.append(name);
10917 if (callerPackage != null) {
10918 builder.append(" from ");
10919 builder.append(callerPackage);
10920 }
10921 builder.append(" asks to run as user ");
10922 builder.append(userId);
10923 builder.append(" but is calling from user ");
10924 builder.append(UserHandle.getUserId(callingUid));
10925 builder.append("; this requires ");
10926 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10927 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010928 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010929 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10930 }
10931 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010932 Slog.w(TAG, msg);
10933 throw new SecurityException(msg);
10934 }
10935 }
10936 }
10937 if (userId == UserHandle.USER_CURRENT
10938 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070010939 // Note that we may be accessing this outside of a lock...
10940 // shouldn't be a big deal, if this is being called outside
10941 // of a locked context there is intrinsically a race with
10942 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010943 userId = mCurrentUserId;
10944 }
10945 if (!allowAll && userId < 0) {
10946 throw new IllegalArgumentException(
10947 "Call does not support special user #" + userId);
10948 }
10949 }
10950 return userId;
10951 }
10952
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010953 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10954 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010955 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010956 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010957 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10958 if (ActivityManager.checkUidPermission(
10959 android.Manifest.permission.INTERACT_ACROSS_USERS,
10960 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10961 ComponentName comp = new ComponentName(aInfo.packageName, className);
10962 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10963 + " requests FLAG_SINGLE_USER, but app does not hold "
10964 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10965 Slog.w(TAG, msg);
10966 throw new SecurityException(msg);
10967 }
10968 result = true;
10969 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010970 } else if (componentProcessName == aInfo.packageName) {
10971 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10972 } else if ("system".equals(componentProcessName)) {
10973 result = true;
10974 }
10975 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010976 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10977 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010978 }
10979 return result;
10980 }
10981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 public int bindService(IApplicationThread caller, IBinder token,
10983 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010984 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010985 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 // Refuse possible leaked file descriptors
10987 if (service != null && service.hasFileDescriptors() == true) {
10988 throw new IllegalArgumentException("File descriptors passed in Intent");
10989 }
10990
10991 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010992 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10993 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 }
10995 }
10996
10997 public boolean unbindService(IServiceConnection connection) {
10998 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010999 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 }
11002
11003 public void publishService(IBinder token, Intent intent, IBinder service) {
11004 // Refuse possible leaked file descriptors
11005 if (intent != null && intent.hasFileDescriptors() == true) {
11006 throw new IllegalArgumentException("File descriptors passed in Intent");
11007 }
11008
11009 synchronized(this) {
11010 if (!(token instanceof ServiceRecord)) {
11011 throw new IllegalArgumentException("Invalid service token");
11012 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011013 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014 }
11015 }
11016
11017 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11018 // Refuse possible leaked file descriptors
11019 if (intent != null && intent.hasFileDescriptors() == true) {
11020 throw new IllegalArgumentException("File descriptors passed in Intent");
11021 }
11022
11023 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011024 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 }
11026 }
11027
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011028 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 synchronized(this) {
11030 if (!(token instanceof ServiceRecord)) {
11031 throw new IllegalArgumentException("Invalid service token");
11032 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011033 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 }
11036
11037 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011038 // BACKUP AND RESTORE
11039 // =========================================================
11040
11041 // Cause the target app to be launched if necessary and its backup agent
11042 // instantiated. The backup agent will invoke backupAgentCreated() on the
11043 // activity manager to announce its creation.
11044 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011045 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011046 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11047
11048 synchronized(this) {
11049 // !!! TODO: currently no check here that we're already bound
11050 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11051 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11052 synchronized (stats) {
11053 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11054 }
11055
Dianne Hackborne7f97212011-02-24 14:40:20 -080011056 // Backup agent is now in use, its package can't be stopped.
11057 try {
11058 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011059 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011060 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011061 } catch (IllegalArgumentException e) {
11062 Slog.w(TAG, "Failed trying to unstop package "
11063 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011064 }
11065
Christopher Tate181fafa2009-05-14 11:12:14 -070011066 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011067 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11068 ? new ComponentName(app.packageName, app.backupAgentName)
11069 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011070 // startProcessLocked() returns existing proc's record if it's already running
11071 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011072 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011073 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011074 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011075 return false;
11076 }
11077
11078 r.app = proc;
11079 mBackupTarget = r;
11080 mBackupAppName = app.packageName;
11081
Christopher Tate6fa95972009-06-05 18:43:55 -070011082 // Try not to kill the process during backup
11083 updateOomAdjLocked(proc);
11084
Christopher Tate181fafa2009-05-14 11:12:14 -070011085 // If the process is already attached, schedule the creation of the backup agent now.
11086 // If it is not yet live, this will be done when it attaches to the framework.
11087 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011088 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011089 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011090 proc.thread.scheduleCreateBackupAgent(app,
11091 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011092 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011093 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011094 }
11095 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011096 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011097 }
11098 // Invariants: at this point, the target app process exists and the application
11099 // is either already running or in the process of coming up. mBackupTarget and
11100 // mBackupAppName describe the app, so that when it binds back to the AM we
11101 // know that it's scheduled for a backup-agent operation.
11102 }
11103
11104 return true;
11105 }
11106
11107 // A backup agent has just come up
11108 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011109 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011110 + " = " + agent);
11111
11112 synchronized(this) {
11113 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011114 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011115 return;
11116 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011117 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011118
Dianne Hackborn06740692010-09-22 22:46:21 -070011119 long oldIdent = Binder.clearCallingIdentity();
11120 try {
11121 IBackupManager bm = IBackupManager.Stub.asInterface(
11122 ServiceManager.getService(Context.BACKUP_SERVICE));
11123 bm.agentConnected(agentPackageName, agent);
11124 } catch (RemoteException e) {
11125 // can't happen; the backup manager service is local
11126 } catch (Exception e) {
11127 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11128 e.printStackTrace();
11129 } finally {
11130 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011131 }
11132 }
11133
11134 // done with this agent
11135 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011136 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011137 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011138 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011139 return;
11140 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011141
11142 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011143 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011144 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011145 return;
11146 }
11147
Christopher Tate181fafa2009-05-14 11:12:14 -070011148 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011149 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011150 return;
11151 }
11152
Christopher Tate6fa95972009-06-05 18:43:55 -070011153 ProcessRecord proc = mBackupTarget.app;
11154 mBackupTarget = null;
11155 mBackupAppName = null;
11156
11157 // Not backing this app up any more; reset its OOM adjustment
11158 updateOomAdjLocked(proc);
11159
Christopher Tatec7b31e32009-06-10 15:49:30 -070011160 // If the app crashed during backup, 'thread' will be null here
11161 if (proc.thread != null) {
11162 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011163 proc.thread.scheduleDestroyBackupAgent(appInfo,
11164 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011165 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011166 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011167 e.printStackTrace();
11168 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011169 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011170 }
11171 }
11172 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011173 // BROADCASTS
11174 // =========================================================
11175
Josh Bartel7f208742010-02-25 11:01:44 -060011176 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011177 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011179 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11180 if (stickies == null) {
11181 return cur;
11182 }
11183 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 if (list == null) {
11185 return cur;
11186 }
11187 int N = list.size();
11188 for (int i=0; i<N; i++) {
11189 Intent intent = list.get(i);
11190 if (filter.match(resolver, intent, true, TAG) >= 0) {
11191 if (cur == null) {
11192 cur = new ArrayList<Intent>();
11193 }
11194 cur.add(intent);
11195 }
11196 }
11197 return cur;
11198 }
11199
Christopher Tatef46723b2012-01-26 14:19:24 -080011200 boolean isPendingBroadcastProcessLocked(int pid) {
11201 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11202 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204
Christopher Tatef46723b2012-01-26 14:19:24 -080011205 void skipPendingBroadcastLocked(int pid) {
11206 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11207 for (BroadcastQueue queue : mBroadcastQueues) {
11208 queue.skipPendingBroadcastLocked(pid);
11209 }
11210 }
11211
11212 // The app just attached; send any pending broadcasts that it should receive
11213 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11214 boolean didSomething = false;
11215 for (BroadcastQueue queue : mBroadcastQueues) {
11216 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011218 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 }
11220
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011221 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011222 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011223 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011224 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011225 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011226 synchronized(this) {
11227 ProcessRecord callerApp = null;
11228 if (caller != null) {
11229 callerApp = getRecordForAppLocked(caller);
11230 if (callerApp == null) {
11231 throw new SecurityException(
11232 "Unable to find app for caller " + caller
11233 + " (pid=" + Binder.getCallingPid()
11234 + ") when registering receiver " + receiver);
11235 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011236 if (callerApp.info.uid != Process.SYSTEM_UID &&
11237 !callerApp.pkgList.contains(callerPackage)) {
11238 throw new SecurityException("Given caller package " + callerPackage
11239 + " is not running in process " + callerApp);
11240 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011241 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011242 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011243 } else {
11244 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011245 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011246 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011247 }
11248
Dianne Hackborn139748f2012-09-24 11:36:57 -070011249 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011250 true, true, "registerReceiver", callerPackage);
11251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 List allSticky = null;
11253
11254 // Look for any matching sticky broadcasts...
11255 Iterator actions = filter.actionsIterator();
11256 if (actions != null) {
11257 while (actions.hasNext()) {
11258 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011259 allSticky = getStickiesLocked(action, filter, allSticky,
11260 UserHandle.USER_ALL);
11261 allSticky = getStickiesLocked(action, filter, allSticky,
11262 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011263 }
11264 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011265 allSticky = getStickiesLocked(null, filter, allSticky,
11266 UserHandle.USER_ALL);
11267 allSticky = getStickiesLocked(null, filter, allSticky,
11268 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 }
11270
11271 // The first sticky in the list is returned directly back to
11272 // the client.
11273 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11274
Joe Onorato8a9b2202010-02-26 18:56:32 -080011275 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011276 + ": " + sticky);
11277
11278 if (receiver == null) {
11279 return sticky;
11280 }
11281
11282 ReceiverList rl
11283 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11284 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011285 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11286 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 if (rl.app != null) {
11288 rl.app.receivers.add(rl);
11289 } else {
11290 try {
11291 receiver.asBinder().linkToDeath(rl, 0);
11292 } catch (RemoteException e) {
11293 return sticky;
11294 }
11295 rl.linkedToDeath = true;
11296 }
11297 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011298 } else if (rl.uid != callingUid) {
11299 throw new IllegalArgumentException(
11300 "Receiver requested to register for uid " + callingUid
11301 + " was previously registered for uid " + rl.uid);
11302 } else if (rl.pid != callingPid) {
11303 throw new IllegalArgumentException(
11304 "Receiver requested to register for pid " + callingPid
11305 + " was previously registered for pid " + rl.pid);
11306 } else if (rl.userId != userId) {
11307 throw new IllegalArgumentException(
11308 "Receiver requested to register for user " + userId
11309 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011311 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011312 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 rl.add(bf);
11314 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011315 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316 }
11317 mReceiverResolver.addFilter(bf);
11318
11319 // Enqueue broadcasts for all existing stickies that match
11320 // this filter.
11321 if (allSticky != null) {
11322 ArrayList receivers = new ArrayList();
11323 receivers.add(bf);
11324
11325 int N = allSticky.size();
11326 for (int i=0; i<N; i++) {
11327 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011328 BroadcastQueue queue = broadcastQueueForIntent(intent);
11329 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011331 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011332 queue.enqueueParallelBroadcastLocked(r);
11333 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 }
11335 }
11336
11337 return sticky;
11338 }
11339 }
11340
11341 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011342 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343
Christopher Tatef46723b2012-01-26 14:19:24 -080011344 final long origId = Binder.clearCallingIdentity();
11345 try {
11346 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011347
Christopher Tatef46723b2012-01-26 14:19:24 -080011348 synchronized(this) {
11349 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011351 if (rl != null) {
11352 if (rl.curBroadcast != null) {
11353 BroadcastRecord r = rl.curBroadcast;
11354 final boolean doNext = finishReceiverLocked(
11355 receiver.asBinder(), r.resultCode, r.resultData,
11356 r.resultExtras, r.resultAbort, true);
11357 if (doNext) {
11358 doTrim = true;
11359 r.queue.processNextBroadcast(false);
11360 }
11361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362
Christopher Tatef46723b2012-01-26 14:19:24 -080011363 if (rl.app != null) {
11364 rl.app.receivers.remove(rl);
11365 }
11366 removeReceiverLocked(rl);
11367 if (rl.linkedToDeath) {
11368 rl.linkedToDeath = false;
11369 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011371 }
11372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373
Christopher Tatef46723b2012-01-26 14:19:24 -080011374 // If we actually concluded any broadcasts, we might now be able
11375 // to trim the recipients' apps from our working set
11376 if (doTrim) {
11377 trimApplications();
11378 return;
11379 }
11380
11381 } finally {
11382 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384 }
11385
11386 void removeReceiverLocked(ReceiverList rl) {
11387 mRegisteredReceivers.remove(rl.receiver.asBinder());
11388 int N = rl.size();
11389 for (int i=0; i<N; i++) {
11390 mReceiverResolver.removeFilter(rl.get(i));
11391 }
11392 }
11393
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011394 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011395 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11396 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011397 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011398 try {
11399 r.thread.dispatchPackageBroadcast(cmd, packages);
11400 } catch (RemoteException ex) {
11401 }
11402 }
11403 }
11404 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011405
11406 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11407 int[] users) {
11408 List<ResolveInfo> receivers = null;
11409 try {
11410 HashSet<ComponentName> singleUserReceivers = null;
11411 boolean scannedFirstReceivers = false;
11412 for (int user : users) {
11413 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11414 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011415 if (user != 0 && newReceivers != null) {
11416 // If this is not the primary user, we need to check for
11417 // any receivers that should be filtered out.
11418 for (int i=0; i<newReceivers.size(); i++) {
11419 ResolveInfo ri = newReceivers.get(i);
11420 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11421 newReceivers.remove(i);
11422 i--;
11423 }
11424 }
11425 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011426 if (newReceivers != null && newReceivers.size() == 0) {
11427 newReceivers = null;
11428 }
11429 if (receivers == null) {
11430 receivers = newReceivers;
11431 } else if (newReceivers != null) {
11432 // We need to concatenate the additional receivers
11433 // found with what we have do far. This would be easy,
11434 // but we also need to de-dup any receivers that are
11435 // singleUser.
11436 if (!scannedFirstReceivers) {
11437 // Collect any single user receivers we had already retrieved.
11438 scannedFirstReceivers = true;
11439 for (int i=0; i<receivers.size(); i++) {
11440 ResolveInfo ri = receivers.get(i);
11441 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11442 ComponentName cn = new ComponentName(
11443 ri.activityInfo.packageName, ri.activityInfo.name);
11444 if (singleUserReceivers == null) {
11445 singleUserReceivers = new HashSet<ComponentName>();
11446 }
11447 singleUserReceivers.add(cn);
11448 }
11449 }
11450 }
11451 // Add the new results to the existing results, tracking
11452 // and de-dupping single user receivers.
11453 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011454 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011455 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11456 ComponentName cn = new ComponentName(
11457 ri.activityInfo.packageName, ri.activityInfo.name);
11458 if (singleUserReceivers == null) {
11459 singleUserReceivers = new HashSet<ComponentName>();
11460 }
11461 if (!singleUserReceivers.contains(cn)) {
11462 singleUserReceivers.add(cn);
11463 receivers.add(ri);
11464 }
11465 } else {
11466 receivers.add(ri);
11467 }
11468 }
11469 }
11470 }
11471 } catch (RemoteException ex) {
11472 // pm is in same process, this will never happen.
11473 }
11474 return receivers;
11475 }
11476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 private final int broadcastIntentLocked(ProcessRecord callerApp,
11478 String callerPackage, Intent intent, String resolvedType,
11479 IIntentReceiver resultTo, int resultCode, String resultData,
11480 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011481 boolean ordered, boolean sticky, int callingPid, int callingUid,
11482 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 intent = new Intent(intent);
11484
Dianne Hackborne7f97212011-02-24 14:40:20 -080011485 // By default broadcasts do not go to stopped apps.
11486 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11487
Joe Onorato8a9b2202010-02-26 18:56:32 -080011488 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011490 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011492 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011494
Dianne Hackborn139748f2012-09-24 11:36:57 -070011495 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011496 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011497
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011498 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011499 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011500 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011501 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11502 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11503 Slog.w(TAG, "Skipping broadcast of " + intent
11504 + ": user " + userId + " is stopped");
11505 return ActivityManager.BROADCAST_SUCCESS;
11506 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011507 }
11508
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011509 /*
11510 * Prevent non-system code (defined here to be non-persistent
11511 * processes) from sending protected broadcasts.
11512 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011513 int callingAppId = UserHandle.getAppId(callingUid);
11514 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11515 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011516 callingUid == 0) {
11517 // Always okay.
11518 } else if (callerApp == null || !callerApp.persistent) {
11519 try {
11520 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11521 intent.getAction())) {
11522 String msg = "Permission Denial: not allowed to send broadcast "
11523 + intent.getAction() + " from pid="
11524 + callingPid + ", uid=" + callingUid;
11525 Slog.w(TAG, msg);
11526 throw new SecurityException(msg);
11527 }
11528 } catch (RemoteException e) {
11529 Slog.w(TAG, "Remote exception", e);
11530 return ActivityManager.BROADCAST_SUCCESS;
11531 }
11532 }
11533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534 // Handle special intents: if this broadcast is from the package
11535 // manager about a package being removed, we need to remove all of
11536 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011537 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011539 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11540 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011541 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011542 || uidRemoved) {
11543 if (checkComponentPermission(
11544 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011545 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 == PackageManager.PERMISSION_GRANTED) {
11547 if (uidRemoved) {
11548 final Bundle intentExtras = intent.getExtras();
11549 final int uid = intentExtras != null
11550 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11551 if (uid >= 0) {
11552 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11553 synchronized (bs) {
11554 bs.removeUidStatsLocked(uid);
11555 }
11556 }
11557 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011558 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011559 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011560 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011561 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11562 if (list != null && (list.length > 0)) {
11563 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011564 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011565 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011566 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011567 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011568 }
11569 } else {
11570 Uri data = intent.getData();
11571 String ssp;
11572 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11573 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11574 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011575 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11576 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011577 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011578 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011579 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011580 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 }
11583 }
11584 }
11585 } else {
11586 String msg = "Permission Denial: " + intent.getAction()
11587 + " broadcast from " + callerPackage + " (pid=" + callingPid
11588 + ", uid=" + callingUid + ")"
11589 + " requires "
11590 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011591 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592 throw new SecurityException(msg);
11593 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011594
11595 // Special case for adding a package: by default turn on compatibility
11596 // mode.
11597 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011598 Uri data = intent.getData();
11599 String ssp;
11600 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11601 mCompatModePackages.handlePackageAddedLocked(ssp,
11602 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604 }
11605
11606 /*
11607 * If this is the time zone changed action, queue up a message that will reset the timezone
11608 * of all currently running processes. This message will get queued up before the broadcast
11609 * happens.
11610 */
11611 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11612 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11613 }
11614
Robert Greenwalt03595d02010-11-02 14:08:23 -070011615 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11616 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11617 }
11618
Robert Greenwalt434203a2010-10-11 16:00:27 -070011619 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11620 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11621 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11622 }
11623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 // Add to the sticky list if requested.
11625 if (sticky) {
11626 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11627 callingPid, callingUid)
11628 != PackageManager.PERMISSION_GRANTED) {
11629 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11630 + callingPid + ", uid=" + callingUid
11631 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011632 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 throw new SecurityException(msg);
11634 }
11635 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011636 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011637 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011638 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011639 }
11640 if (intent.getComponent() != null) {
11641 throw new SecurityException(
11642 "Sticky broadcasts can't target a specific component");
11643 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011644 // We use userId directly here, since the "all" target is maintained
11645 // as a separate set of sticky broadcasts.
11646 if (userId != UserHandle.USER_ALL) {
11647 // But first, if this is not a broadcast to all users, then
11648 // make sure it doesn't conflict with an existing broadcast to
11649 // all users.
11650 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11651 UserHandle.USER_ALL);
11652 if (stickies != null) {
11653 ArrayList<Intent> list = stickies.get(intent.getAction());
11654 if (list != null) {
11655 int N = list.size();
11656 int i;
11657 for (i=0; i<N; i++) {
11658 if (intent.filterEquals(list.get(i))) {
11659 throw new IllegalArgumentException(
11660 "Sticky broadcast " + intent + " for user "
11661 + userId + " conflicts with existing global broadcast");
11662 }
11663 }
11664 }
11665 }
11666 }
11667 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11668 if (stickies == null) {
11669 stickies = new HashMap<String, ArrayList<Intent>>();
11670 mStickyBroadcasts.put(userId, stickies);
11671 }
11672 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011673 if (list == null) {
11674 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011675 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011676 }
11677 int N = list.size();
11678 int i;
11679 for (i=0; i<N; i++) {
11680 if (intent.filterEquals(list.get(i))) {
11681 // This sticky already exists, replace it.
11682 list.set(i, new Intent(intent));
11683 break;
11684 }
11685 }
11686 if (i >= N) {
11687 list.add(new Intent(intent));
11688 }
11689 }
11690
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011691 int[] users;
11692 if (userId == UserHandle.USER_ALL) {
11693 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011694 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011695 } else {
11696 // Caller wants broadcast to go to one specific user.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011697 users = mCurrentUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011698 }
11699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011700 // Figure out who all will receive this broadcast.
11701 List receivers = null;
11702 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011703 // Need to resolve the intent to interested receivers...
11704 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11705 == 0) {
11706 receivers = collectReceiverComponents(intent, resolvedType, users);
11707 }
11708 if (intent.getComponent() == null) {
11709 registeredReceivers = mReceiverResolver.queryIntent(intent,
11710 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 }
11712
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011713 final boolean replacePending =
11714 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11715
Joe Onorato8a9b2202010-02-26 18:56:32 -080011716 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011717 + " replacePending=" + replacePending);
11718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11720 if (!ordered && NR > 0) {
11721 // If we are not serializing this broadcast, then send the
11722 // registered receivers separately so they don't wait for the
11723 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011724 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11725 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726 callerPackage, callingPid, callingUid, requiredPermission,
11727 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011728 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011729 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011730 TAG, "Enqueueing parallel broadcast " + r);
11731 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011732 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011733 queue.enqueueParallelBroadcastLocked(r);
11734 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011736 registeredReceivers = null;
11737 NR = 0;
11738 }
11739
11740 // Merge into one list.
11741 int ir = 0;
11742 if (receivers != null) {
11743 // A special case for PACKAGE_ADDED: do not allow the package
11744 // being added to see this broadcast. This prevents them from
11745 // using this as a back door to get run as soon as they are
11746 // installed. Maybe in the future we want to have a special install
11747 // broadcast or such for apps, but we'd like to deliberately make
11748 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011749 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011750 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11751 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11752 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011753 Uri data = intent.getData();
11754 if (data != null) {
11755 String pkgName = data.getSchemeSpecificPart();
11756 if (pkgName != null) {
11757 skipPackages = new String[] { pkgName };
11758 }
11759 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011760 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011761 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011762 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011763 if (skipPackages != null && (skipPackages.length > 0)) {
11764 for (String skipPackage : skipPackages) {
11765 if (skipPackage != null) {
11766 int NT = receivers.size();
11767 for (int it=0; it<NT; it++) {
11768 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11769 if (curt.activityInfo.packageName.equals(skipPackage)) {
11770 receivers.remove(it);
11771 it--;
11772 NT--;
11773 }
11774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011775 }
11776 }
11777 }
11778
11779 int NT = receivers != null ? receivers.size() : 0;
11780 int it = 0;
11781 ResolveInfo curt = null;
11782 BroadcastFilter curr = null;
11783 while (it < NT && ir < NR) {
11784 if (curt == null) {
11785 curt = (ResolveInfo)receivers.get(it);
11786 }
11787 if (curr == null) {
11788 curr = registeredReceivers.get(ir);
11789 }
11790 if (curr.getPriority() >= curt.priority) {
11791 // Insert this broadcast record into the final list.
11792 receivers.add(it, curr);
11793 ir++;
11794 curr = null;
11795 it++;
11796 NT++;
11797 } else {
11798 // Skip to the next ResolveInfo in the final list.
11799 it++;
11800 curt = null;
11801 }
11802 }
11803 }
11804 while (ir < NR) {
11805 if (receivers == null) {
11806 receivers = new ArrayList();
11807 }
11808 receivers.add(registeredReceivers.get(ir));
11809 ir++;
11810 }
11811
11812 if ((receivers != null && receivers.size() > 0)
11813 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011814 BroadcastQueue queue = broadcastQueueForIntent(intent);
11815 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011816 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011817 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011818 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011819 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011821 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 if (DEBUG_BROADCAST) {
11823 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011824 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011825 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011826 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011827 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011828 queue.enqueueOrderedBroadcastLocked(r);
11829 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831 }
11832
Dianne Hackborna4972e92012-03-14 10:38:05 -070011833 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 }
11835
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011836 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 // Refuse possible leaked file descriptors
11838 if (intent != null && intent.hasFileDescriptors() == true) {
11839 throw new IllegalArgumentException("File descriptors passed in Intent");
11840 }
11841
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011842 int flags = intent.getFlags();
11843
11844 if (!mProcessesReady) {
11845 // if the caller really truly claims to know what they're doing, go
11846 // ahead and allow the broadcast without launching any receivers
11847 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11848 intent = new Intent(intent);
11849 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11850 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11851 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11852 + " before boot completion");
11853 throw new IllegalStateException("Cannot broadcast before boot completed");
11854 }
11855 }
11856
11857 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11858 throw new IllegalArgumentException(
11859 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11860 }
11861
11862 return intent;
11863 }
11864
11865 public final int broadcastIntent(IApplicationThread caller,
11866 Intent intent, String resolvedType, IIntentReceiver resultTo,
11867 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011868 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011869 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011870 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011871 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011873 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11874 final int callingPid = Binder.getCallingPid();
11875 final int callingUid = Binder.getCallingUid();
11876 final long origId = Binder.clearCallingIdentity();
11877 int res = broadcastIntentLocked(callerApp,
11878 callerApp != null ? callerApp.info.packageName : null,
11879 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011880 resultCode, resultData, map, requiredPermission, serialized, sticky,
11881 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011882 Binder.restoreCallingIdentity(origId);
11883 return res;
11884 }
11885 }
11886
11887 int broadcastIntentInPackage(String packageName, int uid,
11888 Intent intent, String resolvedType, IIntentReceiver resultTo,
11889 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011890 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011892 intent = verifyBroadcastLocked(intent);
11893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894 final long origId = Binder.clearCallingIdentity();
11895 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11896 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011897 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011898 Binder.restoreCallingIdentity(origId);
11899 return res;
11900 }
11901 }
11902
Amith Yamasani742a6712011-05-04 14:49:28 -070011903 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 // Refuse possible leaked file descriptors
11905 if (intent != null && intent.hasFileDescriptors() == true) {
11906 throw new IllegalArgumentException("File descriptors passed in Intent");
11907 }
11908
Dianne Hackborn139748f2012-09-24 11:36:57 -070011909 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011910 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011912 synchronized(this) {
11913 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11914 != PackageManager.PERMISSION_GRANTED) {
11915 String msg = "Permission Denial: unbroadcastIntent() from pid="
11916 + Binder.getCallingPid()
11917 + ", uid=" + Binder.getCallingUid()
11918 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011919 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920 throw new SecurityException(msg);
11921 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011922 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11923 if (stickies != null) {
11924 ArrayList<Intent> list = stickies.get(intent.getAction());
11925 if (list != null) {
11926 int N = list.size();
11927 int i;
11928 for (i=0; i<N; i++) {
11929 if (intent.filterEquals(list.get(i))) {
11930 list.remove(i);
11931 break;
11932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011934 if (list.size() <= 0) {
11935 stickies.remove(intent.getAction());
11936 }
11937 }
11938 if (stickies.size() <= 0) {
11939 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 }
11941 }
11942 }
11943 }
11944
11945 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11946 String resultData, Bundle resultExtras, boolean resultAbort,
11947 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011948 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11949 if (r == null) {
11950 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951 return false;
11952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011953
Christopher Tatef46723b2012-01-26 14:19:24 -080011954 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11955 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 }
11957
11958 public void finishReceiver(IBinder who, int resultCode, String resultData,
11959 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011960 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961
11962 // Refuse possible leaked file descriptors
11963 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11964 throw new IllegalArgumentException("File descriptors passed in Bundle");
11965 }
11966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011967 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011968 try {
11969 boolean doNext = false;
11970 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011971
Christopher Tatef46723b2012-01-26 14:19:24 -080011972 synchronized(this) {
11973 r = broadcastRecordForReceiverLocked(who);
11974 if (r != null) {
11975 doNext = r.queue.finishReceiverLocked(r, resultCode,
11976 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011979
Christopher Tatef46723b2012-01-26 14:19:24 -080011980 if (doNext) {
11981 r.queue.processNextBroadcast(false);
11982 }
11983 trimApplications();
11984 } finally {
11985 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011989 // =========================================================
11990 // INSTRUMENTATION
11991 // =========================================================
11992
11993 public boolean startInstrumentation(ComponentName className,
11994 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011995 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011996 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070011997 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011998 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011999 // Refuse possible leaked file descriptors
12000 if (arguments != null && arguments.hasFileDescriptors()) {
12001 throw new IllegalArgumentException("File descriptors passed in Bundle");
12002 }
12003
12004 synchronized(this) {
12005 InstrumentationInfo ii = null;
12006 ApplicationInfo ai = null;
12007 try {
12008 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012009 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012010 ai = AppGlobals.getPackageManager().getApplicationInfo(
12011 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012012 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012013 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 }
12015 if (ii == null) {
12016 reportStartInstrumentationFailure(watcher, className,
12017 "Unable to find instrumentation info for: " + className);
12018 return false;
12019 }
12020 if (ai == null) {
12021 reportStartInstrumentationFailure(watcher, className,
12022 "Unable to find instrumentation target package: " + ii.targetPackage);
12023 return false;
12024 }
12025
12026 int match = mContext.getPackageManager().checkSignatures(
12027 ii.targetPackage, ii.packageName);
12028 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12029 String msg = "Permission Denial: starting instrumentation "
12030 + className + " from pid="
12031 + Binder.getCallingPid()
12032 + ", uid=" + Binder.getCallingPid()
12033 + " not allowed because package " + ii.packageName
12034 + " does not have a signature matching the target "
12035 + ii.targetPackage;
12036 reportStartInstrumentationFailure(watcher, className, msg);
12037 throw new SecurityException(msg);
12038 }
12039
12040 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012041 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012042 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012043 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012045 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 app.instrumentationProfileFile = profileFile;
12047 app.instrumentationArguments = arguments;
12048 app.instrumentationWatcher = watcher;
12049 app.instrumentationResultClass = className;
12050 Binder.restoreCallingIdentity(origId);
12051 }
12052
12053 return true;
12054 }
12055
12056 /**
12057 * Report errors that occur while attempting to start Instrumentation. Always writes the
12058 * error to the logs, but if somebody is watching, send the report there too. This enables
12059 * the "am" command to report errors with more information.
12060 *
12061 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12062 * @param cn The component name of the instrumentation.
12063 * @param report The error report.
12064 */
12065 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12066 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012067 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012068 try {
12069 if (watcher != null) {
12070 Bundle results = new Bundle();
12071 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12072 results.putString("Error", report);
12073 watcher.instrumentationStatus(cn, -1, results);
12074 }
12075 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012076 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012077 }
12078 }
12079
12080 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12081 if (app.instrumentationWatcher != null) {
12082 try {
12083 // NOTE: IInstrumentationWatcher *must* be oneway here
12084 app.instrumentationWatcher.instrumentationFinished(
12085 app.instrumentationClass,
12086 resultCode,
12087 results);
12088 } catch (RemoteException e) {
12089 }
12090 }
12091 app.instrumentationWatcher = null;
12092 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012093 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012094 app.instrumentationProfileFile = null;
12095 app.instrumentationArguments = null;
12096
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012097 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012098 }
12099
12100 public void finishInstrumentation(IApplicationThread target,
12101 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012102 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 // Refuse possible leaked file descriptors
12104 if (results != null && results.hasFileDescriptors()) {
12105 throw new IllegalArgumentException("File descriptors passed in Intent");
12106 }
12107
12108 synchronized(this) {
12109 ProcessRecord app = getRecordForAppLocked(target);
12110 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012111 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112 return;
12113 }
12114 final long origId = Binder.clearCallingIdentity();
12115 finishInstrumentationLocked(app, resultCode, results);
12116 Binder.restoreCallingIdentity(origId);
12117 }
12118 }
12119
12120 // =========================================================
12121 // CONFIGURATION
12122 // =========================================================
12123
12124 public ConfigurationInfo getDeviceConfigurationInfo() {
12125 ConfigurationInfo config = new ConfigurationInfo();
12126 synchronized (this) {
12127 config.reqTouchScreen = mConfiguration.touchscreen;
12128 config.reqKeyboardType = mConfiguration.keyboard;
12129 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012130 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12131 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12133 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012134 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12135 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012136 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12137 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012138 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012139 }
12140 return config;
12141 }
12142
12143 public Configuration getConfiguration() {
12144 Configuration ci;
12145 synchronized(this) {
12146 ci = new Configuration(mConfiguration);
12147 }
12148 return ci;
12149 }
12150
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012151 public void updatePersistentConfiguration(Configuration values) {
12152 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12153 "updateConfiguration()");
12154 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12155 "updateConfiguration()");
12156 if (values == null) {
12157 throw new NullPointerException("Configuration must not be null");
12158 }
12159
12160 synchronized(this) {
12161 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012162 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012163 Binder.restoreCallingIdentity(origId);
12164 }
12165 }
12166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012167 public void updateConfiguration(Configuration values) {
12168 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12169 "updateConfiguration()");
12170
12171 synchronized(this) {
12172 if (values == null && mWindowManager != null) {
12173 // sentinel: fetch the current configuration from the window manager
12174 values = mWindowManager.computeNewConfiguration();
12175 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012176
12177 if (mWindowManager != null) {
12178 mProcessList.applyDisplaySize(mWindowManager);
12179 }
12180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012181 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012182 if (values != null) {
12183 Settings.System.clearConfiguration(values);
12184 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012185 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 Binder.restoreCallingIdentity(origId);
12187 }
12188 }
12189
12190 /**
12191 * Do either or both things: (1) change the current configuration, and (2)
12192 * make sure the given activity is running with the (now) current
12193 * configuration. Returns true if the activity has been left running, or
12194 * false if <var>starting</var> is being destroyed to match the new
12195 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012196 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012198 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012199 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012200 // do nothing if we are headless
12201 if (mHeadless) return true;
12202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012203 int changes = 0;
12204
12205 boolean kept = true;
12206
12207 if (values != null) {
12208 Configuration newConfig = new Configuration(mConfiguration);
12209 changes = newConfig.updateFrom(values);
12210 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012211 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012212 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 }
12214
Doug Zongker2bec3d42009-12-04 12:52:44 -080012215 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012216
Dianne Hackborn813075a62011-11-14 17:45:19 -080012217 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 saveLocaleLocked(values.locale,
12219 !values.locale.equals(mConfiguration.locale),
12220 values.userSetLocale);
12221 }
12222
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012223 mConfigurationSeq++;
12224 if (mConfigurationSeq <= 0) {
12225 mConfigurationSeq = 1;
12226 }
12227 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012229 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012230
12231 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012232
12233 // TODO: If our config changes, should we auto dismiss any currently
12234 // showing dialogs?
12235 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012236
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012237 AttributeCache ac = AttributeCache.instance();
12238 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012239 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012241
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012242 // Make sure all resources in our process are updated
12243 // right now, so that anyone who is going to retrieve
12244 // resource values after we return will be sure to get
12245 // the new ones. This is especially important during
12246 // boot, where the first config change needs to guarantee
12247 // all resources have that config before following boot
12248 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012249 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012250
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012251 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012252 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012253 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012254 mHandler.sendMessage(msg);
12255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012257 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12258 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012259 try {
12260 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012261 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012262 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012263 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012264 }
12265 } catch (Exception e) {
12266 }
12267 }
12268 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012269 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012270 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12271 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012272 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012273 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012274 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012275 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12276 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12277 broadcastIntentLocked(null, null, intent,
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012278 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012279 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012281 }
12282 }
12283
12284 if (changes != 0 && starting == null) {
12285 // If the configuration changed, and the caller is not already
12286 // in the process of starting an activity, then find the top
12287 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012288 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289 }
12290
12291 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012292 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012293 // And we need to make sure at this point that all other activities
12294 // are made visible with the correct configuration.
12295 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012296 }
12297
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012298 if (values != null && mWindowManager != null) {
12299 mWindowManager.setNewConfiguration(mConfiguration);
12300 }
12301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012302 return kept;
12303 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012304
12305 /**
12306 * Decide based on the configuration whether we should shouw the ANR,
12307 * crash, etc dialogs. The idea is that if there is no affordnace to
12308 * press the on-screen buttons, we shouldn't show the dialog.
12309 *
12310 * A thought: SystemUI might also want to get told about this, the Power
12311 * dialog / global actions also might want different behaviors.
12312 */
12313 private static final boolean shouldShowDialogs(Configuration config) {
12314 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12315 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012317
12318 /**
12319 * Save the locale. You must be inside a synchronized (this) block.
12320 */
12321 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12322 if(isDiff) {
12323 SystemProperties.set("user.language", l.getLanguage());
12324 SystemProperties.set("user.region", l.getCountry());
12325 }
12326
12327 if(isPersist) {
12328 SystemProperties.set("persist.sys.language", l.getLanguage());
12329 SystemProperties.set("persist.sys.country", l.getCountry());
12330 SystemProperties.set("persist.sys.localevar", l.getVariant());
12331 }
12332 }
12333
Adam Powelldd8fab22012-03-22 17:47:27 -070012334 @Override
12335 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12336 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012337 return srec != null && srec.task.affinity != null &&
12338 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012339 }
12340
12341 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12342 Intent resultData) {
12343 ComponentName dest = destIntent.getComponent();
12344
12345 synchronized (this) {
12346 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012347 if (srec == null) {
12348 return false;
12349 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012350 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12351 final int start = history.indexOf(srec);
12352 if (start < 0) {
12353 // Current activity is not in history stack; do nothing.
12354 return false;
12355 }
12356 int finishTo = start - 1;
12357 ActivityRecord parent = null;
12358 boolean foundParentInTask = false;
12359 if (dest != null) {
12360 TaskRecord tr = srec.task;
12361 for (int i = start - 1; i >= 0; i--) {
12362 ActivityRecord r = history.get(i);
12363 if (tr != r.task) {
12364 // Couldn't find parent in the same task; stop at the one above this.
12365 // (Root of current task; in-app "home" behavior)
12366 // Always at least finish the current activity.
12367 finishTo = Math.min(start - 1, i + 1);
12368 parent = history.get(finishTo);
12369 break;
12370 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12371 r.info.name.equals(dest.getClassName())) {
12372 finishTo = i;
12373 parent = r;
12374 foundParentInTask = true;
12375 break;
12376 }
12377 }
12378 }
12379
12380 if (mController != null) {
12381 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12382 if (next != null) {
12383 // ask watcher if this is allowed
12384 boolean resumeOK = true;
12385 try {
12386 resumeOK = mController.activityResuming(next.packageName);
12387 } catch (RemoteException e) {
12388 mController = null;
12389 }
12390
12391 if (!resumeOK) {
12392 return false;
12393 }
12394 }
12395 }
12396 final long origId = Binder.clearCallingIdentity();
12397 for (int i = start; i > finishTo; i--) {
12398 ActivityRecord r = history.get(i);
12399 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012400 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012401 // Only return the supplied result for the first activity finished
12402 resultCode = Activity.RESULT_CANCELED;
12403 resultData = null;
12404 }
12405
12406 if (parent != null && foundParentInTask) {
12407 final int parentLaunchMode = parent.info.launchMode;
12408 final int destIntentFlags = destIntent.getFlags();
12409 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12410 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12411 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12412 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012413 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012414 } else {
12415 try {
12416 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012417 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012418 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12419 null, aInfo, parent.appToken, null,
12420 0, -1, parent.launchedFromUid, 0, null, true, null);
12421 foundParentInTask = res == ActivityManager.START_SUCCESS;
12422 } catch (RemoteException e) {
12423 foundParentInTask = false;
12424 }
12425 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012426 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012427 }
12428 }
12429 Binder.restoreCallingIdentity(origId);
12430 return foundParentInTask;
12431 }
12432 }
12433
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012434 public int getLaunchedFromUid(IBinder activityToken) {
12435 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12436 if (srec == null) {
12437 return -1;
12438 }
12439 return srec.launchedFromUid;
12440 }
12441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442 // =========================================================
12443 // LIFETIME MANAGEMENT
12444 // =========================================================
12445
Christopher Tatef46723b2012-01-26 14:19:24 -080012446 // Returns which broadcast queue the app is the current [or imminent] receiver
12447 // on, or 'null' if the app is not an active broadcast recipient.
12448 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12449 BroadcastRecord r = app.curReceiver;
12450 if (r != null) {
12451 return r.queue;
12452 }
12453
12454 // It's not the current receiver, but it might be starting up to become one
12455 synchronized (this) {
12456 for (BroadcastQueue queue : mBroadcastQueues) {
12457 r = queue.mPendingBroadcast;
12458 if (r != null && r.curApp == app) {
12459 // found it; report which queue it's in
12460 return queue;
12461 }
12462 }
12463 }
12464
12465 return null;
12466 }
12467
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012468 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012469 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012471 // This adjustment has already been computed. If we are calling
12472 // from the top, we may have already computed our adjustment with
12473 // an earlier hidden adjustment that isn't really for us... if
12474 // so, use the new hidden adjustment.
12475 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012476 if (app.hasActivities) {
12477 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12478 } else if (app.hasClientActivities) {
12479 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12480 } else {
12481 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12482 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012483 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012484 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012485 }
12486
12487 if (app.thread == null) {
12488 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012489 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012490 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 }
12492
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012493 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12494 app.adjSource = null;
12495 app.adjTarget = null;
12496 app.empty = false;
12497 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012498 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012499
12500 final int activitiesSize = app.activities.size();
12501
Dianne Hackborn7d608422011-08-07 16:24:18 -070012502 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012503 // The max adjustment doesn't allow this app to be anything
12504 // below foreground, so it is not worth doing work for it.
12505 app.adjType = "fixed";
12506 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012507 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012508 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012509 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012510 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012511 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012512 // System process can do UI, and when they do we want to have
12513 // them trim their memory after the user leaves the UI. To
12514 // facilitate this, here we need to determine whether or not it
12515 // is currently showing UI.
12516 app.systemNoUi = true;
12517 if (app == TOP_APP) {
12518 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012519 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012520 } else if (activitiesSize > 0) {
12521 for (int j = 0; j < activitiesSize; j++) {
12522 final ActivityRecord r = app.activities.get(j);
12523 if (r.visible) {
12524 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012525 }
12526 if (r.app == app) {
12527 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012528 }
12529 }
12530 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012531 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012532 }
12533
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012534 app.keeping = false;
12535 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012536 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012537
The Android Open Source Project4df24232009-03-05 14:34:35 -080012538 // Determine the importance of the process, starting with most
12539 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012541 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012542 boolean foregroundActivities = false;
12543 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012544 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012545 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012546 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012547 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012548 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012549 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012550 foregroundActivities = true;
12551 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012552 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012553 } else if (app.instrumentationClass != null) {
12554 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012555 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012556 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012557 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012558 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012559 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012560 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012561 // counts as being in the foreground for OOM killer purposes.
12562 // It's placed in a sched group based on the nature of the
12563 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012564 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012565 schedGroup = (queue == mFgBroadcastQueue)
12566 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012567 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012568 } else if (app.executingServices.size() > 0) {
12569 // An app that is currently executing a service callback also
12570 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012571 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012572 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012573 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012574 } else {
12575 // Assume process is hidden (has activities); we will correct
12576 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012577 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012578 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012579 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012580 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012581 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012582
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012583 boolean hasStoppingActivities = false;
12584
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012585 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012586 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012587 for (int j = 0; j < activitiesSize; j++) {
12588 final ActivityRecord r = app.activities.get(j);
12589 if (r.visible) {
12590 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012591 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12592 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012593 app.adjType = "visible";
12594 }
12595 schedGroup = Process.THREAD_GROUP_DEFAULT;
12596 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012597 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012598 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012599 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012600 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012601 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12602 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012603 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012604 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012605 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012606 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012607 } else if (r.state == ActivityState.STOPPING) {
12608 // We will apply the actual adjustment later, because
12609 // we want to allow this process to immediately go through
12610 // any memory trimming that is in effect.
12611 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012612 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012613 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012614 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012615 if (r.app == app) {
12616 app.hasActivities = true;
12617 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012618 }
12619 }
12620
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012621 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012622 if (app.hasClientActivities) {
12623 adj = clientHiddenAdj;
12624 app.adjType = "bg-client-act";
12625 } else {
12626 // Whoops, this process is completely empty as far as we know
12627 // at this point.
12628 adj = emptyAdj;
12629 app.empty = true;
12630 app.adjType = "bg-empty";
12631 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012632 }
12633
Dianne Hackborn7d608422011-08-07 16:24:18 -070012634 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012635 if (app.foregroundServices) {
12636 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012637 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012638 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012639 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012640 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012641 } else if (app.forcingToForeground != null) {
12642 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012643 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012644 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012645 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012646 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012647 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012648 }
12649 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012650
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012651 if (app.foregroundServices) {
12652 interesting = true;
12653 }
12654
Dianne Hackborn7d608422011-08-07 16:24:18 -070012655 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012656 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012657 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012658 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012659 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012660 app.adjType = "heavy";
12661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012662
Dianne Hackborn7d608422011-08-07 16:24:18 -070012663 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012664 // This process is hosting what we currently consider to be the
12665 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012666 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012667 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012668 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012669 app.adjType = "home";
12670 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012671
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012672 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12673 && app.activities.size() > 0) {
12674 // This was the previous process that showed UI to the user.
12675 // We want to try to keep it around more aggressively, to give
12676 // a good experience around switching between two apps.
12677 adj = ProcessList.PREVIOUS_APP_ADJ;
12678 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12679 app.hidden = false;
12680 app.adjType = "previous";
12681 }
12682
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012683 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12684 + " reason=" + app.adjType);
12685
The Android Open Source Project4df24232009-03-05 14:34:35 -080012686 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 // there are applications dependent on our services or providers, but
12688 // this gives us a baseline and makes sure we don't get into an
12689 // infinite recursion.
12690 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012691 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012692
Christopher Tate6fa95972009-06-05 18:43:55 -070012693 if (mBackupTarget != null && app == mBackupTarget.app) {
12694 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012695 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012696 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012697 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012698 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012699 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012700 }
12701 }
12702
Dianne Hackborn7d608422011-08-07 16:24:18 -070012703 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012704 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012705 final long now = SystemClock.uptimeMillis();
12706 // This process is more important if the top activity is
12707 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012708 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012709 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012710 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012711 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012712 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012713 // If this process has shown some UI, let it immediately
12714 // go to the LRU list because it may be pretty heavy with
12715 // UI stuff. We'll tag it with a label just to help
12716 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012717 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012718 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012719 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012720 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012721 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012722 // This service has seen some activity within
12723 // recent memory, so we will keep its process ahead
12724 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012725 if (adj > ProcessList.SERVICE_ADJ) {
12726 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012727 app.adjType = "started-services";
12728 app.hidden = false;
12729 }
12730 }
12731 // If we have let the service slide into the background
12732 // state, still have some text describing what it is doing
12733 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012734 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012735 app.adjType = "started-bg-services";
12736 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012737 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012738 // Don't kill this process because it is doing work; it
12739 // has said it is doing work.
12740 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012741 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012742 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012743 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012744 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012746 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012747 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012748 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012749 // XXX should compute this based on the max of
12750 // all connected clients.
12751 ConnectionRecord cr = clist.get(i);
12752 if (cr.binding.client == app) {
12753 // Binding to ourself is not interesting.
12754 continue;
12755 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012756 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012757 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012758 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012759 int myHiddenAdj = hiddenAdj;
12760 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012761 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012762 myHiddenAdj = client.hiddenAdj;
12763 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012764 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012765 }
12766 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012767 int myClientHiddenAdj = clientHiddenAdj;
12768 if (myClientHiddenAdj > client.clientHiddenAdj) {
12769 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12770 myClientHiddenAdj = client.clientHiddenAdj;
12771 } else {
12772 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12773 }
12774 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012775 int myEmptyAdj = emptyAdj;
12776 if (myEmptyAdj > client.emptyAdj) {
12777 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12778 myEmptyAdj = client.emptyAdj;
12779 } else {
12780 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12781 }
12782 }
12783 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012784 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012785 String adjType = null;
12786 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12787 // Not doing bind OOM management, so treat
12788 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012789 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012790 // If this process has shown some UI, let it immediately
12791 // go to the LRU list because it may be pretty heavy with
12792 // UI stuff. We'll tag it with a label just to help
12793 // debug and understand what is going on.
12794 if (adj > clientAdj) {
12795 adjType = "bound-bg-ui-services";
12796 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012797 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012798 clientAdj = adj;
12799 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012800 if (now >= (s.lastActivity
12801 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012802 // This service has not seen activity within
12803 // recent memory, so allow it to drop to the
12804 // LRU list if there is no other reason to keep
12805 // it around. We'll also tag it with a label just
12806 // to help debug and undertand what is going on.
12807 if (adj > clientAdj) {
12808 adjType = "bound-bg-services";
12809 }
12810 clientAdj = adj;
12811 }
12812 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012813 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12814 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12815 // If this connection is keeping the service
12816 // created, then we want to try to better follow
12817 // its memory management semantics for activities.
12818 // That is, if it is sitting in the background
12819 // LRU list as a hidden process (with activities),
12820 // we don't want the service it is connected to
12821 // to go into the empty LRU and quickly get killed,
12822 // because I'll we'll do is just end up restarting
12823 // the service.
12824 app.hasClientActivities |= client.hasActivities;
12825 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012826 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012827 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012828 // If this process has recently shown UI, and
12829 // the process that is binding to it is less
12830 // important than being visible, then we don't
12831 // care about the binding as much as we care
12832 // about letting this process get into the LRU
12833 // list to be killed and restarted if needed for
12834 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012835 if (app.hasShownUi && app != mHomeProcess
12836 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012837 adjType = "bound-bg-ui-services";
12838 } else {
12839 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12840 |Context.BIND_IMPORTANT)) != 0) {
12841 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012842 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12843 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12844 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12845 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12846 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012847 adj = clientAdj;
12848 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012849 app.pendingUiClean = true;
12850 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12851 adj = ProcessList.VISIBLE_APP_ADJ;
12852 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012853 }
12854 if (!client.hidden) {
12855 app.hidden = false;
12856 }
12857 if (client.keeping) {
12858 app.keeping = true;
12859 }
12860 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012861 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012862 }
12863 if (adjType != null) {
12864 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012865 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12866 .REASON_SERVICE_IN_USE;
12867 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012868 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012869 app.adjTarget = s.name;
12870 }
12871 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12872 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12873 schedGroup = Process.THREAD_GROUP_DEFAULT;
12874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012875 }
12876 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012877 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012878 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012879 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012880 (a.visible || a.state == ActivityState.RESUMED
12881 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012882 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012883 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12884 schedGroup = Process.THREAD_GROUP_DEFAULT;
12885 }
12886 app.hidden = false;
12887 app.adjType = "service";
12888 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12889 .REASON_SERVICE_IN_USE;
12890 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012891 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012892 app.adjTarget = s.name;
12893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012895 }
12896 }
12897 }
12898 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012899
Dianne Hackborn287952c2010-09-22 22:34:31 -070012900 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012901 // would like to avoid killing it unless it would prevent the current
12902 // application from running. By default we put the process in
12903 // with the rest of the background processes; as we scan through
12904 // its services we may bump it up from there.
12905 if (adj > hiddenAdj) {
12906 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012907 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012908 app.adjType = "bg-services";
12909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012910 }
12911
Dianne Hackborn7d608422011-08-07 16:24:18 -070012912 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012913 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012914 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012915 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012916 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012917 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012918 for (int i = cpr.connections.size()-1;
12919 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12920 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12921 i--) {
12922 ContentProviderConnection conn = cpr.connections.get(i);
12923 ProcessRecord client = conn.client;
12924 if (client == app) {
12925 // Being our own client is not interesting.
12926 continue;
12927 }
12928 int myHiddenAdj = hiddenAdj;
12929 if (myHiddenAdj > client.hiddenAdj) {
12930 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12931 myHiddenAdj = client.hiddenAdj;
12932 } else {
12933 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012934 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012935 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012936 int myClientHiddenAdj = clientHiddenAdj;
12937 if (myClientHiddenAdj > client.clientHiddenAdj) {
12938 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
12939 myClientHiddenAdj = client.clientHiddenAdj;
12940 } else {
12941 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
12942 }
12943 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012944 int myEmptyAdj = emptyAdj;
12945 if (myEmptyAdj > client.emptyAdj) {
12946 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12947 myEmptyAdj = client.emptyAdj;
12948 } else {
12949 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12950 }
12951 }
12952 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012953 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012954 if (adj > clientAdj) {
12955 if (app.hasShownUi && app != mHomeProcess
12956 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12957 app.adjType = "bg-ui-provider";
12958 } else {
12959 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12960 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12961 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012963 if (!client.hidden) {
12964 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012965 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012966 if (client.keeping) {
12967 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012968 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012969 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12970 .REASON_PROVIDER_IN_USE;
12971 app.adjSource = client;
12972 app.adjSourceOom = clientAdj;
12973 app.adjTarget = cpr.name;
12974 }
12975 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12976 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 }
12978 }
12979 // If the provider has external (non-framework) process
12980 // dependencies, ensure that its adjustment is at least
12981 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012982 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012983 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12984 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012985 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012986 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012987 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012988 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012989 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012990 }
12991 }
12992 }
12993 }
12994
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012995 if (adj == ProcessList.SERVICE_ADJ) {
12996 if (doingAll) {
12997 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12998 mNewNumServiceProcs++;
12999 }
13000 if (app.serviceb) {
13001 adj = ProcessList.SERVICE_B_ADJ;
13002 }
13003 } else {
13004 app.serviceb = false;
13005 }
13006
13007 app.nonStoppingAdj = adj;
13008
13009 if (hasStoppingActivities) {
13010 // Only upgrade adjustment.
13011 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13012 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13013 app.adjType = "stopping";
13014 }
13015 }
13016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013017 app.curRawAdj = adj;
13018
Joe Onorato8a9b2202010-02-26 18:56:32 -080013019 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13021 if (adj > app.maxAdj) {
13022 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013023 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013024 schedGroup = Process.THREAD_GROUP_DEFAULT;
13025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013027 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013028 app.keeping = true;
13029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013030
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013031 if (app.hasAboveClient) {
13032 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13033 // then we need to drop its adjustment to be lower than the service's
13034 // in order to honor the request. We want to drop it by one adjustment
13035 // level... but there is special meaning applied to various levels so
13036 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013037 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013038 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013039 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13040 adj = ProcessList.VISIBLE_APP_ADJ;
13041 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13042 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13043 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13044 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013045 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013046 adj++;
13047 }
13048 }
13049
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013050 int importance = app.memImportance;
13051 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13052 app.curAdj = adj;
13053 app.curSchedGroup = schedGroup;
13054 if (!interesting) {
13055 // For this reporting, if there is not something explicitly
13056 // interesting in this process then we will push it to the
13057 // background importance.
13058 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13059 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13060 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13061 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13062 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13063 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13064 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13065 } else if (adj >= ProcessList.SERVICE_ADJ) {
13066 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13067 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13068 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13069 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13070 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13071 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13072 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13073 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13074 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13075 } else {
13076 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13077 }
13078 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013079
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013080 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13081 if (foregroundActivities != app.foregroundActivities) {
13082 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13083 }
13084 if (changes != 0) {
13085 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13086 app.memImportance = importance;
13087 app.foregroundActivities = foregroundActivities;
13088 int i = mPendingProcessChanges.size()-1;
13089 ProcessChangeItem item = null;
13090 while (i >= 0) {
13091 item = mPendingProcessChanges.get(i);
13092 if (item.pid == app.pid) {
13093 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13094 break;
13095 }
13096 i--;
13097 }
13098 if (i < 0) {
13099 // No existing item in pending changes; need a new one.
13100 final int NA = mAvailProcessChanges.size();
13101 if (NA > 0) {
13102 item = mAvailProcessChanges.remove(NA-1);
13103 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13104 } else {
13105 item = new ProcessChangeItem();
13106 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13107 }
13108 item.changes = 0;
13109 item.pid = app.pid;
13110 item.uid = app.info.uid;
13111 if (mPendingProcessChanges.size() == 0) {
13112 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13113 "*** Enqueueing dispatch processes changed!");
13114 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13115 }
13116 mPendingProcessChanges.add(item);
13117 }
13118 item.changes |= changes;
13119 item.importance = importance;
13120 item.foregroundActivities = foregroundActivities;
13121 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13122 + Integer.toHexString(System.identityHashCode(item))
13123 + " " + app.toShortString() + ": changes=" + item.changes
13124 + " importance=" + item.importance
13125 + " foreground=" + item.foregroundActivities
13126 + " type=" + app.adjType + " source=" + app.adjSource
13127 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013128 }
13129
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013130 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013131 }
13132
13133 /**
13134 * Ask a given process to GC right now.
13135 */
13136 final void performAppGcLocked(ProcessRecord app) {
13137 try {
13138 app.lastRequestedGc = SystemClock.uptimeMillis();
13139 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013140 if (app.reportLowMemory) {
13141 app.reportLowMemory = false;
13142 app.thread.scheduleLowMemory();
13143 } else {
13144 app.thread.processInBackground();
13145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013146 }
13147 } catch (Exception e) {
13148 // whatever.
13149 }
13150 }
13151
13152 /**
13153 * Returns true if things are idle enough to perform GCs.
13154 */
Josh Bartel7f208742010-02-25 11:01:44 -060013155 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013156 boolean processingBroadcasts = false;
13157 for (BroadcastQueue q : mBroadcastQueues) {
13158 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13159 processingBroadcasts = true;
13160 }
13161 }
13162 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013163 && (mSleeping || (mMainStack.mResumedActivity != null &&
13164 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013165 }
13166
13167 /**
13168 * Perform GCs on all processes that are waiting for it, but only
13169 * if things are idle.
13170 */
13171 final void performAppGcsLocked() {
13172 final int N = mProcessesToGc.size();
13173 if (N <= 0) {
13174 return;
13175 }
Josh Bartel7f208742010-02-25 11:01:44 -060013176 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 while (mProcessesToGc.size() > 0) {
13178 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013179 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013180 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13181 <= SystemClock.uptimeMillis()) {
13182 // To avoid spamming the system, we will GC processes one
13183 // at a time, waiting a few seconds between each.
13184 performAppGcLocked(proc);
13185 scheduleAppGcsLocked();
13186 return;
13187 } else {
13188 // It hasn't been long enough since we last GCed this
13189 // process... put it in the list to wait for its time.
13190 addProcessToGcListLocked(proc);
13191 break;
13192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013193 }
13194 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013195
13196 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013197 }
13198 }
13199
13200 /**
13201 * If all looks good, perform GCs on all processes waiting for them.
13202 */
13203 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013204 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013205 performAppGcsLocked();
13206 return;
13207 }
13208 // Still not idle, wait some more.
13209 scheduleAppGcsLocked();
13210 }
13211
13212 /**
13213 * Schedule the execution of all pending app GCs.
13214 */
13215 final void scheduleAppGcsLocked() {
13216 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013217
13218 if (mProcessesToGc.size() > 0) {
13219 // Schedule a GC for the time to the next process.
13220 ProcessRecord proc = mProcessesToGc.get(0);
13221 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13222
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013223 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013224 long now = SystemClock.uptimeMillis();
13225 if (when < (now+GC_TIMEOUT)) {
13226 when = now + GC_TIMEOUT;
13227 }
13228 mHandler.sendMessageAtTime(msg, when);
13229 }
13230 }
13231
13232 /**
13233 * Add a process to the array of processes waiting to be GCed. Keeps the
13234 * list in sorted order by the last GC time. The process can't already be
13235 * on the list.
13236 */
13237 final void addProcessToGcListLocked(ProcessRecord proc) {
13238 boolean added = false;
13239 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13240 if (mProcessesToGc.get(i).lastRequestedGc <
13241 proc.lastRequestedGc) {
13242 added = true;
13243 mProcessesToGc.add(i+1, proc);
13244 break;
13245 }
13246 }
13247 if (!added) {
13248 mProcessesToGc.add(0, proc);
13249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013250 }
13251
13252 /**
13253 * Set up to ask a process to GC itself. This will either do it
13254 * immediately, or put it on the list of processes to gc the next
13255 * time things are idle.
13256 */
13257 final void scheduleAppGcLocked(ProcessRecord app) {
13258 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013259 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013260 return;
13261 }
13262 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013263 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013264 scheduleAppGcsLocked();
13265 }
13266 }
13267
Dianne Hackborn287952c2010-09-22 22:34:31 -070013268 final void checkExcessivePowerUsageLocked(boolean doKills) {
13269 updateCpuStatsNow();
13270
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013271 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013272 boolean doWakeKills = doKills;
13273 boolean doCpuKills = doKills;
13274 if (mLastPowerCheckRealtime == 0) {
13275 doWakeKills = false;
13276 }
13277 if (mLastPowerCheckUptime == 0) {
13278 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013279 }
13280 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013281 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013282 }
13283 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013284 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13285 final long curUptime = SystemClock.uptimeMillis();
13286 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13287 mLastPowerCheckRealtime = curRealtime;
13288 mLastPowerCheckUptime = curUptime;
13289 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13290 doWakeKills = false;
13291 }
13292 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13293 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013294 }
13295 int i = mLruProcesses.size();
13296 while (i > 0) {
13297 i--;
13298 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013299 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013300 long wtime;
13301 synchronized (stats) {
13302 wtime = stats.getProcessWakeTime(app.info.uid,
13303 app.pid, curRealtime);
13304 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013305 long wtimeUsed = wtime - app.lastWakeTime;
13306 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13307 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013308 StringBuilder sb = new StringBuilder(128);
13309 sb.append("Wake for ");
13310 app.toShortString(sb);
13311 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013312 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013313 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013314 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013315 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013316 sb.append((wtimeUsed*100)/realtimeSince);
13317 sb.append("%)");
13318 Slog.i(TAG, sb.toString());
13319 sb.setLength(0);
13320 sb.append("CPU for ");
13321 app.toShortString(sb);
13322 sb.append(": over ");
13323 TimeUtils.formatDuration(uptimeSince, sb);
13324 sb.append(" used ");
13325 TimeUtils.formatDuration(cputimeUsed, sb);
13326 sb.append(" (");
13327 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013328 sb.append("%)");
13329 Slog.i(TAG, sb.toString());
13330 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013331 // If a process has held a wake lock for more
13332 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013333 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013334 if (doWakeKills && realtimeSince > 0
13335 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13336 synchronized (stats) {
13337 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13338 realtimeSince, wtimeUsed);
13339 }
13340 Slog.w(TAG, "Excessive wake lock in " + app.processName
13341 + " (pid " + app.pid + "): held " + wtimeUsed
13342 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013343 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013344 app.processName, app.setAdj, "excessive wake lock");
13345 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013346 } else if (doCpuKills && uptimeSince > 0
13347 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13348 synchronized (stats) {
13349 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13350 uptimeSince, cputimeUsed);
13351 }
13352 Slog.w(TAG, "Excessive CPU in " + app.processName
13353 + " (pid " + app.pid + "): used " + cputimeUsed
13354 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013355 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013356 app.processName, app.setAdj, "excessive cpu");
13357 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013358 } else {
13359 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013360 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013361 }
13362 }
13363 }
13364 }
13365
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013366 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013367 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013368 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013369 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013370 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013371
13372 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013373 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 }
13375
Dianne Hackborn287952c2010-09-22 22:34:31 -070013376 final boolean wasKeeping = app.keeping;
13377
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013378 boolean success = true;
13379
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013380 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013381
Jeff Brown10e89712011-07-08 18:52:57 -070013382 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013383 if (wasKeeping && !app.keeping) {
13384 // This app is no longer something we want to keep. Note
13385 // its current wake lock time to later know to kill it if
13386 // it is not behaving well.
13387 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13388 synchronized (stats) {
13389 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13390 app.pid, SystemClock.elapsedRealtime());
13391 }
13392 app.lastCpuTime = app.curCpuTime;
13393 }
13394
13395 app.setRawAdj = app.curRawAdj;
13396 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013397
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013398 if (app.curAdj != app.setAdj) {
13399 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013400 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013401 TAG, "Set " + app.pid + " " + app.processName +
13402 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013403 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013404 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013405 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013406 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013407 }
13408 }
13409 if (app.setSchedGroup != app.curSchedGroup) {
13410 app.setSchedGroup = app.curSchedGroup;
13411 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13412 "Setting process group of " + app.processName
13413 + " to " + app.curSchedGroup);
13414 if (app.waitingToKill != null &&
13415 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13416 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013417 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013418 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013419 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013420 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013421 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013422 } else {
13423 if (true) {
13424 long oldId = Binder.clearCallingIdentity();
13425 try {
13426 Process.setProcessGroup(app.pid, app.curSchedGroup);
13427 } catch (Exception e) {
13428 Slog.w(TAG, "Failed setting process group of " + app.pid
13429 + " to " + app.curSchedGroup);
13430 e.printStackTrace();
13431 } finally {
13432 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013433 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013434 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013435 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013436 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013437 app.thread.setSchedulingGroup(app.curSchedGroup);
13438 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013439 }
13440 }
13441 }
13442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013443 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013444 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013445 }
13446
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013447 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013448 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013449 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013450 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013451 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013452 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013453 }
13454 }
13455 return resumedActivity;
13456 }
13457
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013458 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013459 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013460 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13461 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013462 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13463 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013464
13465 mAdjSeq++;
13466
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013467 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13468 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013469 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13470 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013471 if (nowHidden != wasHidden) {
13472 // Changed to/from hidden state, so apps after it in the LRU
13473 // list may also be changed.
13474 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013475 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013476 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013477 }
13478
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013479 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013480 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013481 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013482 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013483
13484 if (false) {
13485 RuntimeException e = new RuntimeException();
13486 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013487 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013488 }
13489
13490 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013491 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013492
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013493 final int emptyProcessLimit;
13494 final int hiddenProcessLimit;
13495 if (mProcessLimit <= 0) {
13496 emptyProcessLimit = hiddenProcessLimit = 0;
13497 } else if (mProcessLimit == 1) {
13498 emptyProcessLimit = 1;
13499 hiddenProcessLimit = 0;
13500 } else {
13501 emptyProcessLimit = (mProcessLimit*2)/3;
13502 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13503 }
13504
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013505 // Let's determine how many processes we have running vs.
13506 // how many slots we have for background processes; we may want
13507 // to put multiple processes in a slot of there are enough of
13508 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013509 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13510 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013511 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13512 if (numEmptyProcs > hiddenProcessLimit) {
13513 // If there are more empty processes than our limit on hidden
13514 // processes, then use the hidden process limit for the factor.
13515 // This ensures that the really old empty processes get pushed
13516 // down to the bottom, so if we are running low on memory we will
13517 // have a better chance at keeping around more hidden processes
13518 // instead of a gazillion empty processes.
13519 numEmptyProcs = hiddenProcessLimit;
13520 }
13521 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013522 if (emptyFactor < 1) emptyFactor = 1;
13523 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13524 if (hiddenFactor < 1) hiddenFactor = 1;
13525 int stepHidden = 0;
13526 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013527 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013528 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013529 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013530
13531 mNumNonHiddenProcs = 0;
13532 mNumHiddenProcs = 0;
13533
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013534 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013535 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013536 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013537 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013538 int nextHiddenAdj = curHiddenAdj+1;
13539 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13540 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013541 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013542 while (i > 0) {
13543 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013544 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013545 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013546 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013547 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013548 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13549 // This process was assigned as a hidden process... step the
13550 // hidden level.
13551 mNumHiddenProcs++;
13552 if (curHiddenAdj != nextHiddenAdj) {
13553 stepHidden++;
13554 if (stepHidden >= hiddenFactor) {
13555 stepHidden = 0;
13556 curHiddenAdj = nextHiddenAdj;
13557 nextHiddenAdj += 2;
13558 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13559 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13560 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013561 if (curClientHiddenAdj <= curHiddenAdj) {
13562 curClientHiddenAdj = curHiddenAdj + 1;
13563 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13564 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13565 }
13566 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013567 }
13568 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013569 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013570 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013571 Slog.i(TAG, "No longer want " + app.processName
13572 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013573 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013574 app.processName, app.setAdj, "too many background");
13575 app.killedBackground = true;
13576 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013577 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013578 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13579 // This process has a client that has activities. We will have
13580 // given it the current hidden adj; here we will just leave it
13581 // without stepping the hidden adj.
13582 curClientHiddenAdj++;
13583 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13584 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13585 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013586 } else {
13587 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13588 // This process was assigned as an empty process... step the
13589 // empty level.
13590 if (curEmptyAdj != nextEmptyAdj) {
13591 stepEmpty++;
13592 if (stepEmpty >= emptyFactor) {
13593 stepEmpty = 0;
13594 curEmptyAdj = nextEmptyAdj;
13595 nextEmptyAdj += 2;
13596 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13597 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13598 }
13599 }
13600 }
13601 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13602 mNumNonHiddenProcs++;
13603 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013604 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13605 && !app.hasClientActivities) {
13606 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13607 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013608 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013609 + " (pid " + app.pid + "): empty for "
13610 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13611 / 1000) + "s");
13612 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13613 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013614 app.killedBackground = true;
13615 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013616 } else {
13617 numEmpty++;
13618 if (numEmpty > emptyProcessLimit) {
13619 Slog.i(TAG, "No longer want " + app.processName
13620 + " (pid " + app.pid + "): empty #" + numEmpty);
13621 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13622 app.processName, app.setAdj, "too many background");
13623 app.killedBackground = true;
13624 Process.killProcessQuiet(app.pid);
13625 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013626 }
13627 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013628 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013629 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013630 // If this is an isolated process, and there are no
13631 // services running in it, then the process is no longer
13632 // needed. We agressively kill these because we can by
13633 // definition not re-use the same process again, and it is
13634 // good to avoid having whatever code was running in them
13635 // left sitting around after no longer needed.
13636 Slog.i(TAG, "Isolated process " + app.processName
13637 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013638 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013639 app.processName, app.setAdj, "isolated not needed");
13640 app.killedBackground = true;
13641 Process.killProcessQuiet(app.pid);
13642 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013643 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13644 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13645 && !app.killedBackground) {
13646 numTrimming++;
13647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013648 }
13649 }
13650
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013651 mNumServiceProcs = mNewNumServiceProcs;
13652
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013653 // Now determine the memory trimming level of background processes.
13654 // Unfortunately we need to start at the back of the list to do this
13655 // properly. We only do this if the number of background apps we
13656 // are managing to keep around is less than half the maximum we desire;
13657 // if we are keeping a good number around, we'll let them use whatever
13658 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013659 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13660 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013661 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013662 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013663 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013664 int minFactor = 2;
13665 if (mHomeProcess != null) minFactor++;
13666 if (mPreviousProcess != null) minFactor++;
13667 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013668 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013669 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013670 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013671 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013672 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013673 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13674 } else {
13675 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13676 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013677 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013678 for (i=0; i<N; i++) {
13679 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013680 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13681 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013682 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013683 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13684 try {
13685 app.thread.scheduleTrimMemory(curLevel);
13686 } catch (RemoteException e) {
13687 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013688 if (false) {
13689 // For now we won't do this; our memory trimming seems
13690 // to be good enough at this point that destroying
13691 // activities causes more harm than good.
13692 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13693 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013694 // Need to do this on its own message because the stack may not
13695 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013696 // For these apps we will also finish their activities
13697 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013698 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013699 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013700 }
13701 }
13702 app.trimMemoryLevel = curLevel;
13703 step++;
13704 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013705 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013706 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013707 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13708 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013709 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013710 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13711 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013712 break;
13713 }
13714 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013715 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013716 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013717 && app.thread != null) {
13718 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013719 app.thread.scheduleTrimMemory(
13720 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013721 } catch (RemoteException e) {
13722 }
13723 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013724 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013725 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013726 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013727 && app.pendingUiClean) {
13728 // If this application is now in the background and it
13729 // had done UI, then give it the special trim level to
13730 // have it free UI resources.
13731 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13732 if (app.trimMemoryLevel < level && app.thread != null) {
13733 try {
13734 app.thread.scheduleTrimMemory(level);
13735 } catch (RemoteException e) {
13736 }
13737 }
13738 app.pendingUiClean = false;
13739 }
13740 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013741 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013742 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013743 } catch (RemoteException e) {
13744 }
13745 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013746 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013747 }
13748 }
13749 } else {
13750 final int N = mLruProcesses.size();
13751 for (i=0; i<N; i++) {
13752 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013753 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013754 && app.pendingUiClean) {
13755 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13756 && app.thread != null) {
13757 try {
13758 app.thread.scheduleTrimMemory(
13759 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13760 } catch (RemoteException e) {
13761 }
13762 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013763 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013764 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013765 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013766 }
13767 }
13768
13769 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013770 // Need to do this on its own message because the stack may not
13771 // be in a consistent state at this point.
13772 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013774 }
13775
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013776 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013777 synchronized (this) {
13778 int i;
13779
13780 // First remove any unused application processes whose package
13781 // has been removed.
13782 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13783 final ProcessRecord app = mRemovedProcesses.get(i);
13784 if (app.activities.size() == 0
13785 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013786 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 TAG, "Exiting empty application process "
13788 + app.processName + " ("
13789 + (app.thread != null ? app.thread.asBinder() : null)
13790 + ")\n");
13791 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013792 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013793 app.processName, app.setAdj, "empty");
13794 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013795 } else {
13796 try {
13797 app.thread.scheduleExit();
13798 } catch (Exception e) {
13799 // Ignore exceptions.
13800 }
13801 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013802 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013803 mRemovedProcesses.remove(i);
13804
13805 if (app.persistent) {
13806 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013807 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013808 }
13809 }
13810 }
13811 }
13812
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013813 // Now update the oom adj for all processes.
13814 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013815 }
13816 }
13817
13818 /** This method sends the specified signal to each of the persistent apps */
13819 public void signalPersistentProcesses(int sig) throws RemoteException {
13820 if (sig != Process.SIGNAL_USR1) {
13821 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13822 }
13823
13824 synchronized (this) {
13825 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13826 != PackageManager.PERMISSION_GRANTED) {
13827 throw new SecurityException("Requires permission "
13828 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13829 }
13830
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013831 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13832 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013833 if (r.thread != null && r.persistent) {
13834 Process.sendSignal(r.pid, sig);
13835 }
13836 }
13837 }
13838 }
13839
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013840 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13841 if (proc == null || proc == mProfileProc) {
13842 proc = mProfileProc;
13843 path = mProfileFile;
13844 profileType = mProfileType;
13845 clearProfilerLocked();
13846 }
13847 if (proc == null) {
13848 return;
13849 }
13850 try {
13851 proc.thread.profilerControl(false, path, null, profileType);
13852 } catch (RemoteException e) {
13853 throw new IllegalStateException("Process disappeared");
13854 }
13855 }
13856
13857 private void clearProfilerLocked() {
13858 if (mProfileFd != null) {
13859 try {
13860 mProfileFd.close();
13861 } catch (IOException e) {
13862 }
13863 }
13864 mProfileApp = null;
13865 mProfileProc = null;
13866 mProfileFile = null;
13867 mProfileType = 0;
13868 mAutoStopProfiler = false;
13869 }
13870
Dianne Hackborn1676c852012-09-10 14:52:30 -070013871 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013872 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013873
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013874 try {
13875 synchronized (this) {
13876 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13877 // its own permission.
13878 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13879 != PackageManager.PERMISSION_GRANTED) {
13880 throw new SecurityException("Requires permission "
13881 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013882 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013883
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013884 if (start && fd == null) {
13885 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013886 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013887
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013888 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013889 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013890 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013891 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013892
13893 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013894 throw new IllegalArgumentException("Unknown process: " + process);
13895 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013896
13897 if (start) {
13898 stopProfilerLocked(null, null, 0);
13899 setProfileApp(proc.info, proc.processName, path, fd, false);
13900 mProfileProc = proc;
13901 mProfileType = profileType;
13902 try {
13903 fd = fd.dup();
13904 } catch (IOException e) {
13905 fd = null;
13906 }
13907 proc.thread.profilerControl(start, path, fd, profileType);
13908 fd = null;
13909 mProfileFd = null;
13910 } else {
13911 stopProfilerLocked(proc, path, profileType);
13912 if (fd != null) {
13913 try {
13914 fd.close();
13915 } catch (IOException e) {
13916 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013917 }
13918 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013919
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013920 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013921 }
13922 } catch (RemoteException e) {
13923 throw new IllegalStateException("Process disappeared");
13924 } finally {
13925 if (fd != null) {
13926 try {
13927 fd.close();
13928 } catch (IOException e) {
13929 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013930 }
13931 }
13932 }
Andy McFadden824c5102010-07-09 16:26:57 -070013933
Dianne Hackborn1676c852012-09-10 14:52:30 -070013934 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070013935 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070013936 userId, true, true, callName, null);
13937 ProcessRecord proc = null;
13938 try {
13939 int pid = Integer.parseInt(process);
13940 synchronized (mPidsSelfLocked) {
13941 proc = mPidsSelfLocked.get(pid);
13942 }
13943 } catch (NumberFormatException e) {
13944 }
13945
13946 if (proc == null) {
13947 HashMap<String, SparseArray<ProcessRecord>> all
13948 = mProcessNames.getMap();
13949 SparseArray<ProcessRecord> procs = all.get(process);
13950 if (procs != null && procs.size() > 0) {
13951 proc = procs.valueAt(0);
13952 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13953 for (int i=1; i<procs.size(); i++) {
13954 ProcessRecord thisProc = procs.valueAt(i);
13955 if (thisProc.userId == userId) {
13956 proc = thisProc;
13957 break;
13958 }
13959 }
13960 }
13961 }
13962 }
13963
13964 return proc;
13965 }
13966
13967 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013968 String path, ParcelFileDescriptor fd) throws RemoteException {
13969
13970 try {
13971 synchronized (this) {
13972 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13973 // its own permission (same as profileControl).
13974 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13975 != PackageManager.PERMISSION_GRANTED) {
13976 throw new SecurityException("Requires permission "
13977 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13978 }
13979
13980 if (fd == null) {
13981 throw new IllegalArgumentException("null fd");
13982 }
13983
Dianne Hackborn1676c852012-09-10 14:52:30 -070013984 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013985 if (proc == null || proc.thread == null) {
13986 throw new IllegalArgumentException("Unknown process: " + process);
13987 }
13988
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013989 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13990 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013991 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13992 throw new SecurityException("Process not debuggable: " + proc);
13993 }
13994 }
13995
13996 proc.thread.dumpHeap(managed, path, fd);
13997 fd = null;
13998 return true;
13999 }
14000 } catch (RemoteException e) {
14001 throw new IllegalStateException("Process disappeared");
14002 } finally {
14003 if (fd != null) {
14004 try {
14005 fd.close();
14006 } catch (IOException e) {
14007 }
14008 }
14009 }
14010 }
14011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014012 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14013 public void monitor() {
14014 synchronized (this) { }
14015 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014016
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014017 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014018 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14019 ProcessRecord processRecord = mLruProcesses.get(i);
14020 try {
14021 if (processRecord.thread != null) {
14022 processRecord.thread.setCoreSettings(settings);
14023 }
14024 } catch (RemoteException re) {
14025 /* ignore */
14026 }
14027 }
14028 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014029
14030 // Multi-user methods
14031
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014032 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070014033 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014034 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14035 != PackageManager.PERMISSION_GRANTED) {
14036 String msg = "Permission Denial: switchUser() from pid="
14037 + Binder.getCallingPid()
14038 + ", uid=" + Binder.getCallingUid()
14039 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14040 Slog.w(TAG, msg);
14041 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014042 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014043
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014044 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014045 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014046 synchronized (this) {
14047 final int oldUserId = mCurrentUserId;
14048 if (oldUserId == userId) {
14049 return true;
14050 }
14051
14052 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14053 if (userInfo == null) {
14054 Slog.w(TAG, "No user info for user #" + userId);
14055 return false;
14056 }
14057
Amith Yamasanibc4ba822012-09-28 10:14:01 -070014058 mWindowManager.lockNow();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014059 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14060 R.anim.screen_user_enter);
14061
14062 // If the user we are switching to is not currently started, then
14063 // we need to start it now.
14064 if (mStartedUsers.get(userId) == null) {
14065 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014066 updateStartedUserArrayLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014067 }
14068
14069 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014070 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014071 final Integer userIdInt = Integer.valueOf(userId);
14072 mUserLru.remove(userIdInt);
14073 mUserLru.add(userIdInt);
14074
Craig Mautnerf1b67412012-09-19 13:18:29 -070014075 mWindowManager.setCurrentUser(userId);
14076
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014077 final UserStartedState uss = mStartedUsers.get(userId);
14078
14079 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14080 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14081 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14082 oldUserId, userId, uss));
14083 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14084 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
14085 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014086 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14087 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014088 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14089 broadcastIntentLocked(null, null, intent,
14090 null, null, 0, null, null, null,
14091 false, false, MY_PID, Process.SYSTEM_UID, userId);
14092
14093 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14094 if (userId != 0) {
14095 intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014096 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014097 broadcastIntentLocked(null, null, intent, null,
14098 new IIntentReceiver.Stub() {
14099 public void performReceive(Intent intent, int resultCode,
14100 String data, Bundle extras, boolean ordered,
14101 boolean sticky, int sendingUser) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014102 userInitialized(uss);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014103 }
14104 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14105 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014106 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014107 } else {
14108 getUserManagerLocked().makeInitialized(userInfo.id);
14109 }
14110 }
14111
14112 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14113 if (!haveActivities) {
14114 startHomeActivityLocked(userId);
14115 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014116
Amith Yamasani920ace02012-09-20 22:15:37 -070014117 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014118 sendUserSwitchBroadcastsLocked(oldUserId, userId);
14119 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014120 } finally {
14121 Binder.restoreCallingIdentity(ident);
14122 }
Amith Yamasani13593602012-03-22 16:16:17 -070014123
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014124 return true;
14125 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014126
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014127 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14128 long ident = Binder.clearCallingIdentity();
14129 try {
14130 Intent intent;
14131 if (oldUserId >= 0) {
14132 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014133 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14134 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014135 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14136 broadcastIntentLocked(null, null, intent,
14137 null, null, 0, null, null, null,
14138 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14139 }
14140 if (newUserId >= 0) {
14141 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014142 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14143 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014144 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14145 broadcastIntentLocked(null, null, intent,
14146 null, null, 0, null, null, null,
14147 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14148 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014149 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14150 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014151 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14152 broadcastIntentLocked(null, null, intent,
14153 null, null, 0, null, null,
14154 android.Manifest.permission.MANAGE_USERS,
14155 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14156 }
14157 } finally {
14158 Binder.restoreCallingIdentity(ident);
14159 }
14160 }
14161
14162 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14163 final int newUserId) {
14164 final int N = mUserSwitchObservers.beginBroadcast();
14165 if (N > 0) {
14166 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14167 int mCount = 0;
14168 @Override
14169 public void sendResult(Bundle data) throws RemoteException {
14170 synchronized (ActivityManagerService.this) {
14171 if (mCurUserSwitchCallback == this) {
14172 mCount++;
14173 if (mCount == N) {
14174 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14175 }
14176 }
14177 }
14178 }
14179 };
14180 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014181 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014182 mCurUserSwitchCallback = callback;
14183 }
14184 for (int i=0; i<N; i++) {
14185 try {
14186 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14187 newUserId, callback);
14188 } catch (RemoteException e) {
14189 }
14190 }
14191 } else {
14192 synchronized (this) {
14193 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14194 }
14195 }
14196 mUserSwitchObservers.finishBroadcast();
14197 }
14198
14199 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14200 synchronized (this) {
14201 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14202 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14203 }
14204 }
14205
14206 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14207 mCurUserSwitchCallback = null;
14208 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14209 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14210 oldUserId, newUserId, uss));
14211 }
14212
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014213 void userInitialized(UserStartedState uss) {
14214 synchronized (ActivityManagerService.this) {
14215 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14216 uss.initializing = false;
14217 completeSwitchAndInitalizeLocked(uss);
14218 }
14219 }
14220
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014221 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14222 final int N = mUserSwitchObservers.beginBroadcast();
14223 for (int i=0; i<N; i++) {
14224 try {
14225 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14226 } catch (RemoteException e) {
14227 }
14228 }
14229 mUserSwitchObservers.finishBroadcast();
14230 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014231 uss.switching = false;
14232 completeSwitchAndInitalizeLocked(uss);
14233 }
14234 }
14235
14236 void completeSwitchAndInitalizeLocked(UserStartedState uss) {
14237 if (!uss.switching && !uss.initializing) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014238 mWindowManager.stopFreezingScreen();
14239 }
14240 }
14241
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014242 void finishUserSwitch(UserStartedState uss) {
14243 synchronized (this) {
14244 if (uss.mState == UserStartedState.STATE_BOOTING
14245 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14246 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014247 final int userId = uss.mHandle.getIdentifier();
14248 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14249 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14250 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014251 null, null, 0, null, null,
14252 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014253 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014254 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014255 int num = mUserLru.size();
14256 int i = 0;
14257 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14258 Integer oldUserId = mUserLru.get(i);
14259 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14260 if (oldUss == null) {
14261 // Shouldn't happen, but be sane if it does.
14262 mUserLru.remove(i);
14263 num--;
14264 continue;
14265 }
14266 if (oldUss.mState == UserStartedState.STATE_STOPPING) {
14267 // This user is already stopping, doesn't count.
14268 num--;
14269 i++;
14270 continue;
14271 }
14272 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14273 // Owner and current can't be stopped, but count as running.
14274 i++;
14275 continue;
14276 }
14277 // This is a user to be stopped.
14278 stopUserLocked(oldUserId, null);
14279 num--;
14280 i++;
14281 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014282 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014283 }
14284
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014285 @Override
14286 public int stopUser(final int userId, final IStopUserCallback callback) {
14287 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14288 != PackageManager.PERMISSION_GRANTED) {
14289 String msg = "Permission Denial: switchUser() from pid="
14290 + Binder.getCallingPid()
14291 + ", uid=" + Binder.getCallingUid()
14292 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14293 Slog.w(TAG, msg);
14294 throw new SecurityException(msg);
14295 }
14296 if (userId <= 0) {
14297 throw new IllegalArgumentException("Can't stop primary user " + userId);
14298 }
Amith Yamasani13593602012-03-22 16:16:17 -070014299 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014300 return stopUserLocked(userId, callback);
14301 }
14302 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014303
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014304 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14305 if (mCurrentUserId == userId) {
14306 return ActivityManager.USER_OP_IS_CURRENT;
14307 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014308
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014309 final UserStartedState uss = mStartedUsers.get(userId);
14310 if (uss == null) {
14311 // User is not started, nothing to do... but we do need to
14312 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014313 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014314 mHandler.post(new Runnable() {
14315 @Override
14316 public void run() {
14317 try {
14318 callback.userStopped(userId);
14319 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014320 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014321 }
14322 });
14323 }
14324 return ActivityManager.USER_OP_SUCCESS;
14325 }
14326
14327 if (callback != null) {
14328 uss.mStopCallbacks.add(callback);
14329 }
14330
14331 if (uss.mState != UserStartedState.STATE_STOPPING) {
14332 uss.mState = UserStartedState.STATE_STOPPING;
14333
14334 long ident = Binder.clearCallingIdentity();
14335 try {
14336 // Inform of user switch
14337 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
14338 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
14339 @Override
14340 public void performReceive(Intent intent, int resultCode, String data,
14341 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14342 finishUserStop(uss);
14343 }
14344 };
14345 broadcastIntentLocked(null, null, intent,
14346 null, resultReceiver, 0, null, null, null,
14347 true, false, MY_PID, Process.SYSTEM_UID, userId);
14348 } finally {
14349 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014350 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014351 }
Amith Yamasani13593602012-03-22 16:16:17 -070014352
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014353 return ActivityManager.USER_OP_SUCCESS;
14354 }
14355
14356 void finishUserStop(UserStartedState uss) {
14357 final int userId = uss.mHandle.getIdentifier();
14358 boolean stopped;
14359 ArrayList<IStopUserCallback> callbacks;
14360 synchronized (this) {
14361 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
14362 if (uss.mState != UserStartedState.STATE_STOPPING
14363 || mStartedUsers.get(userId) != uss) {
14364 stopped = false;
14365 } else {
14366 stopped = true;
14367 // User can no longer run.
14368 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014369 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014370 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014371
14372 // Clean up all state and processes associated with the user.
14373 // Kill all the processes for the user.
14374 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014375 }
14376 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014377
14378 for (int i=0; i<callbacks.size(); i++) {
14379 try {
14380 if (stopped) callbacks.get(i).userStopped(userId);
14381 else callbacks.get(i).userStopAborted(userId);
14382 } catch (RemoteException e) {
14383 }
14384 }
14385 }
14386
14387 @Override
14388 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014389 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14390 != PackageManager.PERMISSION_GRANTED) && (
14391 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14392 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014393 String msg = "Permission Denial: getCurrentUser() from pid="
14394 + Binder.getCallingPid()
14395 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014396 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014397 Slog.w(TAG, msg);
14398 throw new SecurityException(msg);
14399 }
14400 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014401 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014402 }
Amith Yamasani13593602012-03-22 16:16:17 -070014403 }
14404
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014405 int getCurrentUserIdLocked() {
14406 return mCurrentUserId;
14407 }
14408
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014409 @Override
14410 public boolean isUserRunning(int userId) {
14411 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14412 != PackageManager.PERMISSION_GRANTED) {
14413 String msg = "Permission Denial: isUserRunning() from pid="
14414 + Binder.getCallingPid()
14415 + ", uid=" + Binder.getCallingUid()
14416 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14417 Slog.w(TAG, msg);
14418 throw new SecurityException(msg);
14419 }
14420 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014421 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014422 }
14423 }
14424
Dianne Hackborn1676c852012-09-10 14:52:30 -070014425 boolean isUserRunningLocked(int userId) {
14426 UserStartedState state = mStartedUsers.get(userId);
14427 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014428 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014429
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014430 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014431 public int[] getRunningUserIds() {
14432 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14433 != PackageManager.PERMISSION_GRANTED) {
14434 String msg = "Permission Denial: isUserRunning() from pid="
14435 + Binder.getCallingPid()
14436 + ", uid=" + Binder.getCallingUid()
14437 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14438 Slog.w(TAG, msg);
14439 throw new SecurityException(msg);
14440 }
14441 synchronized (this) {
14442 return mStartedUserArray;
14443 }
14444 }
14445
14446 private void updateStartedUserArrayLocked() {
14447 mStartedUserArray = new int[mStartedUsers.size()];
14448 for (int i=0; i<mStartedUsers.size(); i++) {
14449 mStartedUserArray[i] = mStartedUsers.keyAt(i);
14450 }
14451 }
14452
14453 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014454 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14455 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14456 != PackageManager.PERMISSION_GRANTED) {
14457 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14458 + Binder.getCallingPid()
14459 + ", uid=" + Binder.getCallingUid()
14460 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14461 Slog.w(TAG, msg);
14462 throw new SecurityException(msg);
14463 }
14464
14465 mUserSwitchObservers.register(observer);
14466 }
14467
14468 @Override
14469 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14470 mUserSwitchObservers.unregister(observer);
14471 }
14472
Dianne Hackborn1676c852012-09-10 14:52:30 -070014473 private boolean userExists(int userId) {
14474 if (userId == 0) {
14475 return true;
14476 }
14477 UserManagerService ums = getUserManagerLocked();
14478 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14479 }
14480
14481 int[] getUsersLocked() {
14482 UserManagerService ums = getUserManagerLocked();
14483 return ums != null ? ums.getUserIds() : new int[] { 0 };
14484 }
14485
14486 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014487 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014488 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14489 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014490 }
14491 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014492 }
14493
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014494 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014495 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014496
14497 throw new SecurityException("Caller uid=" + uid
14498 + " is not privileged to communicate with user=" + userId);
14499 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014500
14501 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014502 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014503 }
14504
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014505 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014506 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014507 ApplicationInfo newInfo = new ApplicationInfo(info);
14508 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014509 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14510 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014511 return newInfo;
14512 }
14513
14514 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014515 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014516 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014517 return aInfo;
14518 }
14519
14520 ActivityInfo info = new ActivityInfo(aInfo);
14521 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14522 return info;
14523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014524}