blob: bfefe67370933fc8b5894f912021cf54f11cb56a [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 Hackborna1e989b2009-09-01 19:54:29 -0700184 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800185 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700187 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700188 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700189 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700190 static final boolean DEBUG_POWER = localLOGV || false;
191 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700192 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 static final boolean VALIDATE_TOKENS = false;
194 static final boolean SHOW_ACTIVITY_START_TIME = true;
195
196 // Control over CPU and battery monitoring.
197 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
198 static final boolean MONITOR_CPU_USAGE = true;
199 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
200 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
201 static final boolean MONITOR_THREAD_CPU_USAGE = false;
202
Dianne Hackborn1655be42009-05-08 14:29:01 -0700203 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700204 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700205
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800206 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700208 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // Maximum number of recent tasks that we can remember.
211 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700212
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700213 // Amount of time after a call to stopAppSwitches() during which we will
214 // prevent further untrusted switches from happening.
215 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 // How long we wait for a launched process to attach to the activity manager
218 // before we decide it's never going to come up for real.
219 static final int PROC_START_TIMEOUT = 10*1000;
220
Jeff Brown3f9dd282011-07-08 20:02:19 -0700221 // How long we wait for a launched process to attach to the activity manager
222 // before we decide it's never going to come up for real, when the process was
223 // started with a wrapper for instrumentation (such as Valgrind) because it
224 // could take much longer than usual.
225 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 // How long to wait after going idle before forcing apps to GC.
228 static final int GC_TIMEOUT = 5*1000;
229
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700230 // The minimum amount of time between successive GC requests for a process.
231 static final int GC_MIN_INTERVAL = 60*1000;
232
Dianne Hackborn287952c2010-09-22 22:34:31 -0700233 // The rate at which we check for apps using excessive power -- 15 mins.
234 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
235
236 // The minimum sample duration we will allow before deciding we have
237 // enough data on wake locks to start killing things.
238 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
239
240 // The minimum sample duration we will allow before deciding we have
241 // enough data on CPU usage to start killing things.
242 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800245 static final int BROADCAST_FG_TIMEOUT = 10*1000;
246 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // How long we wait until we timeout on key dispatching.
249 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // How long we wait until we timeout on key dispatching during instrumentation.
252 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
253
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700254 // Amount of time we wait for observers to handle a user switch before
255 // giving up on them and unfreezing the screen.
256 static final int USER_SWITCH_TIMEOUT = 2*1000;
257
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700258 // Maximum number of users we allow to be running at a time.
259 static final int MAX_RUNNING_USERS = 3;
260
Dan Egnor42471dd2010-01-07 17:25:22 -0800261 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 static final String[] EMPTY_STRING_ARRAY = new String[0];
264
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700265 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700266
267 private final boolean mHeadless;
268
Joe Onorato54a4a412011-11-02 20:50:08 -0700269 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
270 // default actuion automatically. Important for devices without direct input
271 // devices.
272 private boolean mShowDialogs = true;
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700275 * Description of a request to start a new activity, which has been held
276 * due to app switches being disabled.
277 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700278 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700279 ActivityRecord r;
280 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700281 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700282 }
283
284 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
285 = new ArrayList<PendingActivityLaunch>();
286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800288 BroadcastQueue mFgBroadcastQueue;
289 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800290 // Convenient for easy iteration over the queues. Foreground is first
291 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800292 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800293
294 BroadcastQueue broadcastQueueForIntent(Intent intent) {
295 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
296 if (DEBUG_BACKGROUND_BROADCAST) {
297 Slog.i(TAG, "Broadcast intent " + intent + " on "
298 + (isFg ? "foreground" : "background")
299 + " queue");
300 }
301 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
302 }
303
304 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
305 for (BroadcastQueue queue : mBroadcastQueues) {
306 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
307 if (r != null) {
308 return r;
309 }
310 }
311 return null;
312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
314 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 * Activity we have told the window manager to have key focus.
316 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700317 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * List of intents that were used to start the most recent tasks.
320 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700321 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322
323 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700324 * Process management.
325 */
326 final ProcessList mProcessList = new ProcessList();
327
328 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 * All of the applications we currently have running organized by name.
330 * The keys are strings of the application package name (as
331 * returned by the package manager), and the keys are ApplicationRecord
332 * objects.
333 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700334 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335
336 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800337 * The currently running isolated processes.
338 */
339 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
340
341 /**
342 * Counter for assigning isolated process uids, to avoid frequently reusing the
343 * same ones.
344 */
345 int mNextIsolatedProcessUid = 0;
346
347 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700348 * The currently running heavy-weight process, if any.
349 */
350 ProcessRecord mHeavyWeightProcess = null;
351
352 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 * The last time that various processes have crashed.
354 */
355 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
356
357 /**
358 * Set of applications that we consider to be bad, and will reject
359 * incoming broadcasts from (which the user has no control over).
360 * Processes are added to this set when they have crashed twice within
361 * a minimum amount of time; they are removed from it when they are
362 * later restarted (hopefully due to some user action). The value is the
363 * time it was added to the list.
364 */
365 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
366
367 /**
368 * All of the processes we currently have running organized by pid.
369 * The keys are the pid running the application.
370 *
371 * <p>NOTE: This object is protected by its own lock, NOT the global
372 * activity manager lock!
373 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700374 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375
376 /**
377 * All of the processes that have been forced to be foreground. The key
378 * is the pid of the caller who requested it (we hold a death
379 * link on it).
380 */
381 abstract class ForegroundToken implements IBinder.DeathRecipient {
382 int pid;
383 IBinder token;
384 }
385 final SparseArray<ForegroundToken> mForegroundProcesses
386 = new SparseArray<ForegroundToken>();
387
388 /**
389 * List of records for processes that someone had tried to start before the
390 * system was ready. We don't start them at that point, but ensure they
391 * are started by the time booting is complete.
392 */
393 final ArrayList<ProcessRecord> mProcessesOnHold
394 = new ArrayList<ProcessRecord>();
395
396 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 * List of persistent applications that are in the process
398 * of being started.
399 */
400 final ArrayList<ProcessRecord> mPersistentStartingProcesses
401 = new ArrayList<ProcessRecord>();
402
403 /**
404 * Processes that are being forcibly torn down.
405 */
406 final ArrayList<ProcessRecord> mRemovedProcesses
407 = new ArrayList<ProcessRecord>();
408
409 /**
410 * List of running applications, sorted by recent usage.
411 * The first entry in the list is the least recently used.
412 * It contains ApplicationRecord objects. This list does NOT include
413 * any persistent application records (since we never want to exit them).
414 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800415 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 = new ArrayList<ProcessRecord>();
417
418 /**
419 * List of processes that should gc as soon as things are idle.
420 */
421 final ArrayList<ProcessRecord> mProcessesToGc
422 = new ArrayList<ProcessRecord>();
423
424 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800425 * This is the process holding what we currently consider to be
426 * the "home" activity.
427 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700428 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800429
430 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700431 * This is the process holding the activity the user last visited that
432 * is in a different process from the one they are currently in.
433 */
434 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800435
436 /**
437 * The time at which the previous process was last visible.
438 */
439 long mPreviousProcessVisibleTime;
440
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700441 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700442 * Which uses have been started, so are allowed to run code.
443 */
444 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
445
446 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700447 * LRU list of history of current users. Most recently current is at the end.
448 */
449 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
450
451 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700452 * Constant array of the users that are currently started.
453 */
454 int[] mStartedUserArray = new int[] { 0 };
455
456 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700457 * Registered observers of the user switching mechanics.
458 */
459 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
460 = new RemoteCallbackList<IUserSwitchObserver>();
461
462 /**
463 * Currently active user switch.
464 */
465 Object mCurUserSwitchCallback;
466
467 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400468 * Packages that the user has asked to have run in screen size
469 * compatibility mode instead of filling the screen.
470 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700471 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400472
473 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 * Set of PendingResultRecord objects that are currently active.
475 */
476 final HashSet mPendingResultRecords = new HashSet();
477
478 /**
479 * Set of IntentSenderRecord objects that are currently active.
480 */
481 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
482 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
483
484 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800485 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700486 * already logged DropBox entries for. Guarded by itself. If
487 * something (rogue user app) forces this over
488 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
489 */
490 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
491 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
492
493 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700494 * Strict Mode background batched logging state.
495 *
496 * The string buffer is guarded by itself, and its lock is also
497 * used to determine if another batched write is already
498 * in-flight.
499 */
500 private final StringBuilder mStrictModeBuffer = new StringBuilder();
501
502 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 * Keeps track of all IIntentReceivers that have been registered for
504 * broadcasts. Hash keys are the receiver IBinder, hash value is
505 * a ReceiverList.
506 */
507 final HashMap mRegisteredReceivers = new HashMap();
508
509 /**
510 * Resolver for broadcast intents to registered receivers.
511 * Holds BroadcastFilter (subclass of IntentFilter).
512 */
513 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
514 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
515 @Override
516 protected boolean allowFilterResult(
517 BroadcastFilter filter, List<BroadcastFilter> dest) {
518 IBinder target = filter.receiverList.receiver.asBinder();
519 for (int i=dest.size()-1; i>=0; i--) {
520 if (dest.get(i).receiverList.receiver.asBinder() == target) {
521 return false;
522 }
523 }
524 return true;
525 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700526
527 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700528 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700529 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
530 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700531 return super.newResult(filter, match, userId);
532 }
533 return null;
534 }
535
536 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700537 protected BroadcastFilter[] newArray(int size) {
538 return new BroadcastFilter[size];
539 }
540
541 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700542 protected String packageForFilter(BroadcastFilter filter) {
543 return filter.packageName;
544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 };
546
547 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700548 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700550 * that action (which should usually be one). The SparseArray is keyed
551 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
552 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700554 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
555 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700557 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
559 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700560 * Backup/restore process management
561 */
562 String mBackupAppName = null;
563 BackupRecord mBackupTarget = null;
564
565 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 * List of PendingThumbnailsRecord objects of clients who are still
567 * waiting to receive all of the thumbnails for a task.
568 */
569 final ArrayList mPendingThumbnails = new ArrayList();
570
571 /**
572 * List of HistoryRecord objects that have been finished and must
573 * still report back to a pending thumbnail receiver.
574 */
575 final ArrayList mCancelledThumbnails = new ArrayList();
576
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700577 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 /**
580 * List of content providers who have clients waiting for them. The
581 * application is currently being launched and the provider will be
582 * removed from this list once it is published.
583 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700584 final ArrayList<ContentProviderRecord> mLaunchingProviders
585 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 /**
588 * Global set of specific Uri permissions that have been granted.
589 */
590 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
591 = new SparseArray<HashMap<Uri, UriPermission>>();
592
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800593 CoreSettingsObserver mCoreSettingsObserver;
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 /**
596 * Thread-local storage used to carry caller permissions over through
597 * indirect content-provider access.
598 * @see #ActivityManagerService.openContentUri()
599 */
600 private class Identity {
601 public int pid;
602 public int uid;
603
604 Identity(int _pid, int _uid) {
605 pid = _pid;
606 uid = _uid;
607 }
608 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
611
612 /**
613 * All information we have collected about the runtime performance of
614 * any user id that can impact battery performance.
615 */
616 final BatteryStatsService mBatteryStatsService;
617
618 /**
619 * information about component usage
620 */
621 final UsageStatsService mUsageStatsService;
622
623 /**
624 * Current configuration information. HistoryRecord objects are given
625 * a reference to this object to indicate which configuration they are
626 * currently running in, so this object must be kept immutable.
627 */
628 Configuration mConfiguration = new Configuration();
629
630 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800631 * Current sequencing integer of the configuration, for skipping old
632 * configurations.
633 */
634 int mConfigurationSeq = 0;
635
636 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700637 * Hardware-reported OpenGLES version.
638 */
639 final int GL_ES_VERSION;
640
641 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 * List of initialization arguments to pass to all processes when binding applications to them.
643 * For example, references to the commonly used services.
644 */
645 HashMap<String, IBinder> mAppBindArgs;
646
647 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700648 * Temporary to avoid allocations. Protected by main lock.
649 */
650 final StringBuilder mStringBuilder = new StringBuilder(256);
651
652 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 * Used to control how we initialize the service.
654 */
655 boolean mStartRunning = false;
656 ComponentName mTopComponent;
657 String mTopAction;
658 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700659 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 boolean mSystemReady = false;
661 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700662 boolean mWaitingUpdate = false;
663 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700664 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700665 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
667 Context mContext;
668
669 int mFactoryTest;
670
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700671 boolean mCheckedForSetup;
672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700674 * The time at which we will allow normal application switches again,
675 * after a call to {@link #stopAppSwitches()}.
676 */
677 long mAppSwitchesAllowedTime;
678
679 /**
680 * This is set to true after the first switch after mAppSwitchesAllowedTime
681 * is set; any switches after that will clear the time.
682 */
683 boolean mDidAppSwitch;
684
685 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700687 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700688 long mLastPowerCheckRealtime;
689
690 /**
691 * Last time (in uptime) at which we checked for power usage.
692 */
693 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700694
695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 * Set while we are wanting to sleep, to prevent any
697 * activities from being started/resumed.
698 */
699 boolean mSleeping = false;
700
701 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700702 * State of external calls telling us if the device is asleep.
703 */
704 boolean mWentToSleep = false;
705
706 /**
707 * State of external call telling us if the lock screen is shown.
708 */
709 boolean mLockScreenShown = false;
710
711 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700712 * Set if we are shutting down the system, similar to sleeping.
713 */
714 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715
716 /**
717 * Task identifier that activities are currently being started
718 * in. Incremented each time a new task is created.
719 * todo: Replace this with a TokenSpace class that generates non-repeating
720 * integers that won't wrap.
721 */
722 int mCurTask = 1;
723
724 /**
725 * Current sequence id for oom_adj computation traversal.
726 */
727 int mAdjSeq = 0;
728
729 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700730 * Current sequence id for process LRU updating.
731 */
732 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733
734 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700735 * Keep track of the non-hidden/empty process we last found, to help
736 * determine how to distribute hidden/empty processes next time.
737 */
738 int mNumNonHiddenProcs = 0;
739
740 /**
741 * Keep track of the number of hidden procs, to balance oom adj
742 * distribution between those and empty procs.
743 */
744 int mNumHiddenProcs = 0;
745
746 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700747 * Keep track of the number of service processes we last found, to
748 * determine on the next iteration which should be B services.
749 */
750 int mNumServiceProcs = 0;
751 int mNewNumServiceProcs = 0;
752
753 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 * System monitoring: number of processes that died since the last
755 * N procs were started.
756 */
757 int[] mProcDeaths = new int[20];
758
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700759 /**
760 * This is set if we had to do a delayed dexopt of an app before launching
761 * it, to increasing the ANR timeouts in that case.
762 */
763 boolean mDidDexOpt;
764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 String mDebugApp = null;
766 boolean mWaitForDebugger = false;
767 boolean mDebugTransient = false;
768 String mOrigDebugApp = null;
769 boolean mOrigWaitForDebugger = false;
770 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700771 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700772 String mProfileApp = null;
773 ProcessRecord mProfileProc = null;
774 String mProfileFile;
775 ParcelFileDescriptor mProfileFd;
776 int mProfileType = 0;
777 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800778 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700780 static class ProcessChangeItem {
781 static final int CHANGE_ACTIVITIES = 1<<0;
782 static final int CHANGE_IMPORTANCE= 1<<1;
783 int changes;
784 int uid;
785 int pid;
786 int importance;
787 boolean foregroundActivities;
788 }
789
Jeff Sharkeya4620792011-05-20 15:29:23 -0700790 final RemoteCallbackList<IProcessObserver> mProcessObservers
791 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700792 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
793
794 final ArrayList<ProcessChangeItem> mPendingProcessChanges
795 = new ArrayList<ProcessChangeItem>();
796 final ArrayList<ProcessChangeItem> mAvailProcessChanges
797 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 /**
800 * Callback of last caller to {@link #requestPss}.
801 */
802 Runnable mRequestPssCallback;
803
804 /**
805 * Remaining processes for which we are waiting results from the last
806 * call to {@link #requestPss}.
807 */
808 final ArrayList<ProcessRecord> mRequestPssList
809 = new ArrayList<ProcessRecord>();
810
811 /**
812 * Runtime statistics collection thread. This object's lock is used to
813 * protect all related state.
814 */
815 final Thread mProcessStatsThread;
816
817 /**
818 * Used to collect process stats when showing not responding dialog.
819 * Protected by mProcessStatsThread.
820 */
821 final ProcessStats mProcessStats = new ProcessStats(
822 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700823 final AtomicLong mLastCpuTime = new AtomicLong(0);
824 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 long mLastWriteTime = 0;
827
828 /**
829 * Set to true after the system has finished booting.
830 */
831 boolean mBooted = false;
832
Dianne Hackborn7d608422011-08-07 16:24:18 -0700833 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700834 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835
836 WindowManagerService mWindowManager;
837
838 static ActivityManagerService mSelf;
839 static ActivityThread mSystemThread;
840
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700841 private int mCurrentUserId = 0;
842 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700843 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 private final class AppDeathRecipient implements IBinder.DeathRecipient {
846 final ProcessRecord mApp;
847 final int mPid;
848 final IApplicationThread mAppThread;
849
850 AppDeathRecipient(ProcessRecord app, int pid,
851 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800852 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 TAG, "New death recipient " + this
854 + " for thread " + thread.asBinder());
855 mApp = app;
856 mPid = pid;
857 mAppThread = thread;
858 }
859
860 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800861 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 TAG, "Death received in " + this
863 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 synchronized(ActivityManagerService.this) {
865 appDiedLocked(mApp, mPid, mAppThread);
866 }
867 }
868 }
869
870 static final int SHOW_ERROR_MSG = 1;
871 static final int SHOW_NOT_RESPONDING_MSG = 2;
872 static final int SHOW_FACTORY_ERROR_MSG = 3;
873 static final int UPDATE_CONFIGURATION_MSG = 4;
874 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
875 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 static final int SERVICE_TIMEOUT_MSG = 12;
877 static final int UPDATE_TIME_ZONE = 13;
878 static final int SHOW_UID_ERROR_MSG = 14;
879 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700881 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700882 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800883 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700884 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
885 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700886 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700887 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700888 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700889 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700890 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700891 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700892 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700893 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700894 static final int REPORT_USER_SWITCH_MSG = 34;
895 static final int CONTINUE_USER_SWITCH_MSG = 35;
896 static final int USER_SWITCH_TIMEOUT_MSG = 36;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800898 static final int FIRST_ACTIVITY_STACK_MSG = 100;
899 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
900 static final int FIRST_COMPAT_MODE_MSG = 300;
901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700903 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700904 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
906 final Handler mHandler = new Handler() {
907 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 //}
910
911 public void handleMessage(Message msg) {
912 switch (msg.what) {
913 case SHOW_ERROR_MSG: {
914 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 synchronized (ActivityManagerService.this) {
916 ProcessRecord proc = (ProcessRecord)data.get("app");
917 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800918 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 return;
920 }
921 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700922 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800923 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 d.show();
925 proc.crashDialog = d;
926 } else {
927 // The device is asleep, so just pretend that the user
928 // saw a crash dialog and hit "force quit".
929 res.set(0);
930 }
931 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700932
933 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 } break;
935 case SHOW_NOT_RESPONDING_MSG: {
936 synchronized (ActivityManagerService.this) {
937 HashMap data = (HashMap) msg.obj;
938 ProcessRecord proc = (ProcessRecord)data.get("app");
939 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800940 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 return;
942 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800943
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700944 Intent intent = new Intent("android.intent.action.ANR");
945 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800946 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
947 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700948 }
949 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800950 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700951 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800952
Justin Kohbc52ca22012-03-29 15:11:44 -0700953 if (mShowDialogs) {
954 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700955 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700956 d.show();
957 proc.anrDialog = d;
958 } else {
959 // Just kill the app if there is no dialog to be shown.
960 killAppAtUsersRequest(proc, null);
961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700963
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700964 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700966 case SHOW_STRICT_MODE_VIOLATION_MSG: {
967 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
968 synchronized (ActivityManagerService.this) {
969 ProcessRecord proc = (ProcessRecord) data.get("app");
970 if (proc == null) {
971 Slog.e(TAG, "App not found when showing strict mode dialog.");
972 break;
973 }
974 if (proc.crashDialog != null) {
975 Slog.e(TAG, "App already has strict mode dialog: " + proc);
976 return;
977 }
978 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700979 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700980 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
981 d.show();
982 proc.crashDialog = d;
983 } else {
984 // The device is asleep, so just pretend that the user
985 // saw a crash dialog and hit "force quit".
986 res.set(0);
987 }
988 }
989 ensureBootCompleted();
990 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 case SHOW_FACTORY_ERROR_MSG: {
992 Dialog d = new FactoryErrorDialog(
993 mContext, msg.getData().getCharSequence("msg"));
994 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700995 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 } break;
997 case UPDATE_CONFIGURATION_MSG: {
998 final ContentResolver resolver = mContext.getContentResolver();
999 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1000 } break;
1001 case GC_BACKGROUND_PROCESSES_MSG: {
1002 synchronized (ActivityManagerService.this) {
1003 performAppGcsIfAppropriateLocked();
1004 }
1005 } break;
1006 case WAIT_FOR_DEBUGGER_MSG: {
1007 synchronized (ActivityManagerService.this) {
1008 ProcessRecord app = (ProcessRecord)msg.obj;
1009 if (msg.arg1 != 0) {
1010 if (!app.waitedForDebugger) {
1011 Dialog d = new AppWaitingForDebuggerDialog(
1012 ActivityManagerService.this,
1013 mContext, app);
1014 app.waitDialog = d;
1015 app.waitedForDebugger = true;
1016 d.show();
1017 }
1018 } else {
1019 if (app.waitDialog != null) {
1020 app.waitDialog.dismiss();
1021 app.waitDialog = null;
1022 }
1023 }
1024 }
1025 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001027 if (mDidDexOpt) {
1028 mDidDexOpt = false;
1029 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1030 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001031 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001032 return;
1033 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001034 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 } break;
1036 case UPDATE_TIME_ZONE: {
1037 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 if (r.thread != null) {
1041 try {
1042 r.thread.updateTimeZone();
1043 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001044 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 }
1047 }
1048 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001049 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001050 case CLEAR_DNS_CACHE: {
1051 synchronized (ActivityManagerService.this) {
1052 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1053 ProcessRecord r = mLruProcesses.get(i);
1054 if (r.thread != null) {
1055 try {
1056 r.thread.clearDnsCache();
1057 } catch (RemoteException ex) {
1058 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1059 }
1060 }
1061 }
1062 }
1063 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001064 case UPDATE_HTTP_PROXY: {
1065 ProxyProperties proxy = (ProxyProperties)msg.obj;
1066 String host = "";
1067 String port = "";
1068 String exclList = "";
1069 if (proxy != null) {
1070 host = proxy.getHost();
1071 port = Integer.toString(proxy.getPort());
1072 exclList = proxy.getExclusionList();
1073 }
1074 synchronized (ActivityManagerService.this) {
1075 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1076 ProcessRecord r = mLruProcesses.get(i);
1077 if (r.thread != null) {
1078 try {
1079 r.thread.setHttpProxy(host, port, exclList);
1080 } catch (RemoteException ex) {
1081 Slog.w(TAG, "Failed to update http proxy for: " +
1082 r.info.processName);
1083 }
1084 }
1085 }
1086 }
1087 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001089 String title = "System UIDs Inconsistent";
1090 String text = "UIDs on the system are inconsistent, you need to wipe your"
1091 + " data partition or your device will be unstable.";
1092 Log.e(TAG, title + ": " + text);
1093 if (mShowDialogs) {
1094 // XXX This is a temporary dialog, no need to localize.
1095 AlertDialog d = new BaseErrorDialog(mContext);
1096 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1097 d.setCancelable(false);
1098 d.setTitle(title);
1099 d.setMessage(text);
1100 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1101 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1102 mUidAlert = d;
1103 d.show();
1104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 } break;
1106 case IM_FEELING_LUCKY_MSG: {
1107 if (mUidAlert != null) {
1108 mUidAlert.dismiss();
1109 mUidAlert = null;
1110 }
1111 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001113 if (mDidDexOpt) {
1114 mDidDexOpt = false;
1115 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1116 nmsg.obj = msg.obj;
1117 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1118 return;
1119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 ProcessRecord app = (ProcessRecord)msg.obj;
1121 synchronized (ActivityManagerService.this) {
1122 processStartTimedOutLocked(app);
1123 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001124 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001125 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1126 synchronized (ActivityManagerService.this) {
1127 doPendingActivityLaunchesLocked(true);
1128 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001129 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001130 case KILL_APPLICATION_MSG: {
1131 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001132 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001133 boolean restart = (msg.arg2 == 1);
1134 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001135 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1136 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001137 }
1138 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001139 case FINALIZE_PENDING_INTENT_MSG: {
1140 ((PendingIntentRecord)msg.obj).completeFinalize();
1141 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001142 case POST_HEAVY_NOTIFICATION_MSG: {
1143 INotificationManager inm = NotificationManager.getService();
1144 if (inm == null) {
1145 return;
1146 }
1147
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001148 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001149 ProcessRecord process = root.app;
1150 if (process == null) {
1151 return;
1152 }
1153
1154 try {
1155 Context context = mContext.createPackageContext(process.info.packageName, 0);
1156 String text = mContext.getString(R.string.heavy_weight_notification,
1157 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1158 Notification notification = new Notification();
1159 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1160 notification.when = 0;
1161 notification.flags = Notification.FLAG_ONGOING_EVENT;
1162 notification.tickerText = text;
1163 notification.defaults = 0; // please be quiet
1164 notification.sound = null;
1165 notification.vibrate = null;
1166 notification.setLatestEventInfo(context, text,
1167 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001168 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1169 PendingIntent.FLAG_CANCEL_CURRENT, null,
1170 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001171
1172 try {
1173 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001174 inm.enqueueNotificationWithTag("android", null,
1175 R.string.heavy_weight_notification,
1176 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001177 } catch (RuntimeException e) {
1178 Slog.w(ActivityManagerService.TAG,
1179 "Error showing notification for heavy-weight app", e);
1180 } catch (RemoteException e) {
1181 }
1182 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001183 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001184 }
1185 } break;
1186 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1187 INotificationManager inm = NotificationManager.getService();
1188 if (inm == null) {
1189 return;
1190 }
1191 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001192 inm.cancelNotificationWithTag("android", null,
1193 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001194 } catch (RuntimeException e) {
1195 Slog.w(ActivityManagerService.TAG,
1196 "Error canceling notification for service", e);
1197 } catch (RemoteException e) {
1198 }
1199 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001200 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1201 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001202 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001203 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001204 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1205 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001206 }
1207 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001208 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1209 synchronized (ActivityManagerService.this) {
1210 ActivityRecord ar = (ActivityRecord)msg.obj;
1211 if (mCompatModeDialog != null) {
1212 if (mCompatModeDialog.mAppInfo.packageName.equals(
1213 ar.info.applicationInfo.packageName)) {
1214 return;
1215 }
1216 mCompatModeDialog.dismiss();
1217 mCompatModeDialog = null;
1218 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001219 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001220 if (mCompatModePackages.getPackageAskCompatModeLocked(
1221 ar.packageName)) {
1222 int mode = mCompatModePackages.computeCompatModeLocked(
1223 ar.info.applicationInfo);
1224 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1225 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1226 mCompatModeDialog = new CompatModeDialog(
1227 ActivityManagerService.this, mContext,
1228 ar.info.applicationInfo);
1229 mCompatModeDialog.show();
1230 }
1231 }
1232 }
1233 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001234 break;
1235 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001236 case DISPATCH_PROCESSES_CHANGED: {
1237 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001238 break;
1239 }
1240 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001241 final int pid = msg.arg1;
1242 final int uid = msg.arg2;
1243 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001244 break;
1245 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001246 case REPORT_MEM_USAGE: {
1247 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1248 if (!isDebuggable) {
1249 return;
1250 }
1251 synchronized (ActivityManagerService.this) {
1252 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1254 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001255 // avoid spamming.
1256 return;
1257 }
1258 mLastMemUsageReportTime = now;
1259 }
1260 Thread thread = new Thread() {
1261 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001262 StringBuilder dropBuilder = new StringBuilder(1024);
1263 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001264 StringWriter oomSw = new StringWriter();
1265 PrintWriter oomPw = new PrintWriter(oomSw);
1266 StringWriter catSw = new StringWriter();
1267 PrintWriter catPw = new PrintWriter(catSw);
1268 String[] emptyArgs = new String[] { };
1269 StringBuilder tag = new StringBuilder(128);
1270 StringBuilder stack = new StringBuilder(128);
1271 tag.append("Low on memory -- ");
1272 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1273 tag, stack);
1274 dropBuilder.append(stack);
1275 dropBuilder.append('\n');
1276 dropBuilder.append('\n');
1277 String oomString = oomSw.toString();
1278 dropBuilder.append(oomString);
1279 dropBuilder.append('\n');
1280 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001281 try {
1282 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1283 "procrank", });
1284 final InputStreamReader converter = new InputStreamReader(
1285 proc.getInputStream());
1286 BufferedReader in = new BufferedReader(converter);
1287 String line;
1288 while (true) {
1289 line = in.readLine();
1290 if (line == null) {
1291 break;
1292 }
1293 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001294 logBuilder.append(line);
1295 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001296 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001297 dropBuilder.append(line);
1298 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001299 }
1300 converter.close();
1301 } catch (IOException e) {
1302 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001303 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001304 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001305 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001306 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001307 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1308 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001309 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001310 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001311 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001312 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001313 addErrorToDropBox("lowmem", null, "system_server", null,
1314 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001315 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001316 synchronized (ActivityManagerService.this) {
1317 long now = SystemClock.uptimeMillis();
1318 if (mLastMemUsageReportTime < now) {
1319 mLastMemUsageReportTime = now;
1320 }
1321 }
1322 }
1323 };
1324 thread.start();
1325 break;
1326 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001327 case REPORT_USER_SWITCH_MSG: {
1328 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1329 break;
1330 }
1331 case CONTINUE_USER_SWITCH_MSG: {
1332 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1333 break;
1334 }
1335 case USER_SWITCH_TIMEOUT_MSG: {
1336 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1337 break;
1338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340 }
1341 };
1342
1343 public static void setSystemProcess() {
1344 try {
1345 ActivityManagerService m = mSelf;
1346
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001347 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001349 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001350 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 if (MONITOR_CPU_USAGE) {
1352 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 ServiceManager.addService("permission", new PermissionController(m));
1355
1356 ApplicationInfo info =
1357 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001358 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001359 mSystemThread.installSystemApplicationInfo(info);
1360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 synchronized (mSelf) {
1362 ProcessRecord app = mSelf.newProcessRecordLocked(
1363 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001364 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001366 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001367 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001368 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 synchronized (mSelf.mPidsSelfLocked) {
1370 mSelf.mPidsSelfLocked.put(app.pid, app);
1371 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001372 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374 } catch (PackageManager.NameNotFoundException e) {
1375 throw new RuntimeException(
1376 "Unable to find android system package", e);
1377 }
1378 }
1379
1380 public void setWindowManager(WindowManagerService wm) {
1381 mWindowManager = wm;
1382 }
1383
1384 public static final Context main(int factoryTest) {
1385 AThread thr = new AThread();
1386 thr.start();
1387
1388 synchronized (thr) {
1389 while (thr.mService == null) {
1390 try {
1391 thr.wait();
1392 } catch (InterruptedException e) {
1393 }
1394 }
1395 }
1396
1397 ActivityManagerService m = thr.mService;
1398 mSelf = m;
1399 ActivityThread at = ActivityThread.systemMain();
1400 mSystemThread = at;
1401 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001402 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 m.mContext = context;
1404 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001405 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406
1407 m.mBatteryStatsService.publish(context);
1408 m.mUsageStatsService.publish(context);
1409
1410 synchronized (thr) {
1411 thr.mReady = true;
1412 thr.notifyAll();
1413 }
1414
1415 m.startRunning(null, null, null, null);
1416
1417 return context;
1418 }
1419
1420 public static ActivityManagerService self() {
1421 return mSelf;
1422 }
1423
1424 static class AThread extends Thread {
1425 ActivityManagerService mService;
1426 boolean mReady = false;
1427
1428 public AThread() {
1429 super("ActivityManager");
1430 }
1431
1432 public void run() {
1433 Looper.prepare();
1434
1435 android.os.Process.setThreadPriority(
1436 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001437 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438
1439 ActivityManagerService m = new ActivityManagerService();
1440
1441 synchronized (this) {
1442 mService = m;
1443 notifyAll();
1444 }
1445
1446 synchronized (this) {
1447 while (!mReady) {
1448 try {
1449 wait();
1450 } catch (InterruptedException e) {
1451 }
1452 }
1453 }
1454
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001455 // For debug builds, log event loop stalls to dropbox for analysis.
1456 if (StrictMode.conditionallyEnableDebugLogging()) {
1457 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1458 }
1459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 Looper.loop();
1461 }
1462 }
1463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 static class MemBinder extends Binder {
1465 ActivityManagerService mActivityManagerService;
1466 MemBinder(ActivityManagerService activityManagerService) {
1467 mActivityManagerService = activityManagerService;
1468 }
1469
1470 @Override
1471 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001472 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1473 != PackageManager.PERMISSION_GRANTED) {
1474 pw.println("Permission Denial: can't dump meminfo from from pid="
1475 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1476 + " without permission " + android.Manifest.permission.DUMP);
1477 return;
1478 }
1479
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001480 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001481 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483 }
1484
Chet Haase9c1e23b2011-03-24 10:51:31 -07001485 static class GraphicsBinder extends Binder {
1486 ActivityManagerService mActivityManagerService;
1487 GraphicsBinder(ActivityManagerService activityManagerService) {
1488 mActivityManagerService = activityManagerService;
1489 }
1490
1491 @Override
1492 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001493 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1494 != PackageManager.PERMISSION_GRANTED) {
1495 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1496 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1497 + " without permission " + android.Manifest.permission.DUMP);
1498 return;
1499 }
1500
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001501 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001502 }
1503 }
1504
Jeff Brown6754ba22011-12-14 20:20:01 -08001505 static class DbBinder extends Binder {
1506 ActivityManagerService mActivityManagerService;
1507 DbBinder(ActivityManagerService activityManagerService) {
1508 mActivityManagerService = activityManagerService;
1509 }
1510
1511 @Override
1512 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1513 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1514 != PackageManager.PERMISSION_GRANTED) {
1515 pw.println("Permission Denial: can't dump dbinfo from from pid="
1516 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1517 + " without permission " + android.Manifest.permission.DUMP);
1518 return;
1519 }
1520
1521 mActivityManagerService.dumpDbInfo(fd, pw, args);
1522 }
1523 }
1524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 static class CpuBinder extends Binder {
1526 ActivityManagerService mActivityManagerService;
1527 CpuBinder(ActivityManagerService activityManagerService) {
1528 mActivityManagerService = activityManagerService;
1529 }
1530
1531 @Override
1532 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001533 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1534 != PackageManager.PERMISSION_GRANTED) {
1535 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1536 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1537 + " without permission " + android.Manifest.permission.DUMP);
1538 return;
1539 }
1540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001542 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1543 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1544 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548
1549 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001550 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001551
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001552 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1553 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1554 mBroadcastQueues[0] = mFgBroadcastQueue;
1555 mBroadcastQueues[1] = mBgBroadcastQueue;
1556
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001557 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001558 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 File dataDir = Environment.getDataDirectory();
1561 File systemDir = new File(dataDir, "system");
1562 systemDir.mkdirs();
1563 mBatteryStatsService = new BatteryStatsService(new File(
1564 systemDir, "batterystats.bin").toString());
1565 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001566 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001567 mOnBattery = DEBUG_POWER ? true
1568 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001569 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001571 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001572 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001573 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001575 // User 0 is the first and only user that runs at boot.
1576 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001577 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001578 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001579
Jack Palevichb90d28c2009-07-22 15:35:24 -07001580 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1581 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1582
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001583 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001584 mConfiguration.setLocale(Locale.getDefault());
1585
Dianne Hackborn813075a62011-11-14 17:45:19 -08001586 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 mProcessStats.init();
1588
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001589 mCompatModePackages = new CompatModePackages(this, systemDir);
1590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 // Add ourself to the Watchdog monitors.
1592 Watchdog.getInstance().addMonitor(this);
1593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 mProcessStatsThread = new Thread("ProcessStats") {
1595 public void run() {
1596 while (true) {
1597 try {
1598 try {
1599 synchronized(this) {
1600 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001601 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001603 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 // + ", write delay=" + nextWriteDelay);
1605 if (nextWriteDelay < nextCpuDelay) {
1606 nextCpuDelay = nextWriteDelay;
1607 }
1608 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001609 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 this.wait(nextCpuDelay);
1611 }
1612 }
1613 } catch (InterruptedException e) {
1614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 updateCpuStatsNow();
1616 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001617 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 }
1619 }
1620 }
1621 };
1622 mProcessStatsThread.start();
1623 }
1624
1625 @Override
1626 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1627 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001628 if (code == SYSPROPS_TRANSACTION) {
1629 // We need to tell all apps about the system property change.
1630 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1631 synchronized(this) {
1632 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1633 final int NA = apps.size();
1634 for (int ia=0; ia<NA; ia++) {
1635 ProcessRecord app = apps.valueAt(ia);
1636 if (app.thread != null) {
1637 procs.add(app.thread.asBinder());
1638 }
1639 }
1640 }
1641 }
1642
1643 int N = procs.size();
1644 for (int i=0; i<N; i++) {
1645 Parcel data2 = Parcel.obtain();
1646 try {
1647 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1648 } catch (RemoteException e) {
1649 }
1650 data2.recycle();
1651 }
1652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 try {
1654 return super.onTransact(code, data, reply, flags);
1655 } catch (RuntimeException e) {
1656 // The activity manager only throws security exceptions, so let's
1657 // log all others.
1658 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001659 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 throw e;
1662 }
1663 }
1664
1665 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001666 final long now = SystemClock.uptimeMillis();
1667 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1668 return;
1669 }
1670 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1671 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 mProcessStatsThread.notify();
1673 }
1674 }
1675 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 void updateCpuStatsNow() {
1678 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001679 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 final long now = SystemClock.uptimeMillis();
1681 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001684 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1685 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 haveNewCpuStats = true;
1687 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001688 //Slog.i(TAG, mProcessStats.printCurrentState());
1689 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 // + mProcessStats.getTotalCpuPercent() + "%");
1691
Joe Onorato8a9b2202010-02-26 18:56:32 -08001692 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 if ("true".equals(SystemProperties.get("events.cpu"))) {
1694 int user = mProcessStats.getLastUserTime();
1695 int system = mProcessStats.getLastSystemTime();
1696 int iowait = mProcessStats.getLastIoWaitTime();
1697 int irq = mProcessStats.getLastIrqTime();
1698 int softIrq = mProcessStats.getLastSoftIrqTime();
1699 int idle = mProcessStats.getLastIdleTime();
1700
1701 int total = user + system + iowait + irq + softIrq + idle;
1702 if (total == 0) total = 1;
1703
Doug Zongker2bec3d42009-12-04 12:52:44 -08001704 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 ((user+system+iowait+irq+softIrq) * 100) / total,
1706 (user * 100) / total,
1707 (system * 100) / total,
1708 (iowait * 100) / total,
1709 (irq * 100) / total,
1710 (softIrq * 100) / total);
1711 }
1712 }
1713
Amith Yamasanie43530a2009-08-21 13:11:37 -07001714 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001715 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001716 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 synchronized(mPidsSelfLocked) {
1718 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001719 if (mOnBattery) {
1720 int perc = bstats.startAddingCpuLocked();
1721 int totalUTime = 0;
1722 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001723 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001725 ProcessStats.Stats st = mProcessStats.getStats(i);
1726 if (!st.working) {
1727 continue;
1728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001730 int otherUTime = (st.rel_utime*perc)/100;
1731 int otherSTime = (st.rel_stime*perc)/100;
1732 totalUTime += otherUTime;
1733 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 if (pr != null) {
1735 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001736 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1737 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001738 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001739 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001740 } else {
1741 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001742 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001743 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001744 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1745 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001746 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
1749 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001750 bstats.finishAddingCpuLocked(perc, totalUTime,
1751 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753 }
1754 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1757 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001758 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 }
1760 }
1761 }
1762 }
1763
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001764 @Override
1765 public void batteryNeedsCpuUpdate() {
1766 updateCpuStatsNow();
1767 }
1768
1769 @Override
1770 public void batteryPowerChanged(boolean onBattery) {
1771 // When plugging in, update the CPU stats first before changing
1772 // the plug state.
1773 updateCpuStatsNow();
1774 synchronized (this) {
1775 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001776 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001777 }
1778 }
1779 }
1780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 /**
1782 * Initialize the application bind args. These are passed to each
1783 * process when the bindApplication() IPC is sent to the process. They're
1784 * lazily setup to make sure the services are running when they're asked for.
1785 */
1786 private HashMap<String, IBinder> getCommonServicesLocked() {
1787 if (mAppBindArgs == null) {
1788 mAppBindArgs = new HashMap<String, IBinder>();
1789
1790 // Setup the application init args
1791 mAppBindArgs.put("package", ServiceManager.getService("package"));
1792 mAppBindArgs.put("window", ServiceManager.getService("window"));
1793 mAppBindArgs.put(Context.ALARM_SERVICE,
1794 ServiceManager.getService(Context.ALARM_SERVICE));
1795 }
1796 return mAppBindArgs;
1797 }
1798
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001799 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 if (mFocusedActivity != r) {
1801 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001802 if (r != null) {
1803 mWindowManager.setFocusedApp(r.appToken, true);
1804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
1806 }
1807
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001808 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001810 int lrui = mLruProcesses.indexOf(app);
1811 if (lrui >= 0) mLruProcesses.remove(lrui);
1812
1813 int i = mLruProcesses.size()-1;
1814 int skipTop = 0;
1815
Dianne Hackborn906497c2010-05-10 15:57:38 -07001816 app.lruSeq = mLruSeq;
1817
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001818 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001819 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001820 if (app.activities.size() > 0) {
1821 // If this process has activities, we more strongly want to keep
1822 // it around.
1823 app.lruWeight = app.lastActivityTime;
1824 } else if (app.pubProviders.size() > 0) {
1825 // If this process contains content providers, we want to keep
1826 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001827 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001828 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001829 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001830 } else {
1831 // If this process doesn't have activities, we less strongly
1832 // want to keep it around, and generally want to avoid getting
1833 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001834 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001835 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001836 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001837 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001838
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001839 while (i >= 0) {
1840 ProcessRecord p = mLruProcesses.get(i);
1841 // If this app shouldn't be in front of the first N background
1842 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001843 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001844 skipTop--;
1845 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001846 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001847 mLruProcesses.add(i+1, app);
1848 break;
1849 }
1850 i--;
1851 }
1852 if (i < 0) {
1853 mLruProcesses.add(0, app);
1854 }
1855
Dianne Hackborn906497c2010-05-10 15:57:38 -07001856 // If the app is currently using a content provider or service,
1857 // bump those processes as well.
1858 if (app.connections.size() > 0) {
1859 for (ConnectionRecord cr : app.connections) {
1860 if (cr.binding != null && cr.binding.service != null
1861 && cr.binding.service.app != null
1862 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001863 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001864 }
1865 }
1866 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001867 for (int j=app.conProviders.size()-1; j>=0; j--) {
1868 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1869 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001870 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001871 }
1872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
1874
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001875 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001876 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001877 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001878 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001879
1880 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1881 if (oomAdj) {
1882 updateOomAdjLocked();
1883 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001884 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001885
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001886 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001888 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001889 // The system gets to run in any process. If there are multiple
1890 // processes with the same uid, just pick the first (this
1891 // should never happen).
1892 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1893 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001894 if (procs == null) return null;
1895 final int N = procs.size();
1896 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001897 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900 ProcessRecord proc = mProcessNames.get(processName, uid);
1901 return proc;
1902 }
1903
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001904 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001905 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001906 try {
1907 if (pm.performDexOpt(packageName)) {
1908 mDidDexOpt = true;
1909 }
1910 } catch (RemoteException e) {
1911 }
1912 }
1913
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001914 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 int transit = mWindowManager.getPendingAppTransition();
1916 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1917 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1918 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1919 }
1920
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001921 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001923 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1924 boolean isolated) {
1925 ProcessRecord app;
1926 if (!isolated) {
1927 app = getProcessRecordLocked(processName, info.uid);
1928 } else {
1929 // If this is an isolated process, it can't re-use an existing process.
1930 app = null;
1931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 // We don't have to do anything more if:
1933 // (1) There is an existing application record; and
1934 // (2) The caller doesn't think it is dead, OR there is no thread
1935 // object attached to it so we know it couldn't have crashed; and
1936 // (3) There is a pid assigned to it, so it is either starting or
1937 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001938 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 + " app=" + app + " knownToBeDead=" + knownToBeDead
1940 + " thread=" + (app != null ? app.thread : null)
1941 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001942 if (app != null && app.pid > 0) {
1943 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001944 // We already have the app running, or are waiting for it to
1945 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001946 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001947 // If this is a new package in the process, add the package to the list
1948 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001949 return app;
1950 } else {
1951 // An application record is attached to a previous process,
1952 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001953 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001954 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 String hostingNameStr = hostingName != null
1959 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001960
1961 if (!isolated) {
1962 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1963 // If we are in the background, then check to see if this process
1964 // is bad. If so, we will just silently fail.
1965 if (mBadProcesses.get(info.processName, info.uid) != null) {
1966 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1967 + "/" + info.processName);
1968 return null;
1969 }
1970 } else {
1971 // When the user is explicitly starting a process, then clear its
1972 // crash count so that we won't make it bad until they see at
1973 // least one crash dialog again, and make the process good again
1974 // if it had been bad.
1975 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001976 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001977 mProcessCrashTimes.remove(info.processName, info.uid);
1978 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001979 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
1980 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001981 info.processName);
1982 mBadProcesses.remove(info.processName, info.uid);
1983 if (app != null) {
1984 app.bad = false;
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987 }
1988 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001991 app = newProcessRecordLocked(null, info, processName, isolated);
1992 if (app == null) {
1993 Slog.w(TAG, "Failed making new process record for "
1994 + processName + "/" + info.uid + " isolated=" + isolated);
1995 return null;
1996 }
1997 mProcessNames.put(processName, app.uid, app);
1998 if (isolated) {
1999 mIsolatedProcesses.put(app.uid, app);
2000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 } else {
2002 // If this is a new package in the process, add the package to the list
2003 app.addPackage(info.packageName);
2004 }
2005
2006 // If the system is not ready yet, then hold off on starting this
2007 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002008 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002009 && !isAllowedWhileBooting(info)
2010 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 if (!mProcessesOnHold.contains(app)) {
2012 mProcessesOnHold.add(app);
2013 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002014 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 return app;
2016 }
2017
2018 startProcessLocked(app, hostingType, hostingNameStr);
2019 return (app.pid != 0) ? app : null;
2020 }
2021
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002022 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2023 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2024 }
2025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 private final void startProcessLocked(ProcessRecord app,
2027 String hostingType, String hostingNameStr) {
2028 if (app.pid > 0 && app.pid != MY_PID) {
2029 synchronized (mPidsSelfLocked) {
2030 mPidsSelfLocked.remove(app.pid);
2031 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2032 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002033 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 }
2035
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002036 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2037 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 mProcessesOnHold.remove(app);
2039
2040 updateCpuStats();
2041
2042 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2043 mProcDeaths[0] = 0;
2044
2045 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002046 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002049 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002050 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002051 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002052 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002053 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002054 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002055
2056 if (Environment.isExternalStorageEmulated()) {
2057 if (pm.checkPermission(
2058 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2059 app.info.packageName) == PERMISSION_GRANTED) {
2060 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2061 } else {
2062 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2063 }
2064 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002065 } catch (PackageManager.NameNotFoundException e) {
2066 Slog.w(TAG, "Unable to retrieve gids", e);
2067 }
Kenny Roote091f222012-09-11 15:01:26 -07002068
2069 /*
2070 * Add shared application GID so applications can share some
2071 * resources like shared libraries
2072 */
2073 if (permGids == null) {
2074 gids = new int[1];
2075 } else {
2076 gids = new int[permGids.length + 1];
2077 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2078 }
2079 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2082 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2083 && mTopComponent != null
2084 && app.processName.equals(mTopComponent.getPackageName())) {
2085 uid = 0;
2086 }
2087 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2088 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2089 uid = 0;
2090 }
2091 }
2092 int debugFlags = 0;
2093 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2094 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002095 // Also turn on CheckJNI for debuggable apps. It's quite
2096 // awkward to turn on otherwise.
2097 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002099 // Run the app in safe mode if its manifest requests so or the
2100 // system is booted in safe mode.
2101 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2102 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002103 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2106 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2107 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002108 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2109 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 if ("1".equals(SystemProperties.get("debug.assert"))) {
2112 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2113 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002114
2115 // Start the process. It will either succeed and return a result containing
2116 // the PID of the new process, or else throw a RuntimeException.
2117 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002118 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002119 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2122 synchronized (bs) {
2123 if (bs.isOnBattery()) {
2124 app.batteryStats.incStartsLocked();
2125 }
2126 }
2127
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002128 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2129 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 app.processName, hostingType,
2131 hostingNameStr != null ? hostingNameStr : "");
2132
2133 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002134 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002137 StringBuilder buf = mStringBuilder;
2138 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 buf.append("Start proc ");
2140 buf.append(app.processName);
2141 buf.append(" for ");
2142 buf.append(hostingType);
2143 if (hostingNameStr != null) {
2144 buf.append(" ");
2145 buf.append(hostingNameStr);
2146 }
2147 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002148 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 buf.append(" uid=");
2150 buf.append(uid);
2151 buf.append(" gids={");
2152 if (gids != null) {
2153 for (int gi=0; gi<gids.length; gi++) {
2154 if (gi != 0) buf.append(", ");
2155 buf.append(gids[gi]);
2156
2157 }
2158 }
2159 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002160 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002161 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002162 app.usingWrapper = startResult.usingWrapper;
2163 app.removed = false;
2164 synchronized (mPidsSelfLocked) {
2165 this.mPidsSelfLocked.put(startResult.pid, app);
2166 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2167 msg.obj = app;
2168 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2169 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 }
2171 } catch (RuntimeException e) {
2172 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002173 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002174 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 }
2176 }
2177
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002178 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 if (resumed) {
2180 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2181 } else {
2182 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2183 }
2184 }
2185
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002186 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002187 if (mHeadless) {
2188 // Added because none of the other calls to ensureBootCompleted seem to fire
2189 // when running headless.
2190 ensureBootCompleted();
2191 return false;
2192 }
2193
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002194 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2195 && mTopAction == null) {
2196 // We are running in factory test mode, but unable to find
2197 // the factory test app, so just sit around displaying the
2198 // error message and don't try to start anything.
2199 return false;
2200 }
2201 Intent intent = new Intent(
2202 mTopAction,
2203 mTopData != null ? Uri.parse(mTopData) : null);
2204 intent.setComponent(mTopComponent);
2205 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2206 intent.addCategory(Intent.CATEGORY_HOME);
2207 }
2208 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002209 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002210 if (aInfo != null) {
2211 intent.setComponent(new ComponentName(
2212 aInfo.applicationInfo.packageName, aInfo.name));
2213 // Don't do this if the home app is currently being
2214 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002215 aInfo = new ActivityInfo(aInfo);
2216 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002217 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2218 aInfo.applicationInfo.uid);
2219 if (app == null || app.instrumentationClass == null) {
2220 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002221 mMainStack.startActivityLocked(null, intent, null, aInfo,
2222 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002223 }
2224 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002225
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002226 return true;
2227 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002228
Amith Yamasani259d5e52012-08-31 15:11:01 -07002229 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2230 ActivityInfo ai = null;
2231 ComponentName comp = intent.getComponent();
2232 try {
2233 if (comp != null) {
2234 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2235 } else {
2236 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2237 intent,
2238 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2239 flags, userId);
2240
2241 if (info != null) {
2242 ai = info.activityInfo;
2243 }
2244 }
2245 } catch (RemoteException e) {
2246 // ignore
2247 }
2248
2249 return ai;
2250 }
2251
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002252 /**
2253 * Starts the "new version setup screen" if appropriate.
2254 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002255 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002256 // Only do this once per boot.
2257 if (mCheckedForSetup) {
2258 return;
2259 }
2260
2261 // We will show this screen if the current one is a different
2262 // version than the last one shown, and we are not running in
2263 // low-level factory test mode.
2264 final ContentResolver resolver = mContext.getContentResolver();
2265 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002266 Settings.Global.getInt(resolver,
2267 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002268 mCheckedForSetup = true;
2269
2270 // See if we should be showing the platform update setup UI.
2271 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2272 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2273 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2274
2275 // We don't allow third party apps to replace this.
2276 ResolveInfo ri = null;
2277 for (int i=0; ris != null && i<ris.size(); i++) {
2278 if ((ris.get(i).activityInfo.applicationInfo.flags
2279 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2280 ri = ris.get(i);
2281 break;
2282 }
2283 }
2284
2285 if (ri != null) {
2286 String vers = ri.activityInfo.metaData != null
2287 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2288 : null;
2289 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2290 vers = ri.activityInfo.applicationInfo.metaData.getString(
2291 Intent.METADATA_SETUP_VERSION);
2292 }
2293 String lastVers = Settings.Secure.getString(
2294 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2295 if (vers != null && !vers.equals(lastVers)) {
2296 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2297 intent.setComponent(new ComponentName(
2298 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002299 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2300 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002301 }
2302 }
2303 }
2304 }
2305
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002306 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002307 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002308 }
2309
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002310 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002311 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002312 throw new SecurityException("Isolated process not allowed to call " + caller);
2313 }
2314 }
2315
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002316 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002317 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002318 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002319 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2320 }
2321 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002322
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002323 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002324 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2325 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002326 synchronized (this) {
2327 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2328 }
2329 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002330
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002331 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002332 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002333 synchronized (this) {
2334 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2335 }
2336 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002337
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002338 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002339 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2340 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002341 synchronized (this) {
2342 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002343 }
2344 }
2345
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002346 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002347 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002348 synchronized (this) {
2349 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2350 }
2351 }
2352
2353 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002354 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2355 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002356 synchronized (this) {
2357 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2358 }
2359 }
2360
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002361 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002362 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002363 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002366 private void dispatchProcessesChanged() {
2367 int N;
2368 synchronized (this) {
2369 N = mPendingProcessChanges.size();
2370 if (mActiveProcessChanges.length < N) {
2371 mActiveProcessChanges = new ProcessChangeItem[N];
2372 }
2373 mPendingProcessChanges.toArray(mActiveProcessChanges);
2374 mAvailProcessChanges.addAll(mPendingProcessChanges);
2375 mPendingProcessChanges.clear();
2376 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2377 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002378 int i = mProcessObservers.beginBroadcast();
2379 while (i > 0) {
2380 i--;
2381 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2382 if (observer != null) {
2383 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002384 for (int j=0; j<N; j++) {
2385 ProcessChangeItem item = mActiveProcessChanges[j];
2386 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2387 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2388 + item.pid + " uid=" + item.uid + ": "
2389 + item.foregroundActivities);
2390 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2391 item.foregroundActivities);
2392 }
2393 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2394 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2395 + item.pid + " uid=" + item.uid + ": " + item.importance);
2396 observer.onImportanceChanged(item.pid, item.uid,
2397 item.importance);
2398 }
2399 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002400 } catch (RemoteException e) {
2401 }
2402 }
2403 }
2404 mProcessObservers.finishBroadcast();
2405 }
2406
2407 private void dispatchProcessDied(int pid, int uid) {
2408 int i = mProcessObservers.beginBroadcast();
2409 while (i > 0) {
2410 i--;
2411 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2412 if (observer != null) {
2413 try {
2414 observer.onProcessDied(pid, uid);
2415 } catch (RemoteException e) {
2416 }
2417 }
2418 }
2419 mProcessObservers.finishBroadcast();
2420 }
2421
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002423 final int N = mPendingActivityLaunches.size();
2424 if (N <= 0) {
2425 return;
2426 }
2427 for (int i=0; i<N; i++) {
2428 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002429 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002430 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002431 }
2432 mPendingActivityLaunches.clear();
2433 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002434
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002435 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002436 Intent intent, String resolvedType, IBinder resultTo,
2437 String resultWho, int requestCode, int startFlags,
2438 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002439 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002440 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002441 }
2442
2443 public final int startActivityAsUser(IApplicationThread caller,
2444 Intent intent, String resolvedType, IBinder resultTo,
2445 String resultWho, int requestCode, int startFlags,
2446 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002447 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002448 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002449 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002450 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002451 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2452 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002453 }
2454
2455 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 Intent intent, String resolvedType, IBinder resultTo,
2457 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002458 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002459 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002460 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002461 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002462 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002463 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002464 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002465 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002466 return res;
2467 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002468
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002469 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002470 Intent intent, String resolvedType, IBinder resultTo,
2471 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002472 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002473 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002474 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002475 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002476 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002478 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002479 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002480 }
2481
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002482 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002483 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002484 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002485 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002486 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002487 // Refuse possible leaked file descriptors
2488 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2489 throw new IllegalArgumentException("File descriptors passed in Intent");
2490 }
2491
2492 IIntentSender sender = intent.getTarget();
2493 if (!(sender instanceof PendingIntentRecord)) {
2494 throw new IllegalArgumentException("Bad PendingIntent object");
2495 }
2496
2497 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002498
2499 synchronized (this) {
2500 // If this is coming from the currently resumed activity, it is
2501 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002502 if (mMainStack.mResumedActivity != null
2503 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002504 Binder.getCallingUid()) {
2505 mAppSwitchesAllowedTime = 0;
2506 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002507 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002508 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2509 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002510 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002511 }
2512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002514 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 // Refuse possible leaked file descriptors
2516 if (intent != null && intent.hasFileDescriptors() == true) {
2517 throw new IllegalArgumentException("File descriptors passed in Intent");
2518 }
2519
2520 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002521 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2522 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002523 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 return false;
2525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 if (r.app == null || r.app.thread == null) {
2527 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002528 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 return false;
2530 }
2531 intent = new Intent(intent);
2532 // The caller is not allowed to change the data.
2533 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2534 // And we are resetting to find the next component...
2535 intent.setComponent(null);
2536
2537 ActivityInfo aInfo = null;
2538 try {
2539 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002540 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002542 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002543 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544
2545 // Look for the original activity in the list...
2546 final int N = resolves != null ? resolves.size() : 0;
2547 for (int i=0; i<N; i++) {
2548 ResolveInfo rInfo = resolves.get(i);
2549 if (rInfo.activityInfo.packageName.equals(r.packageName)
2550 && rInfo.activityInfo.name.equals(r.info.name)) {
2551 // We found the current one... the next matching is
2552 // after it.
2553 i++;
2554 if (i<N) {
2555 aInfo = resolves.get(i).activityInfo;
2556 }
2557 break;
2558 }
2559 }
2560 } catch (RemoteException e) {
2561 }
2562
2563 if (aInfo == null) {
2564 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002565 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 return false;
2567 }
2568
2569 intent.setComponent(new ComponentName(
2570 aInfo.applicationInfo.packageName, aInfo.name));
2571 intent.setFlags(intent.getFlags()&~(
2572 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2573 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2574 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2575 Intent.FLAG_ACTIVITY_NEW_TASK));
2576
2577 // Okay now we need to start the new activity, replacing the
2578 // currently running activity. This is a little tricky because
2579 // we want to start the new one as if the current one is finished,
2580 // but not finish the current one first so that there is no flicker.
2581 // And thus...
2582 final boolean wasFinishing = r.finishing;
2583 r.finishing = true;
2584
2585 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002586 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 final String resultWho = r.resultWho;
2588 final int requestCode = r.requestCode;
2589 r.resultTo = null;
2590 if (resultTo != null) {
2591 resultTo.removeResultsLocked(r, resultWho, requestCode);
2592 }
2593
2594 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002595 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002596 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2597 resultWho, requestCode, -1, r.launchedFromUid, 0,
2598 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 Binder.restoreCallingIdentity(origId);
2600
2601 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002602 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 return false;
2604 }
2605 return true;
2606 }
2607 }
2608
Dianne Hackborn41203752012-08-31 14:05:51 -07002609 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002611 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2612
Dianne Hackborn139748f2012-09-24 11:36:57 -07002613 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002614 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615
Amith Yamasani742a6712011-05-04 14:49:28 -07002616 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002617 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002618 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002619 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002620 }
2621
2622 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002623 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2624 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002625 enforceNotIsolatedCaller("startActivities");
Amith Yamasani95293862012-09-24 18:14:47 -07002626 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002627 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002628 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002629 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002630 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002631 }
2632
Dianne Hackborn41203752012-08-31 14:05:51 -07002633 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002634 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002635 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002636
Dianne Hackborn139748f2012-09-24 11:36:57 -07002637 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002638 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002639 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002640 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002641 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002644 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002646 // Quick case: check if the top-most recent task is the same.
2647 if (N > 0 && mRecentTasks.get(0) == task) {
2648 return;
2649 }
2650 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 for (int i=0; i<N; i++) {
2652 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002653 if (task.userId == tr.userId
2654 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2655 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 mRecentTasks.remove(i);
2657 i--;
2658 N--;
2659 if (task.intent == null) {
2660 // If the new recent task we are adding is not fully
2661 // specified, then replace it with the existing recent task.
2662 task = tr;
2663 }
2664 }
2665 }
2666 if (N >= MAX_RECENT_TASKS) {
2667 mRecentTasks.remove(N-1);
2668 }
2669 mRecentTasks.add(0, task);
2670 }
2671
2672 public void setRequestedOrientation(IBinder token,
2673 int requestedOrientation) {
2674 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002675 ActivityRecord r = mMainStack.isInStackLocked(token);
2676 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 return;
2678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002680 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002682 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002683 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 if (config != null) {
2685 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002686 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002687 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 }
2689 }
2690 Binder.restoreCallingIdentity(origId);
2691 }
2692 }
2693
2694 public int getRequestedOrientation(IBinder token) {
2695 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002696 ActivityRecord r = mMainStack.isInStackLocked(token);
2697 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2699 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002700 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 }
2702 }
2703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 /**
2705 * This is the internal entry point for handling Activity.finish().
2706 *
2707 * @param token The Binder token referencing the Activity we want to finish.
2708 * @param resultCode Result code, if any, from this Activity.
2709 * @param resultData Result data (Intent), if any, from this Activity.
2710 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002711 * @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 -08002712 */
2713 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2714 // Refuse possible leaked file descriptors
2715 if (resultData != null && resultData.hasFileDescriptors() == true) {
2716 throw new IllegalArgumentException("File descriptors passed in Intent");
2717 }
2718
2719 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002720 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002722 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 if (next != null) {
2724 // ask watcher if this is allowed
2725 boolean resumeOK = true;
2726 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002727 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002729 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 }
2731
2732 if (!resumeOK) {
2733 return false;
2734 }
2735 }
2736 }
2737 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002738 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002739 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 Binder.restoreCallingIdentity(origId);
2741 return res;
2742 }
2743 }
2744
Dianne Hackborn860755f2010-06-03 18:47:52 -07002745 public final void finishHeavyWeightApp() {
2746 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2747 != PackageManager.PERMISSION_GRANTED) {
2748 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2749 + Binder.getCallingPid()
2750 + ", uid=" + Binder.getCallingUid()
2751 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2752 Slog.w(TAG, msg);
2753 throw new SecurityException(msg);
2754 }
2755
2756 synchronized(this) {
2757 if (mHeavyWeightProcess == null) {
2758 return;
2759 }
2760
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002761 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002762 mHeavyWeightProcess.activities);
2763 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002764 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002765 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002766 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002767 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002768 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002769 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002770 }
2771 }
2772 }
2773
Dianne Hackborn41203752012-08-31 14:05:51 -07002774 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2775 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002776 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002777 }
2778 }
2779
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002780 public void crashApplication(int uid, int initialPid, String packageName,
2781 String message) {
2782 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2783 != PackageManager.PERMISSION_GRANTED) {
2784 String msg = "Permission Denial: crashApplication() from pid="
2785 + Binder.getCallingPid()
2786 + ", uid=" + Binder.getCallingUid()
2787 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2788 Slog.w(TAG, msg);
2789 throw new SecurityException(msg);
2790 }
2791
2792 synchronized(this) {
2793 ProcessRecord proc = null;
2794
2795 // Figure out which process to kill. We don't trust that initialPid
2796 // still has any relation to current pids, so must scan through the
2797 // list.
2798 synchronized (mPidsSelfLocked) {
2799 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2800 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002801 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002802 continue;
2803 }
2804 if (p.pid == initialPid) {
2805 proc = p;
2806 break;
2807 }
2808 for (String str : p.pkgList) {
2809 if (str.equals(packageName)) {
2810 proc = p;
2811 }
2812 }
2813 }
2814 }
2815
2816 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002817 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002818 + " initialPid=" + initialPid
2819 + " packageName=" + packageName);
2820 return;
2821 }
2822
2823 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002824 if (proc.pid == Process.myPid()) {
2825 Log.w(TAG, "crashApplication: trying to crash self!");
2826 return;
2827 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002828 long ident = Binder.clearCallingIdentity();
2829 try {
2830 proc.thread.scheduleCrash(message);
2831 } catch (RemoteException e) {
2832 }
2833 Binder.restoreCallingIdentity(ident);
2834 }
2835 }
2836 }
2837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 public final void finishSubActivity(IBinder token, String resultWho,
2839 int requestCode) {
2840 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002842 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 Binder.restoreCallingIdentity(origId);
2844 }
2845 }
2846
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002847 public boolean finishActivityAffinity(IBinder token) {
2848 synchronized(this) {
2849 final long origId = Binder.clearCallingIdentity();
2850 boolean res = mMainStack.finishActivityAffinityLocked(token);
2851 Binder.restoreCallingIdentity(origId);
2852 return res;
2853 }
2854 }
2855
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002856 public boolean willActivityBeVisible(IBinder token) {
2857 synchronized(this) {
2858 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002859 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2860 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002861 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002862 return true;
2863 }
2864 if (r.fullscreen && !r.finishing) {
2865 return false;
2866 }
2867 }
2868 return true;
2869 }
2870 }
2871
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002872 public void overridePendingTransition(IBinder token, String packageName,
2873 int enterAnim, int exitAnim) {
2874 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002875 ActivityRecord self = mMainStack.isInStackLocked(token);
2876 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002877 return;
2878 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002879
2880 final long origId = Binder.clearCallingIdentity();
2881
2882 if (self.state == ActivityState.RESUMED
2883 || self.state == ActivityState.PAUSING) {
2884 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002885 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002886 }
2887
2888 Binder.restoreCallingIdentity(origId);
2889 }
2890 }
2891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 * Main function for removing an existing process from the activity manager
2894 * as a result of that process going away. Clears out all connections
2895 * to the process.
2896 */
2897 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002898 boolean restarting, boolean allowRestart) {
2899 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002901 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
2903
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002904 if (mProfileProc == app) {
2905 clearProfilerLocked();
2906 }
2907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002909 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2910 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2911 mMainStack.mPausingActivity = null;
2912 }
2913 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2914 mMainStack.mLastPausedActivity = null;
2915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916
2917 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002918 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919
2920 boolean atTop = true;
2921 boolean hasVisibleActivities = false;
2922
2923 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002924 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002925 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 TAG, "Removing app " + app + " from history with " + i + " entries");
2927 while (i > 0) {
2928 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002929 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002930 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2932 if (r.app == app) {
2933 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002934 if (ActivityStack.DEBUG_ADD_REMOVE) {
2935 RuntimeException here = new RuntimeException("here");
2936 here.fillInStackTrace();
2937 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2938 + ": haveState=" + r.haveState
2939 + " stateNotNeeded=" + r.stateNotNeeded
2940 + " finishing=" + r.finishing
2941 + " state=" + r.state, here);
2942 }
2943 if (!r.finishing) {
2944 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002945 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002946 r.userId, System.identityHashCode(r),
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002947 r.task.taskId, r.shortComponentName,
2948 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002949 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002950 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951
2952 } else {
2953 // We have the current state for this activity, so
2954 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002955 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 TAG, "Keeping entry, setting app to null");
2957 if (r.visible) {
2958 hasVisibleActivities = true;
2959 }
2960 r.app = null;
2961 r.nowVisible = false;
2962 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002963 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2964 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 r.icicle = null;
2966 }
2967 }
2968
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002969 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 }
2971 atTop = false;
2972 }
2973
2974 app.activities.clear();
2975
2976 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002977 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 + " running instrumentation " + app.instrumentationClass);
2979 Bundle info = new Bundle();
2980 info.putString("shortMsg", "Process crashed.");
2981 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2982 }
2983
2984 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002985 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 // If there was nothing to resume, and we are not already
2987 // restarting this process, but there is a visible activity that
2988 // is hosted by the process... then make sure all visible
2989 // activities are running, taking care of restarting this
2990 // process.
2991 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002992 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 }
2994 }
2995 }
2996 }
2997
2998 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2999 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003001 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3002 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3004 return i;
3005 }
3006 }
3007 return -1;
3008 }
3009
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003010 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 IApplicationThread thread) {
3012 if (thread == null) {
3013 return null;
3014 }
3015
3016 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003017 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 }
3019
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003020 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 IApplicationThread thread) {
3022
3023 mProcDeaths[0]++;
3024
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003025 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3026 synchronized (stats) {
3027 stats.noteProcessDiedLocked(app.info.uid, pid);
3028 }
3029
Magnus Edlund7bb25812010-02-24 15:45:06 +01003030 // Clean up already done if the process has been re-started.
3031 if (app.pid == pid && app.thread != null &&
3032 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003033 if (!app.killedBackground) {
3034 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3035 + ") has died.");
3036 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003037 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003038 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 TAG, "Dying app: " + app + ", pid: " + pid
3040 + ", thread: " + thread.asBinder());
3041 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003042 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043
3044 if (doLowMem) {
3045 // If there are no longer any background processes running,
3046 // and the app that died was not running instrumentation,
3047 // then tell everyone we are now low on memory.
3048 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003049 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3050 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003051 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 haveBg = true;
3053 break;
3054 }
3055 }
3056
3057 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003058 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003059 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003060 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3061 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003062 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003063 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3064 // The low memory report is overriding any current
3065 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003066 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003067 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003068 rec.lastRequestedGc = 0;
3069 } else {
3070 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003072 rec.reportLowMemory = true;
3073 rec.lastLowMemory = now;
3074 mProcessesToGc.remove(rec);
3075 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
3077 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003078 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003079 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 }
3081 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003082 } else if (app.pid != pid) {
3083 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003084 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003085 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003086 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003087 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003088 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 + thread.asBinder());
3090 }
3091 }
3092
Dan Egnor42471dd2010-01-07 17:25:22 -08003093 /**
3094 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003095 * @param clearTraces causes the dump file to be erased prior to the new
3096 * traces being written, if true; when false, the new traces will be
3097 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003098 * @param firstPids of dalvik VM processes to dump stack traces for first
3099 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003100 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003101 * @return file containing stack traces, or null if no dump file is configured
3102 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003103 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003104 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003105 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3106 if (tracesPath == null || tracesPath.length() == 0) {
3107 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003109
3110 File tracesFile = new File(tracesPath);
3111 try {
3112 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003113 if (!tracesDir.exists()) {
3114 tracesFile.mkdirs();
3115 if (!SELinux.restorecon(tracesDir)) {
3116 return null;
3117 }
3118 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003119 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3120
Christopher Tate6ee412d2010-05-28 12:01:56 -07003121 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003122 tracesFile.createNewFile();
3123 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3124 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003125 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003126 return null;
3127 }
3128
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003129 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003130 return tracesFile;
3131 }
3132
3133 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003134 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003135 // Use a FileObserver to detect when traces finish writing.
3136 // The order of traces is considered important to maintain for legibility.
3137 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3138 public synchronized void onEvent(int event, String path) { notify(); }
3139 };
3140
3141 try {
3142 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003143
3144 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003145 if (firstPids != null) {
3146 try {
3147 int num = firstPids.size();
3148 for (int i = 0; i < num; i++) {
3149 synchronized (observer) {
3150 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3151 observer.wait(200); // Wait for write-close, give up after 200msec
3152 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003153 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003154 } catch (InterruptedException e) {
3155 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003156 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003157 }
3158
3159 // Next measure CPU usage.
3160 if (processStats != null) {
3161 processStats.init();
3162 System.gc();
3163 processStats.update();
3164 try {
3165 synchronized (processStats) {
3166 processStats.wait(500); // measure over 1/2 second.
3167 }
3168 } catch (InterruptedException e) {
3169 }
3170 processStats.update();
3171
3172 // We'll take the stack crawls of just the top apps using CPU.
3173 final int N = processStats.countWorkingStats();
3174 int numProcs = 0;
3175 for (int i=0; i<N && numProcs<5; i++) {
3176 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3177 if (lastPids.indexOfKey(stats.pid) >= 0) {
3178 numProcs++;
3179 try {
3180 synchronized (observer) {
3181 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3182 observer.wait(200); // Wait for write-close, give up after 200msec
3183 }
3184 } catch (InterruptedException e) {
3185 Log.wtf(TAG, e);
3186 }
3187
3188 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003189 }
3190 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003191
Dan Egnor42471dd2010-01-07 17:25:22 -08003192 } finally {
3193 observer.stopWatching();
3194 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003195
3196 if (nativeProcs != null) {
3197 int[] pids = Process.getPidsForCommands(nativeProcs);
3198 if (pids != null) {
3199 for (int pid : pids) {
3200 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3201 }
3202 }
3203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 }
3205
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003206 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003207 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003208 return;
3209 }
3210 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3211 if (tracesPath == null || tracesPath.length() == 0) {
3212 return;
3213 }
3214
3215 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3216 StrictMode.allowThreadDiskWrites();
3217 try {
3218 final File tracesFile = new File(tracesPath);
3219 final File tracesDir = tracesFile.getParentFile();
3220 final File tracesTmp = new File(tracesDir, "__tmp__");
3221 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003222 if (!tracesDir.exists()) {
3223 tracesFile.mkdirs();
3224 if (!SELinux.restorecon(tracesDir.getPath())) {
3225 return;
3226 }
3227 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003228 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3229
3230 if (tracesFile.exists()) {
3231 tracesTmp.delete();
3232 tracesFile.renameTo(tracesTmp);
3233 }
3234 StringBuilder sb = new StringBuilder();
3235 Time tobj = new Time();
3236 tobj.set(System.currentTimeMillis());
3237 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3238 sb.append(": ");
3239 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3240 sb.append(" since ");
3241 sb.append(msg);
3242 FileOutputStream fos = new FileOutputStream(tracesFile);
3243 fos.write(sb.toString().getBytes());
3244 if (app == null) {
3245 fos.write("\n*** No application process!".getBytes());
3246 }
3247 fos.close();
3248 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3249 } catch (IOException e) {
3250 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3251 return;
3252 }
3253
3254 if (app != null) {
3255 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3256 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003257 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003258 }
3259
3260 File lastTracesFile = null;
3261 File curTracesFile = null;
3262 for (int i=9; i>=0; i--) {
3263 String name = String.format("slow%02d.txt", i);
3264 curTracesFile = new File(tracesDir, name);
3265 if (curTracesFile.exists()) {
3266 if (lastTracesFile != null) {
3267 curTracesFile.renameTo(lastTracesFile);
3268 } else {
3269 curTracesFile.delete();
3270 }
3271 }
3272 lastTracesFile = curTracesFile;
3273 }
3274 tracesFile.renameTo(curTracesFile);
3275 if (tracesTmp.exists()) {
3276 tracesTmp.renameTo(tracesFile);
3277 }
3278 } finally {
3279 StrictMode.setThreadPolicy(oldPolicy);
3280 }
3281 }
3282
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003283 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3284 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003285 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3286 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3287
Dianne Hackborn287952c2010-09-22 22:34:31 -07003288 if (mController != null) {
3289 try {
3290 // 0 == continue, -1 = kill process immediately
3291 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3292 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3293 } catch (RemoteException e) {
3294 mController = null;
3295 }
3296 }
3297
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003298 long anrTime = SystemClock.uptimeMillis();
3299 if (MONITOR_CPU_USAGE) {
3300 updateCpuStatsNow();
3301 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003302
3303 synchronized (this) {
3304 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3305 if (mShuttingDown) {
3306 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3307 return;
3308 } else if (app.notResponding) {
3309 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3310 return;
3311 } else if (app.crashing) {
3312 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3313 return;
3314 }
3315
3316 // In case we come through here for the same app before completing
3317 // this one, mark as anring now so we will bail out.
3318 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003319
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003320 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003321 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3322 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003323
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003324 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003325 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003326
3327 int parentPid = app.pid;
3328 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003329 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003330
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003331 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003332
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003333 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3334 ProcessRecord r = mLruProcesses.get(i);
3335 if (r != null && r.thread != null) {
3336 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003337 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3338 if (r.persistent) {
3339 firstPids.add(pid);
3340 } else {
3341 lastPids.put(pid, Boolean.TRUE);
3342 }
3343 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
3346 }
3347
Dan Egnor42471dd2010-01-07 17:25:22 -08003348 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003349 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003350 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003351 info.append("ANR in ").append(app.processName);
3352 if (activity != null && activity.shortComponentName != null) {
3353 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003354 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003355 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003357 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003359 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003360 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362
Dianne Hackborn287952c2010-09-22 22:34:31 -07003363 final ProcessStats processStats = new ProcessStats(true);
3364
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003365 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003366
Dan Egnor42471dd2010-01-07 17:25:22 -08003367 String cpuInfo = null;
3368 if (MONITOR_CPU_USAGE) {
3369 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003370 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003371 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003372 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003373 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003374 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 }
3376
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003377 info.append(processStats.printCurrentState(anrTime));
3378
Joe Onorato8a9b2202010-02-26 18:56:32 -08003379 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003380 if (tracesFile == null) {
3381 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3382 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3383 }
3384
Jeff Sharkeya353d262011-10-28 11:12:06 -07003385 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3386 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003387
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003388 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003390 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3391 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003393 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3394 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 }
3396 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003397 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
3399 }
3400
Dan Egnor42471dd2010-01-07 17:25:22 -08003401 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3402 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3403 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003404
3405 synchronized (this) {
3406 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003407 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003408 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003409 app.processName, app.setAdj, "background ANR");
3410 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003411 return;
3412 }
3413
3414 // Set the app's notResponding state, and look up the errorReportReceiver
3415 makeAppNotRespondingLocked(app,
3416 activity != null ? activity.shortComponentName : null,
3417 annotation != null ? "ANR " + annotation : "ANR",
3418 info.toString());
3419
3420 // Bring up the infamous App Not Responding dialog
3421 Message msg = Message.obtain();
3422 HashMap map = new HashMap();
3423 msg.what = SHOW_NOT_RESPONDING_MSG;
3424 msg.obj = map;
3425 map.put("app", app);
3426 if (activity != null) {
3427 map.put("activity", activity);
3428 }
3429
3430 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 }
3433
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003434 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3435 if (!mLaunchWarningShown) {
3436 mLaunchWarningShown = true;
3437 mHandler.post(new Runnable() {
3438 @Override
3439 public void run() {
3440 synchronized (ActivityManagerService.this) {
3441 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3442 d.show();
3443 mHandler.postDelayed(new Runnable() {
3444 @Override
3445 public void run() {
3446 synchronized (ActivityManagerService.this) {
3447 d.dismiss();
3448 mLaunchWarningShown = false;
3449 }
3450 }
3451 }, 4000);
3452 }
3453 }
3454 });
3455 }
3456 }
3457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003459 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003460 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 int uid = Binder.getCallingUid();
3462 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003463 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003464 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 long callingId = Binder.clearCallingIdentity();
3466 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003467 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 int pkgUid = -1;
3469 synchronized(this) {
3470 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003471 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 } catch (RemoteException e) {
3473 }
3474 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003475 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 return false;
3477 }
3478 if (uid == pkgUid || checkComponentPermission(
3479 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003480 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003482 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 } else {
3484 throw new SecurityException(pid+" does not have permission:"+
3485 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3486 "for process:"+packageName);
3487 }
3488 }
3489
3490 try {
3491 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003492 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3494 Uri.fromParts("package", packageName, null));
3495 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003496 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003497 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 } catch (RemoteException e) {
3499 }
3500 } finally {
3501 Binder.restoreCallingIdentity(callingId);
3502 }
3503 return true;
3504 }
3505
Dianne Hackborn1676c852012-09-10 14:52:30 -07003506 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003507 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3508 != PackageManager.PERMISSION_GRANTED &&
3509 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3510 != PackageManager.PERMISSION_GRANTED) {
3511 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 + Binder.getCallingPid()
3513 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003514 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003515 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 throw new SecurityException(msg);
3517 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003518
Dianne Hackborn139748f2012-09-24 11:36:57 -07003519 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003520 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 long callingId = Binder.clearCallingIdentity();
3522 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003523 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003525 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003527 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 } catch (RemoteException e) {
3529 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003530 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003531 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 return;
3533 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003534 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003535 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3536 }
3537 } finally {
3538 Binder.restoreCallingIdentity(callingId);
3539 }
3540 }
3541
3542 public void killAllBackgroundProcesses() {
3543 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3544 != PackageManager.PERMISSION_GRANTED) {
3545 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3546 + Binder.getCallingPid()
3547 + ", uid=" + Binder.getCallingUid()
3548 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3549 Slog.w(TAG, msg);
3550 throw new SecurityException(msg);
3551 }
3552
3553 long callingId = Binder.clearCallingIdentity();
3554 try {
3555 synchronized(this) {
3556 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3557 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3558 final int NA = apps.size();
3559 for (int ia=0; ia<NA; ia++) {
3560 ProcessRecord app = apps.valueAt(ia);
3561 if (app.persistent) {
3562 // we don't kill persistent processes
3563 continue;
3564 }
3565 if (app.removed) {
3566 procs.add(app);
3567 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3568 app.removed = true;
3569 procs.add(app);
3570 }
3571 }
3572 }
3573
3574 int N = procs.size();
3575 for (int i=0; i<N; i++) {
3576 removeProcessLocked(procs.get(i), false, true, "kill all background");
3577 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003578 }
3579 } finally {
3580 Binder.restoreCallingIdentity(callingId);
3581 }
3582 }
3583
Dianne Hackborn1676c852012-09-10 14:52:30 -07003584 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3586 != PackageManager.PERMISSION_GRANTED) {
3587 String msg = "Permission Denial: forceStopPackage() from pid="
3588 + Binder.getCallingPid()
3589 + ", uid=" + Binder.getCallingUid()
3590 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003591 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003592 throw new SecurityException(msg);
3593 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003594 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003595 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003596 long callingId = Binder.clearCallingIdentity();
3597 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003598 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003600 int[] users = userId == UserHandle.USER_ALL
3601 ? getUsersLocked() : new int[] { userId };
3602 for (int user : users) {
3603 int pkgUid = -1;
3604 try {
3605 pkgUid = pm.getPackageUid(packageName, user);
3606 } catch (RemoteException e) {
3607 }
3608 if (pkgUid == -1) {
3609 Slog.w(TAG, "Invalid packageName: " + packageName);
3610 continue;
3611 }
3612 try {
3613 pm.setPackageStoppedState(packageName, true, user);
3614 } catch (RemoteException e) {
3615 } catch (IllegalArgumentException e) {
3616 Slog.w(TAG, "Failed trying to unstop package "
3617 + packageName + ": " + e);
3618 }
3619 if (isUserRunningLocked(user)) {
3620 forceStopPackageLocked(packageName, pkgUid);
3621 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 }
3624 } finally {
3625 Binder.restoreCallingIdentity(callingId);
3626 }
3627 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003628
3629 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003630 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003631 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003632 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003633 if (pkg == null) {
3634 return;
3635 }
3636 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003637 if (appid < 0) {
3638 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003639 return;
3640 }
3641 int callerUid = Binder.getCallingUid();
3642 // Only the system server can kill an application
3643 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003644 // Post an aysnc message to kill the application
3645 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003646 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003647 msg.arg2 = 0;
3648 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003649 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003650 } else {
3651 throw new SecurityException(callerUid + " cannot kill pkg: " +
3652 pkg);
3653 }
3654 }
3655
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003656 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003657 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003658
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003659 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003660 final int uid = Binder.getCallingUid();
3661 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003662 try {
3663 synchronized (this) {
3664 // Only allow this from foreground processes, so that background
3665 // applications can't abuse it to prevent system UI from being shown.
3666 if (uid >= Process.FIRST_APPLICATION_UID) {
3667 ProcessRecord proc;
3668 synchronized (mPidsSelfLocked) {
3669 proc = mPidsSelfLocked.get(pid);
3670 }
3671 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3672 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3673 + " from background process " + proc);
3674 return;
3675 }
3676 }
3677 closeSystemDialogsLocked(reason);
3678 }
3679 } finally {
3680 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003681 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003682 }
3683
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003684 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003685 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003686 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003687 if (reason != null) {
3688 intent.putExtra("reason", reason);
3689 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003690 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003691
Dianne Hackborne302a162012-05-15 14:58:32 -07003692 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3693 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003694 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003695 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003696 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003697 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003698 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003699
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003700 broadcastIntentLocked(null, null, intent, null,
3701 null, 0, null, null, null, false, false, -1,
3702 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003703 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003704
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003705 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003706 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003707 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003708 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3709 for (int i=pids.length-1; i>=0; i--) {
3710 infos[i] = new Debug.MemoryInfo();
3711 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003712 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003713 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003714 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003715
Dianne Hackbornb437e092011-08-05 17:50:29 -07003716 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003717 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003718 long[] pss = new long[pids.length];
3719 for (int i=pids.length-1; i>=0; i--) {
3720 pss[i] = Debug.getPss(pids[i]);
3721 }
3722 return pss;
3723 }
3724
Christopher Tate5e1ab332009-09-01 20:32:49 -07003725 public void killApplicationProcess(String processName, int uid) {
3726 if (processName == null) {
3727 return;
3728 }
3729
3730 int callerUid = Binder.getCallingUid();
3731 // Only the system server can kill an application
3732 if (callerUid == Process.SYSTEM_UID) {
3733 synchronized (this) {
3734 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003735 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003736 try {
3737 app.thread.scheduleSuicide();
3738 } catch (RemoteException e) {
3739 // If the other end already died, then our work here is done.
3740 }
3741 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003742 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003743 + processName + " / " + uid);
3744 }
3745 }
3746 } else {
3747 throw new SecurityException(callerUid + " cannot kill app process: " +
3748 processName);
3749 }
3750 }
3751
Dianne Hackborn03abb812010-01-04 18:43:19 -08003752 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003753 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3754 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3756 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003757 if (!mProcessesReady) {
3758 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003761 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 broadcastIntentLocked(null, null, intent,
3763 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003764 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003765 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003767
3768 private void forceStopUserLocked(int userId) {
3769 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3770 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3771 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3772 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3773 broadcastIntentLocked(null, null, intent,
3774 null, null, 0, null, null, null,
3775 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003776 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003777 }
3778
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003779 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003780 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3781 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003782 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783
Dianne Hackborn03abb812010-01-04 18:43:19 -08003784 // Remove all processes this package may have touched: all with the
3785 // same UID (except for the system or root user), and all whose name
3786 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003787 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003788 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3789 final int NA = apps.size();
3790 for (int ia=0; ia<NA; ia++) {
3791 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003792 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003793 // we don't kill persistent processes
3794 continue;
3795 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003796 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003797 if (doit) {
3798 procs.add(app);
3799 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003800 continue;
3801 }
3802
3803 // Skip process if it doesn't meet our oom adj requirement.
3804 if (app.setAdj < minOomAdj) {
3805 continue;
3806 }
3807
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003808 // If no package is specified, we call all processes under the
3809 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003810 if (packageName == null) {
3811 if (app.userId != userId) {
3812 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003813 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003814 // Package has been specified, we want to hit all processes
3815 // that match it. We need to qualify this by the processes
3816 // that are running under the specified app and user ID.
3817 } else {
3818 if (UserHandle.getAppId(app.uid) != appId) {
3819 continue;
3820 }
3821 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3822 continue;
3823 }
3824 if (!app.pkgList.contains(packageName)) {
3825 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003826 }
3827 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003828
3829 // Process has passed all conditions, kill it!
3830 if (!doit) {
3831 return true;
3832 }
3833 app.removed = true;
3834 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003835 }
3836 }
3837
3838 int N = procs.size();
3839 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003840 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003841 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003842 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003843 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003844
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003845 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003846 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003847 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003848 int i;
3849 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003851 if (userId == UserHandle.USER_ALL && name == null) {
3852 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3853 }
3854
3855 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003857 appId = UserHandle.getAppId(
3858 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 } catch (RemoteException e) {
3860 }
3861 }
3862
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003863 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003864 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003865 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3866 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003867 } else {
3868 Slog.i(TAG, "Force stopping user " + userId);
3869 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003870
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003871 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3872 while (badApps.hasNext()) {
3873 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003874 for (i=ba.size()-1; i>=0; i--) {
3875 boolean remove = false;
3876 final int entUid = ba.keyAt(i);
3877 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003878 if (userId == UserHandle.USER_ALL) {
3879 if (UserHandle.getAppId(entUid) == appId) {
3880 remove = true;
3881 }
3882 } else {
3883 if (entUid == UserHandle.getUid(userId, appId)) {
3884 remove = true;
3885 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003886 }
3887 } else if (UserHandle.getUserId(entUid) == userId) {
3888 remove = true;
3889 }
3890 if (remove) {
3891 ba.removeAt(i);
3892 }
3893 }
3894 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003895 badApps.remove();
3896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
3898 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003899
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003900 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3901 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003902 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003904 TaskRecord lastTask = null;
3905 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003906 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003907 final boolean samePackage = r.packageName.equals(name)
3908 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003909 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003910 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003911 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003912 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003913 if (r.finishing) {
3914 // If this activity is just finishing, then it is not
3915 // interesting as far as something to stop.
3916 continue;
3917 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003918 return true;
3919 }
3920 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003921 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003922 if (samePackage) {
3923 if (r.app != null) {
3924 r.app.removed = true;
3925 }
3926 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003928 lastTask = r.task;
3929 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003930 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003931 i--;
3932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
3934 }
3935
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003936 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3937 if (!doit) {
3938 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003940 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003942
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003943 if (name == null) {
3944 // Remove all sticky broadcasts from this user.
3945 mStickyBroadcasts.remove(userId);
3946 }
3947
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003948 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003949 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3950 userId, providers)) {
3951 if (!doit) {
3952 return true;
3953 }
3954 didSomething = true;
3955 }
3956 N = providers.size();
3957 for (i=0; i<N; i++) {
3958 removeDyingProviderLocked(null, providers.get(i), true);
3959 }
3960
3961 if (mIntentSenderRecords.size() > 0) {
3962 Iterator<WeakReference<PendingIntentRecord>> it
3963 = mIntentSenderRecords.values().iterator();
3964 while (it.hasNext()) {
3965 WeakReference<PendingIntentRecord> wpir = it.next();
3966 if (wpir == null) {
3967 it.remove();
3968 continue;
3969 }
3970 PendingIntentRecord pir = wpir.get();
3971 if (pir == null) {
3972 it.remove();
3973 continue;
3974 }
3975 if (name == null) {
3976 // Stopping user, remove all objects for the user.
3977 if (pir.key.userId != userId) {
3978 // Not the same user, skip it.
3979 continue;
3980 }
3981 } else {
3982 if (UserHandle.getAppId(pir.uid) != appId) {
3983 // Different app id, skip it.
3984 continue;
3985 }
3986 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3987 // Different user, skip it.
3988 continue;
3989 }
3990 if (!pir.key.packageName.equals(name)) {
3991 // Different package, skip it.
3992 continue;
3993 }
3994 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003995 if (!doit) {
3996 return true;
3997 }
3998 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003999 it.remove();
4000 pir.canceled = true;
4001 if (pir.key.activity != null) {
4002 pir.key.activity.pendingResults.remove(pir.ref);
4003 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004004 }
4005 }
4006
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004007 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004008 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004009 AttributeCache ac = AttributeCache.instance();
4010 if (ac != null) {
4011 ac.removePackage(name);
4012 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004013 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004014 if (mBooted) {
4015 mMainStack.resumeTopActivityLocked(null);
4016 mMainStack.scheduleIdleLocked();
4017 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004018 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004019
4020 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 }
4022
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004023 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004024 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004026 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004027 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004028 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 + "/" + uid + ")");
4030
4031 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004032 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004033 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004034 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4035 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004036 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 boolean needRestart = false;
4039 if (app.pid > 0 && app.pid != MY_PID) {
4040 int pid = app.pid;
4041 synchronized (mPidsSelfLocked) {
4042 mPidsSelfLocked.remove(pid);
4043 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4044 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004045 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004046 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004047 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004048 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004050 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004052 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 } else {
4054 needRestart = true;
4055 }
4056 }
4057 } else {
4058 mRemovedProcesses.add(app);
4059 }
4060
4061 return needRestart;
4062 }
4063
4064 private final void processStartTimedOutLocked(ProcessRecord app) {
4065 final int pid = app.pid;
4066 boolean gone = false;
4067 synchronized (mPidsSelfLocked) {
4068 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4069 if (knownApp != null && knownApp.thread == null) {
4070 mPidsSelfLocked.remove(pid);
4071 gone = true;
4072 }
4073 }
4074
4075 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004076 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004077 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4078 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004079 mProcessNames.remove(app.processName, app.uid);
4080 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004081 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004082 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4083 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004084 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004085 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004086 // Take care of any launching providers waiting for this process.
4087 checkAppInLaunchingProvidersLocked(app, true);
4088 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004089 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004090 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004091 app.processName, app.setAdj, "start timeout");
4092 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004093 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004094 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004095 try {
4096 IBackupManager bm = IBackupManager.Stub.asInterface(
4097 ServiceManager.getService(Context.BACKUP_SERVICE));
4098 bm.agentDisconnected(app.info.packageName);
4099 } catch (RemoteException e) {
4100 // Can't happen; the backup manager is local
4101 }
4102 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004103 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004104 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004105 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004108 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 }
4110 }
4111
4112 private final boolean attachApplicationLocked(IApplicationThread thread,
4113 int pid) {
4114
4115 // Find the application record that is being attached... either via
4116 // the pid if we are running in multiple processes, or just pull the
4117 // next app record if we are emulating process with anonymous threads.
4118 ProcessRecord app;
4119 if (pid != MY_PID && pid >= 0) {
4120 synchronized (mPidsSelfLocked) {
4121 app = mPidsSelfLocked.get(pid);
4122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 } else {
4124 app = null;
4125 }
4126
4127 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004128 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004130 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004132 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 } else {
4134 try {
4135 thread.scheduleExit();
4136 } catch (Exception e) {
4137 // Ignore exceptions.
4138 }
4139 }
4140 return false;
4141 }
4142
4143 // If this application record is still attached to a previous
4144 // process, clean it up now.
4145 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004146 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 }
4148
4149 // Tell the process all about itself.
4150
Joe Onorato8a9b2202010-02-26 18:56:32 -08004151 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 TAG, "Binding process pid " + pid + " to record " + app);
4153
4154 String processName = app.processName;
4155 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004156 AppDeathRecipient adr = new AppDeathRecipient(
4157 app, pid, thread);
4158 thread.asBinder().linkToDeath(adr, 0);
4159 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 } catch (RemoteException e) {
4161 app.resetPackageList();
4162 startProcessLocked(app, "link fail", processName);
4163 return false;
4164 }
4165
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004166 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167
4168 app.thread = thread;
4169 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004170 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4171 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 app.forcingToForeground = null;
4173 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004174 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 app.debugging = false;
4176
4177 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4178
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004179 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004180 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004182 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004183 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004184 }
4185
Joe Onorato8a9b2202010-02-26 18:56:32 -08004186 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 TAG, "New app record " + app
4188 + " thread=" + thread.asBinder() + " pid=" + pid);
4189 try {
4190 int testMode = IApplicationThread.DEBUG_OFF;
4191 if (mDebugApp != null && mDebugApp.equals(processName)) {
4192 testMode = mWaitForDebugger
4193 ? IApplicationThread.DEBUG_WAIT
4194 : IApplicationThread.DEBUG_ON;
4195 app.debugging = true;
4196 if (mDebugTransient) {
4197 mDebugApp = mOrigDebugApp;
4198 mWaitForDebugger = mOrigWaitForDebugger;
4199 }
4200 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004201 String profileFile = app.instrumentationProfileFile;
4202 ParcelFileDescriptor profileFd = null;
4203 boolean profileAutoStop = false;
4204 if (mProfileApp != null && mProfileApp.equals(processName)) {
4205 mProfileProc = app;
4206 profileFile = mProfileFile;
4207 profileFd = mProfileFd;
4208 profileAutoStop = mAutoStopProfiler;
4209 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004210 boolean enableOpenGlTrace = false;
4211 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4212 enableOpenGlTrace = true;
4213 mOpenGlTraceApp = null;
4214 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004215
Christopher Tate181fafa2009-05-14 11:12:14 -07004216 // If the app is being launched for restore or full backup, set it up specially
4217 boolean isRestrictedBackupMode = false;
4218 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4219 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004220 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004221 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4222 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004223
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004224 ensurePackageDexOpt(app.instrumentationInfo != null
4225 ? app.instrumentationInfo.packageName
4226 : app.info.packageName);
4227 if (app.instrumentationClass != null) {
4228 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004229 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004230 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004231 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004232 ApplicationInfo appInfo = app.instrumentationInfo != null
4233 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004234 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004235 if (profileFd != null) {
4236 profileFd = profileFd.dup();
4237 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004238 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004239 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004240 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4241 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004242 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004243 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004244 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004245 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 } catch (Exception e) {
4247 // todo: Yikes! What should we do? For now we will try to
4248 // start another process, but that could easily get us in
4249 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004250 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251
4252 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004253 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 startProcessLocked(app, "bind fail", processName);
4255 return false;
4256 }
4257
4258 // Remove this record from the list of starting applications.
4259 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004260 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4261 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 mProcessesOnHold.remove(app);
4263
4264 boolean badApp = false;
4265 boolean didSomething = false;
4266
4267 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004268 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004269 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004270 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 && processName.equals(hr.processName)) {
4272 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004273 if (mHeadless) {
4274 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4275 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 didSomething = true;
4277 }
4278 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004279 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 + hr.intent.getComponent().flattenToShortString(), e);
4281 badApp = true;
4282 }
4283 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004284 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 }
4286 }
4287
4288 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004289 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004291 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 badApp = true;
4294 }
4295 }
4296
Christopher Tatef46723b2012-01-26 14:19:24 -08004297 // Check if a next-broadcast receiver is in this process...
4298 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004300 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004302 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 }
4305 }
4306
Christopher Tate181fafa2009-05-14 11:12:14 -07004307 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004308 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004309 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004310 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004311 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004312 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4313 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4314 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004315 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004316 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004317 e.printStackTrace();
4318 }
4319 }
4320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 if (badApp) {
4322 // todo: Also need to kill application to deal with all
4323 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004324 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 return false;
4326 }
4327
4328 if (!didSomething) {
4329 updateOomAdjLocked();
4330 }
4331
4332 return true;
4333 }
4334
4335 public final void attachApplication(IApplicationThread thread) {
4336 synchronized (this) {
4337 int callingPid = Binder.getCallingPid();
4338 final long origId = Binder.clearCallingIdentity();
4339 attachApplicationLocked(thread, callingPid);
4340 Binder.restoreCallingIdentity(origId);
4341 }
4342 }
4343
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004344 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004346 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4347 if (stopProfiling) {
4348 synchronized (this) {
4349 if (mProfileProc == r.app) {
4350 if (mProfileFd != null) {
4351 try {
4352 mProfileFd.close();
4353 } catch (IOException e) {
4354 }
4355 clearProfilerLocked();
4356 }
4357 }
4358 }
4359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 Binder.restoreCallingIdentity(origId);
4361 }
4362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004364 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004365 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004367
4368 synchronized (this) {
4369 updateEventDispatchingLocked();
4370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 }
4372
Dianne Hackborn661cd522011-08-22 00:26:20 -07004373 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004374 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004375 mWindowManager.showBootMessage(msg, always);
4376 }
4377
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004378 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004379 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004380 final long token = Binder.clearCallingIdentity();
4381 try {
4382 synchronized (this) {
4383 if (mLockScreenShown) {
4384 mLockScreenShown = false;
4385 comeOutOfSleepIfNeededLocked();
4386 }
4387 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004388 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004389 } finally {
4390 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004391 }
4392 }
4393
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004394 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004395 IntentFilter pkgFilter = new IntentFilter();
4396 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4397 pkgFilter.addDataScheme("package");
4398 mContext.registerReceiver(new BroadcastReceiver() {
4399 @Override
4400 public void onReceive(Context context, Intent intent) {
4401 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4402 if (pkgs != null) {
4403 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004404 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004405 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4406 setResultCode(Activity.RESULT_OK);
4407 return;
4408 }
4409 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004410 }
4411 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004412 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004413 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004414
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004415 synchronized (this) {
4416 // Ensure that any processes we had put on hold are now started
4417 // up.
4418 final int NP = mProcessesOnHold.size();
4419 if (NP > 0) {
4420 ArrayList<ProcessRecord> procs =
4421 new ArrayList<ProcessRecord>(mProcessesOnHold);
4422 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004423 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4424 + procs.get(ip));
4425 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004426 }
4427 }
4428
4429 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004430 // Start looking for apps that are abusing wake locks.
4431 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004432 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004433 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004434 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004435 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004436 for (int i=0; i<mStartedUsers.size(); i++) {
4437 UserStartedState uss = mStartedUsers.valueAt(i);
4438 if (uss.mState == UserStartedState.STATE_BOOTING) {
4439 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004440 final int userId = mStartedUsers.keyAt(i);
4441 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4442 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4443 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004444 null, null, 0, null, null,
4445 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004446 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004447 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004448 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004449 }
4450 }
4451 }
4452
4453 final void ensureBootCompleted() {
4454 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004455 boolean enableScreen;
4456 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004457 booting = mBooting;
4458 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004459 enableScreen = !mBooted;
4460 mBooted = true;
4461 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004462
4463 if (booting) {
4464 finishBooting();
4465 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004466
4467 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004468 enableScreenAfterBoot();
4469 }
4470 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004471
4472 public final void activityResumed(IBinder token) {
4473 final long origId = Binder.clearCallingIdentity();
4474 mMainStack.activityResumed(token);
4475 Binder.restoreCallingIdentity(origId);
4476 }
4477
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004478 public final void activityPaused(IBinder token) {
4479 final long origId = Binder.clearCallingIdentity();
4480 mMainStack.activityPaused(token, false);
4481 Binder.restoreCallingIdentity(origId);
4482 }
4483
4484 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4485 CharSequence description) {
4486 if (localLOGV) Slog.v(
4487 TAG, "Activity stopped: token=" + token);
4488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 // Refuse possible leaked file descriptors
4490 if (icicle != null && icicle.hasFileDescriptors()) {
4491 throw new IllegalArgumentException("File descriptors passed in Bundle");
4492 }
4493
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004494 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495
4496 final long origId = Binder.clearCallingIdentity();
4497
4498 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004499 r = mMainStack.isInStackLocked(token);
4500 if (r != null) {
4501 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 }
4503 }
4504
4505 if (r != null) {
4506 sendPendingThumbnail(r, null, null, null, false);
4507 }
4508
4509 trimApplications();
4510
4511 Binder.restoreCallingIdentity(origId);
4512 }
4513
4514 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004515 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004516 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518
4519 public String getCallingPackage(IBinder token) {
4520 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004521 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004522 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 }
4524 }
4525
4526 public ComponentName getCallingActivity(IBinder token) {
4527 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004528 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 return r != null ? r.intent.getComponent() : null;
4530 }
4531 }
4532
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004533 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004534 ActivityRecord r = mMainStack.isInStackLocked(token);
4535 if (r == null) {
4536 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004538 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 }
4540
4541 public ComponentName getActivityClassForToken(IBinder token) {
4542 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004543 ActivityRecord r = mMainStack.isInStackLocked(token);
4544 if (r == null) {
4545 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004547 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 }
4549 }
4550
4551 public String getPackageForToken(IBinder token) {
4552 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004553 ActivityRecord r = mMainStack.isInStackLocked(token);
4554 if (r == null) {
4555 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004557 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004558 }
4559 }
4560
4561 public IIntentSender getIntentSender(int type,
4562 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004563 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004564 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004565 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004567 if (intents != null) {
4568 if (intents.length < 1) {
4569 throw new IllegalArgumentException("Intents array length must be >= 1");
4570 }
4571 for (int i=0; i<intents.length; i++) {
4572 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004573 if (intent != null) {
4574 if (intent.hasFileDescriptors()) {
4575 throw new IllegalArgumentException("File descriptors passed in Intent");
4576 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004577 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004578 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4579 throw new IllegalArgumentException(
4580 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4581 }
4582 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004583 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004584 }
4585 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004586 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004587 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004588 }
4589 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004590 if (options != null) {
4591 if (options.hasFileDescriptors()) {
4592 throw new IllegalArgumentException("File descriptors passed in options");
4593 }
4594 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 synchronized(this) {
4597 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004598 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004599 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004600 type == ActivityManager.INTENT_SENDER_BROADCAST, true,
4601 "getIntentSender", null);
4602 if (origUserId == UserHandle.USER_CURRENT) {
4603 // We don't want to evaluate this until the pending intent is
4604 // actually executed. However, we do want to always do the
4605 // security checking for it above.
4606 userId = UserHandle.USER_CURRENT;
4607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004609 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004610 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004611 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4612 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 String msg = "Permission Denial: getIntentSender() from pid="
4614 + Binder.getCallingPid()
4615 + ", uid=" + Binder.getCallingUid()
4616 + ", (need uid=" + uid + ")"
4617 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004618 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 throw new SecurityException(msg);
4620 }
4621 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004622
4623 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004624 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 } catch (RemoteException e) {
4627 throw new SecurityException(e);
4628 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004629 }
4630 }
4631
Dianne Hackborn41203752012-08-31 14:05:51 -07004632 IIntentSender getIntentSenderLocked(int type, String packageName,
4633 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004634 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4635 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004636 if (DEBUG_MU)
4637 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004638 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004639 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004640 activity = mMainStack.isInStackLocked(token);
4641 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004642 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004644 if (activity.finishing) {
4645 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004647 }
4648
4649 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4650 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4651 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4652 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4653 |PendingIntent.FLAG_UPDATE_CURRENT);
4654
4655 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4656 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004657 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004658 WeakReference<PendingIntentRecord> ref;
4659 ref = mIntentSenderRecords.get(key);
4660 PendingIntentRecord rec = ref != null ? ref.get() : null;
4661 if (rec != null) {
4662 if (!cancelCurrent) {
4663 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004664 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004665 rec.key.requestIntent.replaceExtras(intents != null ?
4666 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004667 }
4668 if (intents != null) {
4669 intents[intents.length-1] = rec.key.requestIntent;
4670 rec.key.allIntents = intents;
4671 rec.key.allResolvedTypes = resolvedTypes;
4672 } else {
4673 rec.key.allIntents = null;
4674 rec.key.allResolvedTypes = null;
4675 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 return rec;
4678 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004679 rec.canceled = true;
4680 mIntentSenderRecords.remove(key);
4681 }
4682 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 return rec;
4684 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004685 rec = new PendingIntentRecord(this, key, callingUid);
4686 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004687 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004688 if (activity.pendingResults == null) {
4689 activity.pendingResults
4690 = new HashSet<WeakReference<PendingIntentRecord>>();
4691 }
4692 activity.pendingResults.add(rec.ref);
4693 }
4694 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
4696
4697 public void cancelIntentSender(IIntentSender sender) {
4698 if (!(sender instanceof PendingIntentRecord)) {
4699 return;
4700 }
4701 synchronized(this) {
4702 PendingIntentRecord rec = (PendingIntentRecord)sender;
4703 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004704 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004705 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4706 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 String msg = "Permission Denial: cancelIntentSender() from pid="
4708 + Binder.getCallingPid()
4709 + ", uid=" + Binder.getCallingUid()
4710 + " is not allowed to cancel packges "
4711 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004712 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 throw new SecurityException(msg);
4714 }
4715 } catch (RemoteException e) {
4716 throw new SecurityException(e);
4717 }
4718 cancelIntentSenderLocked(rec, true);
4719 }
4720 }
4721
4722 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4723 rec.canceled = true;
4724 mIntentSenderRecords.remove(rec.key);
4725 if (cleanActivity && rec.key.activity != null) {
4726 rec.key.activity.pendingResults.remove(rec.ref);
4727 }
4728 }
4729
4730 public String getPackageForIntentSender(IIntentSender pendingResult) {
4731 if (!(pendingResult instanceof PendingIntentRecord)) {
4732 return null;
4733 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004734 try {
4735 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4736 return res.key.packageName;
4737 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004738 }
4739 return null;
4740 }
4741
Christopher Tatec4a07d12012-04-06 14:19:13 -07004742 public int getUidForIntentSender(IIntentSender sender) {
4743 if (sender instanceof PendingIntentRecord) {
4744 try {
4745 PendingIntentRecord res = (PendingIntentRecord)sender;
4746 return res.uid;
4747 } catch (ClassCastException e) {
4748 }
4749 }
4750 return -1;
4751 }
4752
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004753 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4754 if (!(pendingResult instanceof PendingIntentRecord)) {
4755 return false;
4756 }
4757 try {
4758 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4759 if (res.key.allIntents == null) {
4760 return false;
4761 }
4762 for (int i=0; i<res.key.allIntents.length; i++) {
4763 Intent intent = res.key.allIntents[i];
4764 if (intent.getPackage() != null && intent.getComponent() != null) {
4765 return false;
4766 }
4767 }
4768 return true;
4769 } catch (ClassCastException e) {
4770 }
4771 return false;
4772 }
4773
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004774 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4775 if (!(pendingResult instanceof PendingIntentRecord)) {
4776 return false;
4777 }
4778 try {
4779 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4780 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4781 return true;
4782 }
4783 return false;
4784 } catch (ClassCastException e) {
4785 }
4786 return false;
4787 }
4788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 public void setProcessLimit(int max) {
4790 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4791 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004792 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004793 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004794 mProcessLimitOverride = max;
4795 }
4796 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004797 }
4798
4799 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004800 synchronized (this) {
4801 return mProcessLimitOverride;
4802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 }
4804
4805 void foregroundTokenDied(ForegroundToken token) {
4806 synchronized (ActivityManagerService.this) {
4807 synchronized (mPidsSelfLocked) {
4808 ForegroundToken cur
4809 = mForegroundProcesses.get(token.pid);
4810 if (cur != token) {
4811 return;
4812 }
4813 mForegroundProcesses.remove(token.pid);
4814 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4815 if (pr == null) {
4816 return;
4817 }
4818 pr.forcingToForeground = null;
4819 pr.foregroundServices = false;
4820 }
4821 updateOomAdjLocked();
4822 }
4823 }
4824
4825 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4826 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4827 "setProcessForeground()");
4828 synchronized(this) {
4829 boolean changed = false;
4830
4831 synchronized (mPidsSelfLocked) {
4832 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004833 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004834 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 return;
4836 }
4837 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4838 if (oldToken != null) {
4839 oldToken.token.unlinkToDeath(oldToken, 0);
4840 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004841 if (pr != null) {
4842 pr.forcingToForeground = null;
4843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 changed = true;
4845 }
4846 if (isForeground && token != null) {
4847 ForegroundToken newToken = new ForegroundToken() {
4848 public void binderDied() {
4849 foregroundTokenDied(this);
4850 }
4851 };
4852 newToken.pid = pid;
4853 newToken.token = token;
4854 try {
4855 token.linkToDeath(newToken, 0);
4856 mForegroundProcesses.put(pid, newToken);
4857 pr.forcingToForeground = token;
4858 changed = true;
4859 } catch (RemoteException e) {
4860 // If the process died while doing this, we will later
4861 // do the cleanup with the process death link.
4862 }
4863 }
4864 }
4865
4866 if (changed) {
4867 updateOomAdjLocked();
4868 }
4869 }
4870 }
4871
4872 // =========================================================
4873 // PERMISSIONS
4874 // =========================================================
4875
4876 static class PermissionController extends IPermissionController.Stub {
4877 ActivityManagerService mActivityManagerService;
4878 PermissionController(ActivityManagerService activityManagerService) {
4879 mActivityManagerService = activityManagerService;
4880 }
4881
4882 public boolean checkPermission(String permission, int pid, int uid) {
4883 return mActivityManagerService.checkPermission(permission, pid,
4884 uid) == PackageManager.PERMISSION_GRANTED;
4885 }
4886 }
4887
4888 /**
4889 * This can be called with or without the global lock held.
4890 */
4891 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004892 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 // We might be performing an operation on behalf of an indirect binder
4894 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4895 // client identity accordingly before proceeding.
4896 Identity tlsIdentity = sCallerIdentity.get();
4897 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004898 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4900 uid = tlsIdentity.uid;
4901 pid = tlsIdentity.pid;
4902 }
4903
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004904 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 return PackageManager.PERMISSION_GRANTED;
4906 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004907
4908 return ActivityManager.checkComponentPermission(permission, uid,
4909 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 }
4911
4912 /**
4913 * As the only public entry point for permissions checking, this method
4914 * can enforce the semantic that requesting a check on a null global
4915 * permission is automatically denied. (Internally a null permission
4916 * string is used when calling {@link #checkComponentPermission} in cases
4917 * when only uid-based security is needed.)
4918 *
4919 * This can be called with or without the global lock held.
4920 */
4921 public int checkPermission(String permission, int pid, int uid) {
4922 if (permission == null) {
4923 return PackageManager.PERMISSION_DENIED;
4924 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004925 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 }
4927
4928 /**
4929 * Binder IPC calls go through the public entry point.
4930 * This can be called with or without the global lock held.
4931 */
4932 int checkCallingPermission(String permission) {
4933 return checkPermission(permission,
4934 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004935 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004936 }
4937
4938 /**
4939 * This can be called with or without the global lock held.
4940 */
4941 void enforceCallingPermission(String permission, String func) {
4942 if (checkCallingPermission(permission)
4943 == PackageManager.PERMISSION_GRANTED) {
4944 return;
4945 }
4946
4947 String msg = "Permission Denial: " + func + " from pid="
4948 + Binder.getCallingPid()
4949 + ", uid=" + Binder.getCallingUid()
4950 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004951 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 throw new SecurityException(msg);
4953 }
4954
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004955 /**
4956 * Determine if UID is holding permissions required to access {@link Uri} in
4957 * the given {@link ProviderInfo}. Final permission checking is always done
4958 * in {@link ContentProvider}.
4959 */
4960 private final boolean checkHoldingPermissionsLocked(
4961 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004962 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4963 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004964
4965 if (pi.applicationInfo.uid == uid) {
4966 return true;
4967 } else if (!pi.exported) {
4968 return false;
4969 }
4970
4971 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4972 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004974 // check if target holds top-level <provider> permissions
4975 if (!readMet && pi.readPermission != null
4976 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4977 readMet = true;
4978 }
4979 if (!writeMet && pi.writePermission != null
4980 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4981 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004982 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004983
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004984 // track if unprotected read/write is allowed; any denied
4985 // <path-permission> below removes this ability
4986 boolean allowDefaultRead = pi.readPermission == null;
4987 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004988
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004989 // check if target holds any <path-permission> that match uri
4990 final PathPermission[] pps = pi.pathPermissions;
4991 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004992 final String path = uri.getPath();
4993 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004994 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004995 i--;
4996 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004997 if (pp.match(path)) {
4998 if (!readMet) {
4999 final String pprperm = pp.getReadPermission();
5000 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5001 + pprperm + " for " + pp.getPath()
5002 + ": match=" + pp.match(path)
5003 + " check=" + pm.checkUidPermission(pprperm, uid));
5004 if (pprperm != null) {
5005 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5006 readMet = true;
5007 } else {
5008 allowDefaultRead = false;
5009 }
5010 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005011 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005012 if (!writeMet) {
5013 final String ppwperm = pp.getWritePermission();
5014 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5015 + ppwperm + " for " + pp.getPath()
5016 + ": match=" + pp.match(path)
5017 + " check=" + pm.checkUidPermission(ppwperm, uid));
5018 if (ppwperm != null) {
5019 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5020 writeMet = true;
5021 } else {
5022 allowDefaultWrite = false;
5023 }
5024 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005025 }
5026 }
5027 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005028 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005029
5030 // grant unprotected <provider> read/write, if not blocked by
5031 // <path-permission> above
5032 if (allowDefaultRead) readMet = true;
5033 if (allowDefaultWrite) writeMet = true;
5034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005035 } catch (RemoteException e) {
5036 return false;
5037 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005038
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005039 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005040 }
5041
5042 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5043 int modeFlags) {
5044 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005045 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 return true;
5047 }
5048 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5049 if (perms == null) return false;
5050 UriPermission perm = perms.get(uri);
5051 if (perm == null) return false;
5052 return (modeFlags&perm.modeFlags) == modeFlags;
5053 }
5054
5055 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005056 enforceNotIsolatedCaller("checkUriPermission");
5057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 // Another redirected-binder-call permissions check as in
5059 // {@link checkComponentPermission}.
5060 Identity tlsIdentity = sCallerIdentity.get();
5061 if (tlsIdentity != null) {
5062 uid = tlsIdentity.uid;
5063 pid = tlsIdentity.pid;
5064 }
5065
5066 // Our own process gets to do everything.
5067 if (pid == MY_PID) {
5068 return PackageManager.PERMISSION_GRANTED;
5069 }
5070 synchronized(this) {
5071 return checkUriPermissionLocked(uri, uid, modeFlags)
5072 ? PackageManager.PERMISSION_GRANTED
5073 : PackageManager.PERMISSION_DENIED;
5074 }
5075 }
5076
Dianne Hackborn39792d22010-08-19 18:01:52 -07005077 /**
5078 * Check if the targetPkg can be granted permission to access uri by
5079 * the callingUid using the given modeFlags. Throws a security exception
5080 * if callingUid is not allowed to do this. Returns the uid of the target
5081 * if the URI permission grant should be performed; returns -1 if it is not
5082 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005083 * If you already know the uid of the target, you can supply it in
5084 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005085 */
5086 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005087 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5089 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5090 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005091 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 }
5093
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005094 if (targetPkg != null) {
5095 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5096 "Checking grant " + targetPkg + " permission to " + uri);
5097 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005098
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005099 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100
5101 // If this is not a content: uri, we can't do anything with it.
5102 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005103 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005104 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005105 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 }
5107
5108 String name = uri.getAuthority();
5109 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005110 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005111 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 if (cpr != null) {
5113 pi = cpr.info;
5114 } else {
5115 try {
5116 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005117 PackageManager.GET_URI_PERMISSION_PATTERNS,
5118 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 } catch (RemoteException ex) {
5120 }
5121 }
5122 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005123 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005124 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 }
5126
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005127 int targetUid = lastTargetUid;
5128 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005129 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005130 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005131 if (targetUid < 0) {
5132 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5133 "Can't grant URI permission no uid for: " + targetPkg);
5134 return -1;
5135 }
5136 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005137 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 }
5140
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005141 if (targetUid >= 0) {
5142 // First... does the target actually need this permission?
5143 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5144 // No need to grant the target this permission.
5145 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5146 "Target " + targetPkg + " already has full permission to " + uri);
5147 return -1;
5148 }
5149 } else {
5150 // First... there is no target package, so can anyone access it?
5151 boolean allowed = pi.exported;
5152 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5153 if (pi.readPermission != null) {
5154 allowed = false;
5155 }
5156 }
5157 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5158 if (pi.writePermission != null) {
5159 allowed = false;
5160 }
5161 }
5162 if (allowed) {
5163 return -1;
5164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 }
5166
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005167 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 if (!pi.grantUriPermissions) {
5169 throw new SecurityException("Provider " + pi.packageName
5170 + "/" + pi.name
5171 + " does not allow granting of Uri permissions (uri "
5172 + uri + ")");
5173 }
5174 if (pi.uriPermissionPatterns != null) {
5175 final int N = pi.uriPermissionPatterns.length;
5176 boolean allowed = false;
5177 for (int i=0; i<N; i++) {
5178 if (pi.uriPermissionPatterns[i] != null
5179 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5180 allowed = true;
5181 break;
5182 }
5183 }
5184 if (!allowed) {
5185 throw new SecurityException("Provider " + pi.packageName
5186 + "/" + pi.name
5187 + " does not allow granting of permission to path of Uri "
5188 + uri);
5189 }
5190 }
5191
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005192 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005194 if (callingUid != Process.myUid()) {
5195 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5196 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5197 throw new SecurityException("Uid " + callingUid
5198 + " does not have permission to uri " + uri);
5199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 }
5201 }
5202
Dianne Hackborn39792d22010-08-19 18:01:52 -07005203 return targetUid;
5204 }
5205
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005206 public int checkGrantUriPermission(int callingUid, String targetPkg,
5207 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005208 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005209 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005210 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005211 }
5212 }
5213
Dianne Hackborn39792d22010-08-19 18:01:52 -07005214 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5215 Uri uri, int modeFlags, UriPermissionOwner owner) {
5216 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5217 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5218 if (modeFlags == 0) {
5219 return;
5220 }
5221
5222 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 // to the uri, and the target doesn't. Let's now give this to
5224 // the target.
5225
Joe Onorato8a9b2202010-02-26 18:56:32 -08005226 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005227 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 HashMap<Uri, UriPermission> targetUris
5230 = mGrantedUriPermissions.get(targetUid);
5231 if (targetUris == null) {
5232 targetUris = new HashMap<Uri, UriPermission>();
5233 mGrantedUriPermissions.put(targetUid, targetUris);
5234 }
5235
5236 UriPermission perm = targetUris.get(uri);
5237 if (perm == null) {
5238 perm = new UriPermission(targetUid, uri);
5239 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005243 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005245 } else {
5246 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5247 perm.readOwners.add(owner);
5248 owner.addReadPermission(perm);
5249 }
5250 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5251 perm.writeOwners.add(owner);
5252 owner.addWritePermission(perm);
5253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 }
5255 }
5256
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005257 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5258 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005259 if (targetPkg == null) {
5260 throw new NullPointerException("targetPkg");
5261 }
5262
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005263 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005264 if (targetUid < 0) {
5265 return;
5266 }
5267
5268 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5269 }
5270
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005271 static class NeededUriGrants extends ArrayList<Uri> {
5272 final String targetPkg;
5273 final int targetUid;
5274 final int flags;
5275
5276 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5277 targetPkg = _targetPkg;
5278 targetUid = _targetUid;
5279 flags = _flags;
5280 }
5281 }
5282
Dianne Hackborn39792d22010-08-19 18:01:52 -07005283 /**
5284 * Like checkGrantUriPermissionLocked, but takes an Intent.
5285 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005286 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5287 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005288 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005289 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5290 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005291 + " from " + intent + "; flags=0x"
5292 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5293
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005294 if (targetPkg == null) {
5295 throw new NullPointerException("targetPkg");
5296 }
5297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005298 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005299 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005300 }
5301 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005302 ClipData clip = intent.getClipData();
5303 if (data == null && clip == null) {
5304 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005305 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005306 if (data != null) {
5307 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5308 mode, needed != null ? needed.targetUid : -1);
5309 if (target > 0) {
5310 if (needed == null) {
5311 needed = new NeededUriGrants(targetPkg, target, mode);
5312 }
5313 needed.add(data);
5314 }
5315 }
5316 if (clip != null) {
5317 for (int i=0; i<clip.getItemCount(); i++) {
5318 Uri uri = clip.getItemAt(i).getUri();
5319 if (uri != null) {
5320 int target = -1;
5321 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5322 mode, needed != null ? needed.targetUid : -1);
5323 if (target > 0) {
5324 if (needed == null) {
5325 needed = new NeededUriGrants(targetPkg, target, mode);
5326 }
5327 needed.add(uri);
5328 }
5329 } else {
5330 Intent clipIntent = clip.getItemAt(i).getIntent();
5331 if (clipIntent != null) {
5332 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5333 callingUid, targetPkg, clipIntent, mode, needed);
5334 if (newNeeded != null) {
5335 needed = newNeeded;
5336 }
5337 }
5338 }
5339 }
5340 }
5341
5342 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005343 }
5344
5345 /**
5346 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5347 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005348 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5349 UriPermissionOwner owner) {
5350 if (needed != null) {
5351 for (int i=0; i<needed.size(); i++) {
5352 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5353 needed.get(i), needed.flags, owner);
5354 }
5355 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005356 }
5357
5358 void grantUriPermissionFromIntentLocked(int callingUid,
5359 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005360 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005361 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005362 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 return;
5364 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005365
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005366 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 }
5368
5369 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5370 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005371 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 synchronized(this) {
5373 final ProcessRecord r = getRecordForAppLocked(caller);
5374 if (r == null) {
5375 throw new SecurityException("Unable to find app for caller "
5376 + caller
5377 + " when granting permission to uri " + uri);
5378 }
5379 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005380 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 }
5382 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005383 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 }
5385
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005386 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 null);
5388 }
5389 }
5390
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005391 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5393 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5394 HashMap<Uri, UriPermission> perms
5395 = mGrantedUriPermissions.get(perm.uid);
5396 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005397 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005398 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 perms.remove(perm.uri);
5400 if (perms.size() == 0) {
5401 mGrantedUriPermissions.remove(perm.uid);
5402 }
5403 }
5404 }
5405 }
5406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005407 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5408 int modeFlags) {
5409 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5410 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5411 if (modeFlags == 0) {
5412 return;
5413 }
5414
Joe Onorato8a9b2202010-02-26 18:56:32 -08005415 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005416 "Revoking all granted permissions to " + uri);
5417
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005418 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419
5420 final String authority = uri.getAuthority();
5421 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005422 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005423 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 if (cpr != null) {
5425 pi = cpr.info;
5426 } else {
5427 try {
5428 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005429 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 } catch (RemoteException ex) {
5431 }
5432 }
5433 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005434 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 return;
5436 }
5437
5438 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005439 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 // Right now, if you are not the original owner of the permission,
5441 // you are not allowed to revoke it.
5442 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5443 throw new SecurityException("Uid " + callingUid
5444 + " does not have permission to uri " + uri);
5445 //}
5446 }
5447
5448 // Go through all of the permissions and remove any that match.
5449 final List<String> SEGMENTS = uri.getPathSegments();
5450 if (SEGMENTS != null) {
5451 final int NS = SEGMENTS.size();
5452 int N = mGrantedUriPermissions.size();
5453 for (int i=0; i<N; i++) {
5454 HashMap<Uri, UriPermission> perms
5455 = mGrantedUriPermissions.valueAt(i);
5456 Iterator<UriPermission> it = perms.values().iterator();
5457 toploop:
5458 while (it.hasNext()) {
5459 UriPermission perm = it.next();
5460 Uri targetUri = perm.uri;
5461 if (!authority.equals(targetUri.getAuthority())) {
5462 continue;
5463 }
5464 List<String> targetSegments = targetUri.getPathSegments();
5465 if (targetSegments == null) {
5466 continue;
5467 }
5468 if (targetSegments.size() < NS) {
5469 continue;
5470 }
5471 for (int j=0; j<NS; j++) {
5472 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5473 continue toploop;
5474 }
5475 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005476 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005477 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 perm.clearModes(modeFlags);
5479 if (perm.modeFlags == 0) {
5480 it.remove();
5481 }
5482 }
5483 if (perms.size() == 0) {
5484 mGrantedUriPermissions.remove(
5485 mGrantedUriPermissions.keyAt(i));
5486 N--;
5487 i--;
5488 }
5489 }
5490 }
5491 }
5492
5493 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5494 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005495 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 synchronized(this) {
5497 final ProcessRecord r = getRecordForAppLocked(caller);
5498 if (r == null) {
5499 throw new SecurityException("Unable to find app for caller "
5500 + caller
5501 + " when revoking permission to uri " + uri);
5502 }
5503 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005504 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 return;
5506 }
5507
5508 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5509 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5510 if (modeFlags == 0) {
5511 return;
5512 }
5513
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005514 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515
5516 final String authority = uri.getAuthority();
5517 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005518 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 if (cpr != null) {
5520 pi = cpr.info;
5521 } else {
5522 try {
5523 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005524 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 } catch (RemoteException ex) {
5526 }
5527 }
5528 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005529 Slog.w(TAG, "No content provider found for permission revoke: "
5530 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 return;
5532 }
5533
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005534 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 }
5536 }
5537
Dianne Hackborn7e269642010-08-25 19:50:20 -07005538 @Override
5539 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005540 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005541 synchronized(this) {
5542 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5543 return owner.getExternalTokenLocked();
5544 }
5545 }
5546
5547 @Override
5548 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5549 Uri uri, int modeFlags) {
5550 synchronized(this) {
5551 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5552 if (owner == null) {
5553 throw new IllegalArgumentException("Unknown owner: " + token);
5554 }
5555 if (fromUid != Binder.getCallingUid()) {
5556 if (Binder.getCallingUid() != Process.myUid()) {
5557 // Only system code can grant URI permissions on behalf
5558 // of other users.
5559 throw new SecurityException("nice try");
5560 }
5561 }
5562 if (targetPkg == null) {
5563 throw new IllegalArgumentException("null target");
5564 }
5565 if (uri == null) {
5566 throw new IllegalArgumentException("null uri");
5567 }
5568
5569 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5570 }
5571 }
5572
5573 @Override
5574 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5575 synchronized(this) {
5576 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5577 if (owner == null) {
5578 throw new IllegalArgumentException("Unknown owner: " + token);
5579 }
5580
5581 if (uri == null) {
5582 owner.removeUriPermissionsLocked(mode);
5583 } else {
5584 owner.removeUriPermissionLocked(uri, mode);
5585 }
5586 }
5587 }
5588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5590 synchronized (this) {
5591 ProcessRecord app =
5592 who != null ? getRecordForAppLocked(who) : null;
5593 if (app == null) return;
5594
5595 Message msg = Message.obtain();
5596 msg.what = WAIT_FOR_DEBUGGER_MSG;
5597 msg.obj = app;
5598 msg.arg1 = waiting ? 1 : 0;
5599 mHandler.sendMessage(msg);
5600 }
5601 }
5602
5603 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005604 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5605 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005607 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005608 outInfo.threshold = homeAppMem;
5609 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5610 outInfo.hiddenAppThreshold = hiddenAppMem;
5611 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005612 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005613 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5614 ProcessList.VISIBLE_APP_ADJ);
5615 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5616 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 }
5618
5619 // =========================================================
5620 // TASK MANAGEMENT
5621 // =========================================================
5622
5623 public List getTasks(int maxNum, int flags,
5624 IThumbnailReceiver receiver) {
5625 ArrayList list = new ArrayList();
5626
5627 PendingThumbnailsRecord pending = null;
5628 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005629 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630
5631 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005632 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5634 + ", receiver=" + receiver);
5635
5636 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5637 != PackageManager.PERMISSION_GRANTED) {
5638 if (receiver != null) {
5639 // If the caller wants to wait for pending thumbnails,
5640 // it ain't gonna get them.
5641 try {
5642 receiver.finished();
5643 } catch (RemoteException ex) {
5644 }
5645 }
5646 String msg = "Permission Denial: getTasks() from pid="
5647 + Binder.getCallingPid()
5648 + ", uid=" + Binder.getCallingUid()
5649 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005650 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 throw new SecurityException(msg);
5652 }
5653
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005654 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005655 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005656 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005657 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 TaskRecord curTask = null;
5659 int numActivities = 0;
5660 int numRunning = 0;
5661 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005662 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005664 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665
5666 // Initialize state for next task if needed.
5667 if (top == null ||
5668 (top.state == ActivityState.INITIALIZING
5669 && top.task == r.task)) {
5670 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 curTask = r.task;
5672 numActivities = numRunning = 0;
5673 }
5674
5675 // Add 'r' into the current task.
5676 numActivities++;
5677 if (r.app != null && r.app.thread != null) {
5678 numRunning++;
5679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680
Joe Onorato8a9b2202010-02-26 18:56:32 -08005681 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 TAG, r.intent.getComponent().flattenToShortString()
5683 + ": task=" + r.task);
5684
5685 // If the next one is a different task, generate a new
5686 // TaskInfo entry for what we have.
5687 if (next == null || next.task != curTask) {
5688 ActivityManager.RunningTaskInfo ci
5689 = new ActivityManager.RunningTaskInfo();
5690 ci.id = curTask.taskId;
5691 ci.baseActivity = r.intent.getComponent();
5692 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005693 if (top.thumbHolder != null) {
5694 ci.description = top.thumbHolder.lastDescription;
5695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 ci.numActivities = numActivities;
5697 ci.numRunning = numRunning;
5698 //System.out.println(
5699 // "#" + maxNum + ": " + " descr=" + ci.description);
5700 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005701 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 TAG, "State=" + top.state + "Idle=" + top.idle
5703 + " app=" + top.app
5704 + " thr=" + (top.app != null ? top.app.thread : null));
5705 if (top.state == ActivityState.RESUMED
5706 || top.state == ActivityState.PAUSING) {
5707 if (top.idle && top.app != null
5708 && top.app.thread != null) {
5709 topRecord = top;
5710 topThumbnail = top.app.thread;
5711 } else {
5712 top.thumbnailNeeded = true;
5713 }
5714 }
5715 if (pending == null) {
5716 pending = new PendingThumbnailsRecord(receiver);
5717 }
5718 pending.pendingRecords.add(top);
5719 }
5720 list.add(ci);
5721 maxNum--;
5722 top = null;
5723 }
5724 }
5725
5726 if (pending != null) {
5727 mPendingThumbnails.add(pending);
5728 }
5729 }
5730
Joe Onorato8a9b2202010-02-26 18:56:32 -08005731 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732
5733 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005734 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005736 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005738 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005739 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
5741 }
5742
5743 if (pending == null && receiver != null) {
5744 // In this case all thumbnails were available and the client
5745 // is being asked to be told when the remaining ones come in...
5746 // which is unusually, since the top-most currently running
5747 // activity should never have a canned thumbnail! Oh well.
5748 try {
5749 receiver.finished();
5750 } catch (RemoteException ex) {
5751 }
5752 }
5753
5754 return list;
5755 }
5756
5757 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005758 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005759 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5760 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 synchronized (this) {
5763 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5764 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005765 final boolean detailed = checkCallingPermission(
5766 android.Manifest.permission.GET_DETAILED_TASKS)
5767 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005769 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 final int N = mRecentTasks.size();
5772 ArrayList<ActivityManager.RecentTaskInfo> res
5773 = new ArrayList<ActivityManager.RecentTaskInfo>(
5774 maxNum < N ? maxNum : N);
5775 for (int i=0; i<N && maxNum > 0; i++) {
5776 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005777 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005778 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005779 // Return the entry if desired by the caller. We always return
5780 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005781 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005782 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5783 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005784
Dianne Hackborn905577f2011-09-07 18:31:28 -07005785 if (i == 0
5786 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 || (tr.intent == null)
5788 || ((tr.intent.getFlags()
5789 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5790 ActivityManager.RecentTaskInfo rti
5791 = new ActivityManager.RecentTaskInfo();
5792 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005793 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 rti.baseIntent = new Intent(
5795 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005796 if (!detailed) {
5797 rti.baseIntent.replaceExtras((Bundle)null);
5798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005800 rti.description = tr.lastDescription;
5801
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005802 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5803 // Check whether this activity is currently available.
5804 try {
5805 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005806 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005807 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005808 continue;
5809 }
5810 } else if (rti.baseIntent != null) {
5811 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005812 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005813 continue;
5814 }
5815 }
5816 } catch (RemoteException e) {
5817 // Will never happen.
5818 }
5819 }
5820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 res.add(rti);
5822 maxNum--;
5823 }
5824 }
5825 return res;
5826 }
5827 }
5828
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005829 private TaskRecord taskForIdLocked(int id) {
5830 final int N = mRecentTasks.size();
5831 for (int i=0; i<N; i++) {
5832 TaskRecord tr = mRecentTasks.get(i);
5833 if (tr.taskId == id) {
5834 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005835 }
5836 }
5837 return null;
5838 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005839
5840 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5841 synchronized (this) {
5842 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5843 "getTaskThumbnails()");
5844 TaskRecord tr = taskForIdLocked(id);
5845 if (tr != null) {
5846 return mMainStack.getTaskThumbnailsLocked(tr);
5847 }
5848 }
5849 return null;
5850 }
5851
Dianne Hackborn15491c62012-09-19 10:59:14 -07005852 public Bitmap getTaskTopThumbnail(int id) {
5853 synchronized (this) {
5854 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5855 "getTaskTopThumbnail()");
5856 TaskRecord tr = taskForIdLocked(id);
5857 if (tr != null) {
5858 return mMainStack.getTaskTopThumbnailLocked(tr);
5859 }
5860 }
5861 return null;
5862 }
5863
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005864 public boolean removeSubTask(int taskId, int subTaskIndex) {
5865 synchronized (this) {
5866 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5867 "removeSubTask()");
5868 long ident = Binder.clearCallingIdentity();
5869 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005870 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5871 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005872 } finally {
5873 Binder.restoreCallingIdentity(ident);
5874 }
5875 }
5876 }
5877
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005878 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5879 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005880 Intent baseIntent = new Intent(
5881 tr.intent != null ? tr.intent : tr.affinityIntent);
5882 ComponentName component = baseIntent.getComponent();
5883 if (component == null) {
5884 Slog.w(TAG, "Now component for base intent of task: " + tr);
5885 return;
5886 }
5887
5888 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005889 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005890
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005891 if (killProcesses) {
5892 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005893 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005894 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005895 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5896 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5897 for (int i=0; i<uids.size(); i++) {
5898 ProcessRecord proc = uids.valueAt(i);
5899 if (proc.userId != tr.userId) {
5900 continue;
5901 }
5902 if (!proc.pkgList.contains(pkg)) {
5903 continue;
5904 }
5905 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005906 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005907 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005908
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005909 // Kill the running processes.
5910 for (int i=0; i<procs.size(); i++) {
5911 ProcessRecord pr = procs.get(i);
5912 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5913 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005914 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005915 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005916 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005917 Process.killProcessQuiet(pr.pid);
5918 } else {
5919 pr.waitingToKill = "remove task";
5920 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005921 }
5922 }
5923 }
5924
5925 public boolean removeTask(int taskId, int flags) {
5926 synchronized (this) {
5927 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5928 "removeTask()");
5929 long ident = Binder.clearCallingIdentity();
5930 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005931 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5932 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005933 if (r != null) {
5934 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005935 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005936 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005937 } else {
5938 TaskRecord tr = null;
5939 int i=0;
5940 while (i < mRecentTasks.size()) {
5941 TaskRecord t = mRecentTasks.get(i);
5942 if (t.taskId == taskId) {
5943 tr = t;
5944 break;
5945 }
5946 i++;
5947 }
5948 if (tr != null) {
5949 if (tr.numActivities <= 0) {
5950 // Caller is just removing a recent task that is
5951 // not actively running. That is easy!
5952 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005953 cleanUpRemovedTaskLocked(tr, flags);
5954 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005955 } else {
5956 Slog.w(TAG, "removeTask: task " + taskId
5957 + " does not have activities to remove, "
5958 + " but numActivities=" + tr.numActivities
5959 + ": " + tr);
5960 }
5961 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005962 }
5963 } finally {
5964 Binder.restoreCallingIdentity(ident);
5965 }
5966 }
5967 return false;
5968 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5971 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005972 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 TaskRecord jt = startTask;
5974
5975 // First look backwards
5976 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005977 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 if (r.task != jt) {
5979 jt = r.task;
5980 if (affinity.equals(jt.affinity)) {
5981 return j;
5982 }
5983 }
5984 }
5985
5986 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005987 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 jt = startTask;
5989 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005990 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 if (r.task != jt) {
5992 if (affinity.equals(jt.affinity)) {
5993 return j;
5994 }
5995 jt = r.task;
5996 }
5997 }
5998
5999 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006000 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 return N-1;
6002 }
6003
6004 return -1;
6005 }
6006
6007 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006008 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006010 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6012 "moveTaskToFront()");
6013
6014 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006015 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6016 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006017 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006018 return;
6019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 final long origId = Binder.clearCallingIdentity();
6021 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006022 TaskRecord tr = taskForIdLocked(task);
6023 if (tr != null) {
6024 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6025 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006027 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6028 // Caller wants the home activity moved with it. To accomplish this,
6029 // we'll just move the home task to the top first.
6030 mMainStack.moveHomeToFrontLocked();
6031 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006032 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006033 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006035 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6036 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006038 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6039 mMainStack.mUserLeaving = true;
6040 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006041 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6042 // Caller wants the home activity moved with it. To accomplish this,
6043 // we'll just move the home task to the top first.
6044 mMainStack.moveHomeToFrontLocked();
6045 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006046 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 return;
6048 }
6049 }
6050 } finally {
6051 Binder.restoreCallingIdentity(origId);
6052 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006053 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 }
6055 }
6056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 public void moveTaskToBack(int task) {
6058 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6059 "moveTaskToBack()");
6060
6061 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006062 if (mMainStack.mResumedActivity != null
6063 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006064 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6065 Binder.getCallingUid(), "Task to back")) {
6066 return;
6067 }
6068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006070 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 Binder.restoreCallingIdentity(origId);
6072 }
6073 }
6074
6075 /**
6076 * Moves an activity, and all of the other activities within the same task, to the bottom
6077 * of the history stack. The activity's order within the task is unchanged.
6078 *
6079 * @param token A reference to the activity we wish to move
6080 * @param nonRoot If false then this only works if the activity is the root
6081 * of a task; if true it will work for any activity in a task.
6082 * @return Returns true if the move completed, false if not.
6083 */
6084 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006085 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 synchronized(this) {
6087 final long origId = Binder.clearCallingIdentity();
6088 int taskId = getTaskForActivityLocked(token, !nonRoot);
6089 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006090 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 }
6092 Binder.restoreCallingIdentity(origId);
6093 }
6094 return false;
6095 }
6096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 public void moveTaskBackwards(int task) {
6098 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6099 "moveTaskBackwards()");
6100
6101 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006102 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6103 Binder.getCallingUid(), "Task backwards")) {
6104 return;
6105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 final long origId = Binder.clearCallingIdentity();
6107 moveTaskBackwardsLocked(task);
6108 Binder.restoreCallingIdentity(origId);
6109 }
6110 }
6111
6112 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006113 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 }
6115
6116 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6117 synchronized(this) {
6118 return getTaskForActivityLocked(token, onlyRoot);
6119 }
6120 }
6121
6122 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006123 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 TaskRecord lastTask = null;
6125 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006126 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006127 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 if (!onlyRoot || lastTask != r.task) {
6129 return r.task.taskId;
6130 }
6131 return -1;
6132 }
6133 lastTask = r.task;
6134 }
6135
6136 return -1;
6137 }
6138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 // =========================================================
6140 // THUMBNAILS
6141 // =========================================================
6142
6143 public void reportThumbnail(IBinder token,
6144 Bitmap thumbnail, CharSequence description) {
6145 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6146 final long origId = Binder.clearCallingIdentity();
6147 sendPendingThumbnail(null, token, thumbnail, description, true);
6148 Binder.restoreCallingIdentity(origId);
6149 }
6150
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006151 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 Bitmap thumbnail, CharSequence description, boolean always) {
6153 TaskRecord task = null;
6154 ArrayList receivers = null;
6155
6156 //System.out.println("Send pending thumbnail: " + r);
6157
6158 synchronized(this) {
6159 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006160 r = mMainStack.isInStackLocked(token);
6161 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 return;
6163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006165 if (thumbnail == null && r.thumbHolder != null) {
6166 thumbnail = r.thumbHolder.lastThumbnail;
6167 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168 }
6169 if (thumbnail == null && !always) {
6170 // If there is no thumbnail, and this entry is not actually
6171 // going away, then abort for now and pick up the next
6172 // thumbnail we get.
6173 return;
6174 }
6175 task = r.task;
6176
6177 int N = mPendingThumbnails.size();
6178 int i=0;
6179 while (i<N) {
6180 PendingThumbnailsRecord pr =
6181 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6182 //System.out.println("Looking in " + pr.pendingRecords);
6183 if (pr.pendingRecords.remove(r)) {
6184 if (receivers == null) {
6185 receivers = new ArrayList();
6186 }
6187 receivers.add(pr);
6188 if (pr.pendingRecords.size() == 0) {
6189 pr.finished = true;
6190 mPendingThumbnails.remove(i);
6191 N--;
6192 continue;
6193 }
6194 }
6195 i++;
6196 }
6197 }
6198
6199 if (receivers != null) {
6200 final int N = receivers.size();
6201 for (int i=0; i<N; i++) {
6202 try {
6203 PendingThumbnailsRecord pr =
6204 (PendingThumbnailsRecord)receivers.get(i);
6205 pr.receiver.newThumbnail(
6206 task != null ? task.taskId : -1, thumbnail, description);
6207 if (pr.finished) {
6208 pr.receiver.finished();
6209 }
6210 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006211 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 }
6213 }
6214 }
6215 }
6216
6217 // =========================================================
6218 // CONTENT PROVIDERS
6219 // =========================================================
6220
Jeff Brown10e89712011-07-08 18:52:57 -07006221 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6222 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006224 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006225 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006226 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 } catch (RemoteException ex) {
6228 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006229 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006230 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6231 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006233 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 for (int i=0; i<N; i++) {
6235 ProviderInfo cpi =
6236 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006237 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6238 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006239 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006240 // This is a singleton provider, but a user besides the
6241 // default user is asking to initialize a process it runs
6242 // in... well, no, it doesn't actually run in this process,
6243 // it runs in the process of the default user. Get rid of it.
6244 providers.remove(i);
6245 N--;
6246 continue;
6247 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006248
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006249 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006250 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006252 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006253 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006255 if (DEBUG_MU)
6256 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 app.pubProviders.put(cpi.name, cpr);
6258 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006259 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 }
6261 }
6262 return providers;
6263 }
6264
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006265 /**
6266 * Check if {@link ProcessRecord} has a possible chance at accessing the
6267 * given {@link ProviderInfo}. Final permission checking is always done
6268 * in {@link ContentProvider}.
6269 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006271 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006273 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006275 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006276 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 return null;
6278 }
6279 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006280 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 == PackageManager.PERMISSION_GRANTED) {
6282 return null;
6283 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006284
6285 PathPermission[] pps = cpi.pathPermissions;
6286 if (pps != null) {
6287 int i = pps.length;
6288 while (i > 0) {
6289 i--;
6290 PathPermission pp = pps[i];
6291 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006292 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006293 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006294 return null;
6295 }
6296 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006297 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006298 == PackageManager.PERMISSION_GRANTED) {
6299 return null;
6300 }
6301 }
6302 }
6303
Dianne Hackbornb424b632010-08-18 15:59:05 -07006304 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6305 if (perms != null) {
6306 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6307 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6308 return null;
6309 }
6310 }
6311 }
6312
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006313 String msg;
6314 if (!cpi.exported) {
6315 msg = "Permission Denial: opening provider " + cpi.name
6316 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6317 + ", uid=" + callingUid + ") that is not exported from uid "
6318 + cpi.applicationInfo.uid;
6319 } else {
6320 msg = "Permission Denial: opening provider " + cpi.name
6321 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6322 + ", uid=" + callingUid + ") requires "
6323 + cpi.readPermission + " or " + cpi.writePermission;
6324 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006325 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 return msg;
6327 }
6328
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006329 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6330 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006331 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006332 for (int i=0; i<r.conProviders.size(); i++) {
6333 ContentProviderConnection conn = r.conProviders.get(i);
6334 if (conn.provider == cpr) {
6335 if (DEBUG_PROVIDER) Slog.v(TAG,
6336 "Adding provider requested by "
6337 + r.processName + " from process "
6338 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6339 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6340 if (stable) {
6341 conn.stableCount++;
6342 conn.numStableIncs++;
6343 } else {
6344 conn.unstableCount++;
6345 conn.numUnstableIncs++;
6346 }
6347 return conn;
6348 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006349 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006350 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6351 if (stable) {
6352 conn.stableCount = 1;
6353 conn.numStableIncs = 1;
6354 } else {
6355 conn.unstableCount = 1;
6356 conn.numUnstableIncs = 1;
6357 }
6358 cpr.connections.add(conn);
6359 r.conProviders.add(conn);
6360 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006361 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006362 cpr.addExternalProcessHandleLocked(externalProcessToken);
6363 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006364 }
6365
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006366 boolean decProviderCountLocked(ContentProviderConnection conn,
6367 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6368 if (conn != null) {
6369 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006370 if (DEBUG_PROVIDER) Slog.v(TAG,
6371 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006372 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006373 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006374 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6375 if (stable) {
6376 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006377 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006378 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006379 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006380 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6381 cpr.connections.remove(conn);
6382 conn.client.conProviders.remove(conn);
6383 return true;
6384 }
6385 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006386 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006387 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006388 return false;
6389 }
6390
Amith Yamasani742a6712011-05-04 14:49:28 -07006391 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006392 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006394 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 ProviderInfo cpi = null;
6396
6397 synchronized(this) {
6398 ProcessRecord r = null;
6399 if (caller != null) {
6400 r = getRecordForAppLocked(caller);
6401 if (r == null) {
6402 throw new SecurityException(
6403 "Unable to find app for caller " + caller
6404 + " (pid=" + Binder.getCallingPid()
6405 + ") when getting content provider " + name);
6406 }
6407 }
6408
6409 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006410 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006411 boolean providerRunning = cpr != null;
6412 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006414 String msg;
6415 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6416 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 }
6418
6419 if (r != null && cpr.canRunHere(r)) {
6420 // This provider has been published or is in the process
6421 // of being published... but it is also allowed to run
6422 // in the caller's process, so don't make a connection
6423 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006424 ContentProviderHolder holder = cpr.newHolder(null);
6425 // don't give caller the provider object, it needs
6426 // to make its own.
6427 holder.provider = null;
6428 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006429 }
6430
6431 final long origId = Binder.clearCallingIdentity();
6432
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006433 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006435 conn = incProviderCountLocked(r, cpr, token, stable);
6436 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006437 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006438 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006439 // make sure to count it as being accessed and thus
6440 // back up on the LRU list. This is good because
6441 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006442 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006443 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006444 }
6445
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006446 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006447 if (false) {
6448 if (cpr.name.flattenToShortString().equals(
6449 "com.android.providers.calendar/.CalendarProvider2")) {
6450 Slog.v(TAG, "****************** KILLING "
6451 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006452 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006453 }
6454 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006455 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006456 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6457 // NOTE: there is still a race here where a signal could be
6458 // pending on the process even though we managed to update its
6459 // adj level. Not sure what to do about this, but at least
6460 // the race is now smaller.
6461 if (!success) {
6462 // Uh oh... it looks like the provider's process
6463 // has been killed on us. We need to wait for a new
6464 // process to be started, and make sure its death
6465 // doesn't kill our process.
6466 Slog.i(TAG,
6467 "Existing provider " + cpr.name.flattenToShortString()
6468 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006469 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006470 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006471 if (!lastRef) {
6472 // This wasn't the last ref our process had on
6473 // the provider... we have now been killed, bail.
6474 return null;
6475 }
6476 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006477 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 }
6480
6481 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006484 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006485 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006487 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006488 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006489 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 } catch (RemoteException ex) {
6491 }
6492 if (cpi == null) {
6493 return null;
6494 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006495 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6496 cpi.name, cpi.flags);
6497 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006498 userId = 0;
6499 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006500 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006501
Dianne Hackbornb424b632010-08-18 15:59:05 -07006502 String msg;
6503 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6504 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 }
6506
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006507 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006508 && !cpi.processName.equals("system")) {
6509 // If this content provider does not run in the system
6510 // process, and the system is not yet ready to run other
6511 // processes, then fail fast instead of hanging.
6512 throw new IllegalArgumentException(
6513 "Attempt to launch content provider before system ready");
6514 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006515
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006516 // Make sure that the user who owns this provider is started. If not,
6517 // we don't want to allow it to run.
6518 if (mStartedUsers.get(userId) == null) {
6519 Slog.w(TAG, "Unable to launch app "
6520 + cpi.applicationInfo.packageName + "/"
6521 + cpi.applicationInfo.uid + " for provider "
6522 + name + ": user " + userId + " is stopped");
6523 return null;
6524 }
6525
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006526 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006527 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 final boolean firstClass = cpr == null;
6529 if (firstClass) {
6530 try {
6531 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006532 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 getApplicationInfo(
6534 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006535 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006537 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 + cpi.name);
6539 return null;
6540 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006541 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006542 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 } catch (RemoteException ex) {
6544 // pm is in same process, this will never happen.
6545 }
6546 }
6547
6548 if (r != null && cpr.canRunHere(r)) {
6549 // If this is a multiprocess provider, then just return its
6550 // info and allow the caller to instantiate it. Only do
6551 // this if the provider is the same user as the caller's
6552 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006553 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 }
6555
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006556 if (DEBUG_PROVIDER) {
6557 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006558 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006559 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 }
6561
6562 // This is single process, and our app is now connecting to it.
6563 // See if we are already in the process of launching this
6564 // provider.
6565 final int N = mLaunchingProviders.size();
6566 int i;
6567 for (i=0; i<N; i++) {
6568 if (mLaunchingProviders.get(i) == cpr) {
6569 break;
6570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 }
6572
6573 // If the provider is not already being launched, then get it
6574 // started.
6575 if (i >= N) {
6576 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006577
6578 try {
6579 // Content provider is now in use, its package can't be stopped.
6580 try {
6581 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006582 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006583 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006584 } catch (IllegalArgumentException e) {
6585 Slog.w(TAG, "Failed trying to unstop package "
6586 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006587 }
6588
6589 ProcessRecord proc = startProcessLocked(cpi.processName,
6590 cpr.appInfo, false, 0, "content provider",
6591 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006592 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006593 if (proc == null) {
6594 Slog.w(TAG, "Unable to launch app "
6595 + cpi.applicationInfo.packageName + "/"
6596 + cpi.applicationInfo.uid + " for provider "
6597 + name + ": process is bad");
6598 return null;
6599 }
6600 cpr.launchingApp = proc;
6601 mLaunchingProviders.add(cpr);
6602 } finally {
6603 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006605 }
6606
6607 // Make sure the provider is published (the same provider class
6608 // may be published under multiple names).
6609 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006610 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006612
Amith Yamasani742a6712011-05-04 14:49:28 -07006613 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006614 conn = incProviderCountLocked(r, cpr, token, stable);
6615 if (conn != null) {
6616 conn.waiting = true;
6617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619 }
6620
6621 // Wait for the provider to be published...
6622 synchronized (cpr) {
6623 while (cpr.provider == null) {
6624 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006625 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 + cpi.applicationInfo.packageName + "/"
6627 + cpi.applicationInfo.uid + " for provider "
6628 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006629 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006630 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 cpi.applicationInfo.packageName,
6632 cpi.applicationInfo.uid, name);
6633 return null;
6634 }
6635 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006636 if (DEBUG_MU) {
6637 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6638 + cpr.launchingApp);
6639 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006640 if (conn != null) {
6641 conn.waiting = true;
6642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 cpr.wait();
6644 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006645 } finally {
6646 if (conn != null) {
6647 conn.waiting = false;
6648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 }
6650 }
6651 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006652 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 }
6654
6655 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006656 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006657 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 if (caller == null) {
6659 String msg = "null IApplicationThread when getting content provider "
6660 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006661 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 throw new SecurityException(msg);
6663 }
6664
Dianne Hackborn139748f2012-09-24 11:36:57 -07006665 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006666 false, true, "getContentProvider", null);
6667 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 }
6669
Jeff Sharkey6d515712012-09-20 16:06:08 -07006670 public ContentProviderHolder getContentProviderExternal(
6671 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006672 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6673 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006674 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006675 false, true, "getContentProvider", null);
6676 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006677 }
6678
Dianne Hackborn41203752012-08-31 14:05:51 -07006679 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6680 IBinder token, int userId) {
6681 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 }
6683
6684 /**
6685 * Drop a content provider from a ProcessRecord's bookkeeping
6686 * @param cpr
6687 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006688 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006689 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006691 ContentProviderConnection conn;
6692 try {
6693 conn = (ContentProviderConnection)connection;
6694 } catch (ClassCastException e) {
6695 String msg ="removeContentProvider: " + connection
6696 + " not a ContentProviderConnection";
6697 Slog.w(TAG, msg);
6698 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006700 if (conn == null) {
6701 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006703 if (decProviderCountLocked(conn, null, null, stable)) {
6704 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 }
6707 }
6708
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006709 public void removeContentProviderExternal(String name, IBinder token) {
6710 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6711 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006712 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006713 }
6714
Dianne Hackborn41203752012-08-31 14:05:51 -07006715 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006717 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 if(cpr == null) {
6719 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006720 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 return;
6722 }
6723
6724 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006725 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006726 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006727 if (localCpr.hasExternalProcessHandles()) {
6728 if (localCpr.removeExternalProcessHandleLocked(token)) {
6729 updateOomAdjLocked();
6730 } else {
6731 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6732 + " with no external reference for token: "
6733 + token + ".");
6734 }
6735 } else {
6736 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6737 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 }
6740 }
6741
6742 public final void publishContentProviders(IApplicationThread caller,
6743 List<ContentProviderHolder> providers) {
6744 if (providers == null) {
6745 return;
6746 }
6747
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006748 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006749 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006751 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006752 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 if (r == null) {
6754 throw new SecurityException(
6755 "Unable to find app for caller " + caller
6756 + " (pid=" + Binder.getCallingPid()
6757 + ") when publishing content providers");
6758 }
6759
6760 final long origId = Binder.clearCallingIdentity();
6761
6762 final int N = providers.size();
6763 for (int i=0; i<N; i++) {
6764 ContentProviderHolder src = providers.get(i);
6765 if (src == null || src.info == null || src.provider == null) {
6766 continue;
6767 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006768 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006769 if (DEBUG_MU)
6770 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006772 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006773 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 String names[] = dst.info.authority.split(";");
6775 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006776 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 }
6778
6779 int NL = mLaunchingProviders.size();
6780 int j;
6781 for (j=0; j<NL; j++) {
6782 if (mLaunchingProviders.get(j) == dst) {
6783 mLaunchingProviders.remove(j);
6784 j--;
6785 NL--;
6786 }
6787 }
6788 synchronized (dst) {
6789 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006790 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006791 dst.notifyAll();
6792 }
6793 updateOomAdjLocked(r);
6794 }
6795 }
6796
6797 Binder.restoreCallingIdentity(origId);
6798 }
6799 }
6800
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006801 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6802 ContentProviderConnection conn;
6803 try {
6804 conn = (ContentProviderConnection)connection;
6805 } catch (ClassCastException e) {
6806 String msg ="refContentProvider: " + connection
6807 + " not a ContentProviderConnection";
6808 Slog.w(TAG, msg);
6809 throw new IllegalArgumentException(msg);
6810 }
6811 if (conn == null) {
6812 throw new NullPointerException("connection is null");
6813 }
6814
6815 synchronized (this) {
6816 if (stable > 0) {
6817 conn.numStableIncs += stable;
6818 }
6819 stable = conn.stableCount + stable;
6820 if (stable < 0) {
6821 throw new IllegalStateException("stableCount < 0: " + stable);
6822 }
6823
6824 if (unstable > 0) {
6825 conn.numUnstableIncs += unstable;
6826 }
6827 unstable = conn.unstableCount + unstable;
6828 if (unstable < 0) {
6829 throw new IllegalStateException("unstableCount < 0: " + unstable);
6830 }
6831
6832 if ((stable+unstable) <= 0) {
6833 throw new IllegalStateException("ref counts can't go to zero here: stable="
6834 + stable + " unstable=" + unstable);
6835 }
6836 conn.stableCount = stable;
6837 conn.unstableCount = unstable;
6838 return !conn.dead;
6839 }
6840 }
6841
6842 public void unstableProviderDied(IBinder connection) {
6843 ContentProviderConnection conn;
6844 try {
6845 conn = (ContentProviderConnection)connection;
6846 } catch (ClassCastException e) {
6847 String msg ="refContentProvider: " + connection
6848 + " not a ContentProviderConnection";
6849 Slog.w(TAG, msg);
6850 throw new IllegalArgumentException(msg);
6851 }
6852 if (conn == null) {
6853 throw new NullPointerException("connection is null");
6854 }
6855
6856 // Safely retrieve the content provider associated with the connection.
6857 IContentProvider provider;
6858 synchronized (this) {
6859 provider = conn.provider.provider;
6860 }
6861
6862 if (provider == null) {
6863 // Um, yeah, we're way ahead of you.
6864 return;
6865 }
6866
6867 // Make sure the caller is being honest with us.
6868 if (provider.asBinder().pingBinder()) {
6869 // Er, no, still looks good to us.
6870 synchronized (this) {
6871 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6872 + " says " + conn + " died, but we don't agree");
6873 return;
6874 }
6875 }
6876
6877 // Well look at that! It's dead!
6878 synchronized (this) {
6879 if (conn.provider.provider != provider) {
6880 // But something changed... good enough.
6881 return;
6882 }
6883
6884 ProcessRecord proc = conn.provider.proc;
6885 if (proc == null || proc.thread == null) {
6886 // Seems like the process is already cleaned up.
6887 return;
6888 }
6889
6890 // As far as we're concerned, this is just like receiving a
6891 // death notification... just a bit prematurely.
6892 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6893 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006894 final long ident = Binder.clearCallingIdentity();
6895 try {
6896 appDiedLocked(proc, proc.pid, proc.thread);
6897 } finally {
6898 Binder.restoreCallingIdentity(ident);
6899 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006900 }
6901 }
6902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006904 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006905 synchronized (mSelf) {
6906 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6907 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006908 if (providers != null) {
6909 for (int i=providers.size()-1; i>=0; i--) {
6910 ProviderInfo pi = (ProviderInfo)providers.get(i);
6911 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6912 Slog.w(TAG, "Not installing system proc provider " + pi.name
6913 + ": not system .apk");
6914 providers.remove(i);
6915 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006916 }
6917 }
6918 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006919 if (providers != null) {
6920 mSystemThread.installSystemProviders(providers);
6921 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006922
6923 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006924
6925 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 }
6927
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006928 /**
6929 * Allows app to retrieve the MIME type of a URI without having permission
6930 * to access its content provider.
6931 *
6932 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6933 *
6934 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6935 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6936 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006937 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006938 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006939 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006940 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006941 final String name = uri.getAuthority();
6942 final long ident = Binder.clearCallingIdentity();
6943 ContentProviderHolder holder = null;
6944
6945 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006946 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006947 if (holder != null) {
6948 return holder.provider.getType(uri);
6949 }
6950 } catch (RemoteException e) {
6951 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6952 return null;
6953 } finally {
6954 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006955 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006956 }
6957 Binder.restoreCallingIdentity(ident);
6958 }
6959
6960 return null;
6961 }
6962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 // =========================================================
6964 // GLOBAL MANAGEMENT
6965 // =========================================================
6966
6967 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006968 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 String proc = customProcess != null ? customProcess : info.processName;
6970 BatteryStatsImpl.Uid.Proc ps = null;
6971 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006972 int uid = info.uid;
6973 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006974 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006975 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6976 uid = 0;
6977 while (true) {
6978 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6979 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6980 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6981 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006982 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006983 mNextIsolatedProcessUid++;
6984 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6985 // No process for this uid, use it.
6986 break;
6987 }
6988 stepsLeft--;
6989 if (stepsLeft <= 0) {
6990 return null;
6991 }
6992 }
6993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006994 synchronized (stats) {
6995 ps = stats.getProcessStatsLocked(info.uid, proc);
6996 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006997 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 }
6999
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007000 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7001 ProcessRecord app;
7002 if (!isolated) {
7003 app = getProcessRecordLocked(info.processName, info.uid);
7004 } else {
7005 app = null;
7006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007007
7008 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007009 app = newProcessRecordLocked(null, info, null, isolated);
7010 mProcessNames.put(info.processName, app.uid, app);
7011 if (isolated) {
7012 mIsolatedProcesses.put(app.uid, app);
7013 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007014 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 }
7016
Dianne Hackborne7f97212011-02-24 14:40:20 -08007017 // This package really, really can not be stopped.
7018 try {
7019 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007020 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007021 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007022 } catch (IllegalArgumentException e) {
7023 Slog.w(TAG, "Failed trying to unstop package "
7024 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007025 }
7026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7028 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7029 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007030 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 }
7032 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7033 mPersistentStartingProcesses.add(app);
7034 startProcessLocked(app, "added application", app.processName);
7035 }
7036
7037 return app;
7038 }
7039
7040 public void unhandledBack() {
7041 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7042 "unhandledBack()");
7043
7044 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007045 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007046 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 TAG, "Performing unhandledBack(): stack size = " + count);
7048 if (count > 1) {
7049 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007050 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007051 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 Binder.restoreCallingIdentity(origId);
7053 }
7054 }
7055 }
7056
7057 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007058 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007059 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007061 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 ParcelFileDescriptor pfd = null;
7063 if (cph != null) {
7064 // We record the binder invoker's uid in thread-local storage before
7065 // going to the content provider to open the file. Later, in the code
7066 // that handles all permissions checks, we look for this uid and use
7067 // that rather than the Activity Manager's own uid. The effect is that
7068 // we do the check against the caller's permissions even though it looks
7069 // to the content provider like the Activity Manager itself is making
7070 // the request.
7071 sCallerIdentity.set(new Identity(
7072 Binder.getCallingPid(), Binder.getCallingUid()));
7073 try {
7074 pfd = cph.provider.openFile(uri, "r");
7075 } catch (FileNotFoundException e) {
7076 // do nothing; pfd will be returned null
7077 } finally {
7078 // Ensure that whatever happens, we clean up the identity state
7079 sCallerIdentity.remove();
7080 }
7081
7082 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007083 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007085 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 }
7087 return pfd;
7088 }
7089
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007090 // Actually is sleeping or shutting down or whatever else in the future
7091 // is an inactive state.
7092 public boolean isSleeping() {
7093 return mSleeping || mShuttingDown;
7094 }
7095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007097 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7098 != PackageManager.PERMISSION_GRANTED) {
7099 throw new SecurityException("Requires permission "
7100 + android.Manifest.permission.DEVICE_POWER);
7101 }
7102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007104 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007105 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007107 if (!mSleeping) {
7108 mSleeping = true;
7109 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007110
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007111 // Initialize the wake times of all processes.
7112 checkExcessivePowerUsageLocked(false);
7113 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7114 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7115 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 }
7118 }
7119
Dianne Hackborn55280a92009-05-07 15:53:46 -07007120 public boolean shutdown(int timeout) {
7121 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7122 != PackageManager.PERMISSION_GRANTED) {
7123 throw new SecurityException("Requires permission "
7124 + android.Manifest.permission.SHUTDOWN);
7125 }
7126
7127 boolean timedout = false;
7128
7129 synchronized(this) {
7130 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007131 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007132
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007133 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007134 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007135 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007136 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007137 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007138 long delay = endTime - System.currentTimeMillis();
7139 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007140 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007141 timedout = true;
7142 break;
7143 }
7144 try {
7145 this.wait();
7146 } catch (InterruptedException e) {
7147 }
7148 }
7149 }
7150 }
7151
7152 mUsageStatsService.shutdown();
7153 mBatteryStatsService.shutdown();
7154
7155 return timedout;
7156 }
7157
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007158 public final void activitySlept(IBinder token) {
7159 if (localLOGV) Slog.v(
7160 TAG, "Activity slept: token=" + token);
7161
7162 ActivityRecord r = null;
7163
7164 final long origId = Binder.clearCallingIdentity();
7165
7166 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007167 r = mMainStack.isInStackLocked(token);
7168 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007169 mMainStack.activitySleptLocked(r);
7170 }
7171 }
7172
7173 Binder.restoreCallingIdentity(origId);
7174 }
7175
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007176 private void comeOutOfSleepIfNeededLocked() {
7177 if (!mWentToSleep && !mLockScreenShown) {
7178 if (mSleeping) {
7179 mSleeping = false;
7180 mMainStack.awakeFromSleepingLocked();
7181 mMainStack.resumeTopActivityLocked(null);
7182 }
7183 }
7184 }
7185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007186 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007187 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7188 != PackageManager.PERMISSION_GRANTED) {
7189 throw new SecurityException("Requires permission "
7190 + android.Manifest.permission.DEVICE_POWER);
7191 }
7192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007193 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007194 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007195 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007196 comeOutOfSleepIfNeededLocked();
7197 }
7198 }
7199
Jeff Brownc042ee22012-05-08 13:03:42 -07007200 private void updateEventDispatchingLocked() {
7201 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7202 }
7203
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007204 public void setLockScreenShown(boolean shown) {
7205 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7206 != PackageManager.PERMISSION_GRANTED) {
7207 throw new SecurityException("Requires permission "
7208 + android.Manifest.permission.DEVICE_POWER);
7209 }
7210
7211 synchronized(this) {
7212 mLockScreenShown = shown;
7213 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007214 }
7215 }
7216
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007217 public void stopAppSwitches() {
7218 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7219 != PackageManager.PERMISSION_GRANTED) {
7220 throw new SecurityException("Requires permission "
7221 + android.Manifest.permission.STOP_APP_SWITCHES);
7222 }
7223
7224 synchronized(this) {
7225 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7226 + APP_SWITCH_DELAY_TIME;
7227 mDidAppSwitch = false;
7228 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7229 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7230 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7231 }
7232 }
7233
7234 public void resumeAppSwitches() {
7235 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7236 != PackageManager.PERMISSION_GRANTED) {
7237 throw new SecurityException("Requires permission "
7238 + android.Manifest.permission.STOP_APP_SWITCHES);
7239 }
7240
7241 synchronized(this) {
7242 // Note that we don't execute any pending app switches... we will
7243 // let those wait until either the timeout, or the next start
7244 // activity request.
7245 mAppSwitchesAllowedTime = 0;
7246 }
7247 }
7248
7249 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7250 String name) {
7251 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7252 return true;
7253 }
7254
7255 final int perm = checkComponentPermission(
7256 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007257 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007258 if (perm == PackageManager.PERMISSION_GRANTED) {
7259 return true;
7260 }
7261
Joe Onorato8a9b2202010-02-26 18:56:32 -08007262 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007263 return false;
7264 }
7265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 public void setDebugApp(String packageName, boolean waitForDebugger,
7267 boolean persistent) {
7268 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7269 "setDebugApp()");
7270
7271 // Note that this is not really thread safe if there are multiple
7272 // callers into it at the same time, but that's not a situation we
7273 // care about.
7274 if (persistent) {
7275 final ContentResolver resolver = mContext.getContentResolver();
7276 Settings.System.putString(
7277 resolver, Settings.System.DEBUG_APP,
7278 packageName);
7279 Settings.System.putInt(
7280 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7281 waitForDebugger ? 1 : 0);
7282 }
7283
7284 synchronized (this) {
7285 if (!persistent) {
7286 mOrigDebugApp = mDebugApp;
7287 mOrigWaitForDebugger = mWaitForDebugger;
7288 }
7289 mDebugApp = packageName;
7290 mWaitForDebugger = waitForDebugger;
7291 mDebugTransient = !persistent;
7292 if (packageName != null) {
7293 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007294 forceStopPackageLocked(packageName, -1, false, false, true, true,
7295 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 Binder.restoreCallingIdentity(origId);
7297 }
7298 }
7299 }
7300
Siva Velusamy92a8b222012-03-09 16:24:04 -08007301 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7302 synchronized (this) {
7303 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7304 if (!isDebuggable) {
7305 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7306 throw new SecurityException("Process not debuggable: " + app.packageName);
7307 }
7308 }
7309
7310 mOpenGlTraceApp = processName;
7311 }
7312 }
7313
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007314 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7315 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7316 synchronized (this) {
7317 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7318 if (!isDebuggable) {
7319 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7320 throw new SecurityException("Process not debuggable: " + app.packageName);
7321 }
7322 }
7323 mProfileApp = processName;
7324 mProfileFile = profileFile;
7325 if (mProfileFd != null) {
7326 try {
7327 mProfileFd.close();
7328 } catch (IOException e) {
7329 }
7330 mProfileFd = null;
7331 }
7332 mProfileFd = profileFd;
7333 mProfileType = 0;
7334 mAutoStopProfiler = autoStopProfiler;
7335 }
7336 }
7337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 public void setAlwaysFinish(boolean enabled) {
7339 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7340 "setAlwaysFinish()");
7341
7342 Settings.System.putInt(
7343 mContext.getContentResolver(),
7344 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7345
7346 synchronized (this) {
7347 mAlwaysFinishActivities = enabled;
7348 }
7349 }
7350
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007351 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007353 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007355 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 }
7357 }
7358
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007359 public boolean isUserAMonkey() {
7360 // For now the fact that there is a controller implies
7361 // we have a monkey.
7362 synchronized (this) {
7363 return mController != null;
7364 }
7365 }
7366
Jeff Sharkeya4620792011-05-20 15:29:23 -07007367 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007368 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7369 "registerProcessObserver()");
7370 synchronized (this) {
7371 mProcessObservers.register(observer);
7372 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007373 }
7374
7375 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007376 synchronized (this) {
7377 mProcessObservers.unregister(observer);
7378 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007379 }
7380
Daniel Sandler69a48172010-06-23 16:29:36 -04007381 public void setImmersive(IBinder token, boolean immersive) {
7382 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007383 ActivityRecord r = mMainStack.isInStackLocked(token);
7384 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007385 throw new IllegalArgumentException();
7386 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007387 r.immersive = immersive;
7388 }
7389 }
7390
7391 public boolean isImmersive(IBinder token) {
7392 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007393 ActivityRecord r = mMainStack.isInStackLocked(token);
7394 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007395 throw new IllegalArgumentException();
7396 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007397 return r.immersive;
7398 }
7399 }
7400
7401 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007402 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007403 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007404 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007405 return (r != null) ? r.immersive : false;
7406 }
7407 }
7408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 public final void enterSafeMode() {
7410 synchronized(this) {
7411 // It only makes sense to do this before the system is ready
7412 // and started launching other packages.
7413 if (!mSystemReady) {
7414 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007415 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 } catch (RemoteException e) {
7417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 }
7419 }
7420 }
7421
Jeff Brownb09abc12011-01-13 21:08:27 -08007422 public final void showSafeModeOverlay() {
7423 View v = LayoutInflater.from(mContext).inflate(
7424 com.android.internal.R.layout.safe_mode, null);
7425 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7426 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7427 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7428 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007429 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007430 lp.format = v.getBackground().getOpacity();
7431 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7432 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7433 ((WindowManager)mContext.getSystemService(
7434 Context.WINDOW_SERVICE)).addView(v, lp);
7435 }
7436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 public void noteWakeupAlarm(IIntentSender sender) {
7438 if (!(sender instanceof PendingIntentRecord)) {
7439 return;
7440 }
7441 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7442 synchronized (stats) {
7443 if (mBatteryStatsService.isOnBattery()) {
7444 mBatteryStatsService.enforceCallingPermission();
7445 PendingIntentRecord rec = (PendingIntentRecord)sender;
7446 int MY_UID = Binder.getCallingUid();
7447 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7448 BatteryStatsImpl.Uid.Pkg pkg =
7449 stats.getPackageStatsLocked(uid, rec.key.packageName);
7450 pkg.incWakeupsLocked();
7451 }
7452 }
7453 }
7454
Dianne Hackborn64825172011-03-02 21:32:58 -08007455 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007457 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007459 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 // XXX Note: don't acquire main activity lock here, because the window
7461 // manager calls in with its locks held.
7462
7463 boolean killed = false;
7464 synchronized (mPidsSelfLocked) {
7465 int[] types = new int[pids.length];
7466 int worstType = 0;
7467 for (int i=0; i<pids.length; i++) {
7468 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7469 if (proc != null) {
7470 int type = proc.setAdj;
7471 types[i] = type;
7472 if (type > worstType) {
7473 worstType = type;
7474 }
7475 }
7476 }
7477
Dianne Hackborn64825172011-03-02 21:32:58 -08007478 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007479 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007480 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7481 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007482 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007484
7485 // If this is not a secure call, don't let it kill processes that
7486 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007487 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7488 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007489 }
7490
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007491 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 for (int i=0; i<pids.length; i++) {
7493 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7494 if (proc == null) {
7495 continue;
7496 }
7497 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007498 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007499 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007500 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007501 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007503 proc.killedBackground = true;
7504 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 }
7506 }
7507 }
7508 return killed;
7509 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007510
7511 @Override
7512 public boolean killProcessesBelowForeground(String reason) {
7513 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7514 throw new SecurityException("killProcessesBelowForeground() only available to system");
7515 }
7516
7517 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7518 }
7519
7520 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7521 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7522 throw new SecurityException("killProcessesBelowAdj() only available to system");
7523 }
7524
7525 boolean killed = false;
7526 synchronized (mPidsSelfLocked) {
7527 final int size = mPidsSelfLocked.size();
7528 for (int i = 0; i < size; i++) {
7529 final int pid = mPidsSelfLocked.keyAt(i);
7530 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7531 if (proc == null) continue;
7532
7533 final int adj = proc.setAdj;
7534 if (adj > belowAdj && !proc.killedBackground) {
7535 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007536 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7537 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007538 killed = true;
7539 proc.killedBackground = true;
7540 Process.killProcessQuiet(pid);
7541 }
7542 }
7543 }
7544 return killed;
7545 }
7546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 public final void startRunning(String pkg, String cls, String action,
7548 String data) {
7549 synchronized(this) {
7550 if (mStartRunning) {
7551 return;
7552 }
7553 mStartRunning = true;
7554 mTopComponent = pkg != null && cls != null
7555 ? new ComponentName(pkg, cls) : null;
7556 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7557 mTopData = data;
7558 if (!mSystemReady) {
7559 return;
7560 }
7561 }
7562
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007563 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 }
7565
7566 private void retrieveSettings() {
7567 final ContentResolver resolver = mContext.getContentResolver();
7568 String debugApp = Settings.System.getString(
7569 resolver, Settings.System.DEBUG_APP);
7570 boolean waitForDebugger = Settings.System.getInt(
7571 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7572 boolean alwaysFinishActivities = Settings.System.getInt(
7573 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7574
7575 Configuration configuration = new Configuration();
7576 Settings.System.getConfiguration(resolver, configuration);
7577
7578 synchronized (this) {
7579 mDebugApp = mOrigDebugApp = debugApp;
7580 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7581 mAlwaysFinishActivities = alwaysFinishActivities;
7582 // This happens before any activities are started, so we can
7583 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007584 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007585 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 }
7587 }
7588
7589 public boolean testIsSystemReady() {
7590 // no need to synchronize(this) just to read & return the value
7591 return mSystemReady;
7592 }
7593
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007594 private static File getCalledPreBootReceiversFile() {
7595 File dataDir = Environment.getDataDirectory();
7596 File systemDir = new File(dataDir, "system");
7597 File fname = new File(systemDir, "called_pre_boots.dat");
7598 return fname;
7599 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007600
7601 static final int LAST_DONE_VERSION = 10000;
7602
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007603 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7604 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7605 File file = getCalledPreBootReceiversFile();
7606 FileInputStream fis = null;
7607 try {
7608 fis = new FileInputStream(file);
7609 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007610 int fvers = dis.readInt();
7611 if (fvers == LAST_DONE_VERSION) {
7612 String vers = dis.readUTF();
7613 String codename = dis.readUTF();
7614 String build = dis.readUTF();
7615 if (android.os.Build.VERSION.RELEASE.equals(vers)
7616 && android.os.Build.VERSION.CODENAME.equals(codename)
7617 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7618 int num = dis.readInt();
7619 while (num > 0) {
7620 num--;
7621 String pkg = dis.readUTF();
7622 String cls = dis.readUTF();
7623 lastDoneReceivers.add(new ComponentName(pkg, cls));
7624 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007625 }
7626 }
7627 } catch (FileNotFoundException e) {
7628 } catch (IOException e) {
7629 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7630 } finally {
7631 if (fis != null) {
7632 try {
7633 fis.close();
7634 } catch (IOException e) {
7635 }
7636 }
7637 }
7638 return lastDoneReceivers;
7639 }
7640
7641 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7642 File file = getCalledPreBootReceiversFile();
7643 FileOutputStream fos = null;
7644 DataOutputStream dos = null;
7645 try {
7646 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7647 fos = new FileOutputStream(file);
7648 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007649 dos.writeInt(LAST_DONE_VERSION);
7650 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007651 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007652 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007653 dos.writeInt(list.size());
7654 for (int i=0; i<list.size(); i++) {
7655 dos.writeUTF(list.get(i).getPackageName());
7656 dos.writeUTF(list.get(i).getClassName());
7657 }
7658 } catch (IOException e) {
7659 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7660 file.delete();
7661 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007662 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007663 if (dos != null) {
7664 try {
7665 dos.close();
7666 } catch (IOException e) {
7667 // TODO Auto-generated catch block
7668 e.printStackTrace();
7669 }
7670 }
7671 }
7672 }
7673
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007674 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 synchronized(this) {
7676 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007677 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 return;
7679 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007680
7681 // Check to see if there are any update receivers to run.
7682 if (!mDidUpdate) {
7683 if (mWaitingUpdate) {
7684 return;
7685 }
7686 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7687 List<ResolveInfo> ris = null;
7688 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007689 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007690 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007691 } catch (RemoteException e) {
7692 }
7693 if (ris != null) {
7694 for (int i=ris.size()-1; i>=0; i--) {
7695 if ((ris.get(i).activityInfo.applicationInfo.flags
7696 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7697 ris.remove(i);
7698 }
7699 }
7700 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007701
7702 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7703
7704 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007705 for (int i=0; i<ris.size(); i++) {
7706 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007707 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7708 if (lastDoneReceivers.contains(comp)) {
7709 ris.remove(i);
7710 i--;
7711 }
7712 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007713
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007714 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007715 for (int i=0; i<ris.size(); i++) {
7716 ActivityInfo ai = ris.get(i).activityInfo;
7717 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7718 doneReceivers.add(comp);
7719 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007720 for (int j=0; j<users.length; j++) {
7721 IIntentReceiver finisher = null;
7722 if (i == ris.size()-1 && j == users.length-1) {
7723 finisher = new IIntentReceiver.Stub() {
7724 public void performReceive(Intent intent, int resultCode,
7725 String data, Bundle extras, boolean ordered,
7726 boolean sticky, int sendingUser) {
7727 // The raw IIntentReceiver interface is called
7728 // with the AM lock held, so redispatch to
7729 // execute our code without the lock.
7730 mHandler.post(new Runnable() {
7731 public void run() {
7732 synchronized (ActivityManagerService.this) {
7733 mDidUpdate = true;
7734 }
7735 writeLastDonePreBootReceivers(doneReceivers);
7736 showBootMessage(mContext.getText(
7737 R.string.android_upgrading_complete),
7738 false);
7739 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007740 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007741 });
7742 }
7743 };
7744 }
7745 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7746 + " for user " + users[j]);
7747 broadcastIntentLocked(null, null, intent, null, finisher,
7748 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7749 users[j]);
7750 if (finisher != null) {
7751 mWaitingUpdate = true;
7752 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007753 }
7754 }
7755 }
7756 if (mWaitingUpdate) {
7757 return;
7758 }
7759 mDidUpdate = true;
7760 }
7761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 mSystemReady = true;
7763 if (!mStartRunning) {
7764 return;
7765 }
7766 }
7767
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007768 ArrayList<ProcessRecord> procsToKill = null;
7769 synchronized(mPidsSelfLocked) {
7770 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7771 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7772 if (!isAllowedWhileBooting(proc.info)){
7773 if (procsToKill == null) {
7774 procsToKill = new ArrayList<ProcessRecord>();
7775 }
7776 procsToKill.add(proc);
7777 }
7778 }
7779 }
7780
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007781 synchronized(this) {
7782 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007783 for (int i=procsToKill.size()-1; i>=0; i--) {
7784 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007785 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007786 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007787 }
7788 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007789
7790 // Now that we have cleaned up any update processes, we
7791 // are ready to start launching real processes and know that
7792 // we won't trample on them any more.
7793 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007794 }
7795
Joe Onorato8a9b2202010-02-26 18:56:32 -08007796 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007797 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 SystemClock.uptimeMillis());
7799
7800 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007801 // Make sure we have no pre-ready processes sitting around.
7802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7804 ResolveInfo ri = mContext.getPackageManager()
7805 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007806 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 CharSequence errorMsg = null;
7808 if (ri != null) {
7809 ActivityInfo ai = ri.activityInfo;
7810 ApplicationInfo app = ai.applicationInfo;
7811 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7812 mTopAction = Intent.ACTION_FACTORY_TEST;
7813 mTopData = null;
7814 mTopComponent = new ComponentName(app.packageName,
7815 ai.name);
7816 } else {
7817 errorMsg = mContext.getResources().getText(
7818 com.android.internal.R.string.factorytest_not_system);
7819 }
7820 } else {
7821 errorMsg = mContext.getResources().getText(
7822 com.android.internal.R.string.factorytest_no_action);
7823 }
7824 if (errorMsg != null) {
7825 mTopAction = null;
7826 mTopData = null;
7827 mTopComponent = null;
7828 Message msg = Message.obtain();
7829 msg.what = SHOW_FACTORY_ERROR_MSG;
7830 msg.getData().putCharSequence("msg", errorMsg);
7831 mHandler.sendMessage(msg);
7832 }
7833 }
7834 }
7835
7836 retrieveSettings();
7837
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007838 if (goingCallback != null) goingCallback.run();
7839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 synchronized (this) {
7841 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7842 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007843 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007844 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007845 if (apps != null) {
7846 int N = apps.size();
7847 int i;
7848 for (i=0; i<N; i++) {
7849 ApplicationInfo info
7850 = (ApplicationInfo)apps.get(i);
7851 if (info != null &&
7852 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007853 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 }
7855 }
7856 }
7857 } catch (RemoteException ex) {
7858 // pm is in same process, this will never happen.
7859 }
7860 }
7861
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007862 // Start up initial activity.
7863 mBooting = true;
7864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007865 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007866 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007867 Message msg = Message.obtain();
7868 msg.what = SHOW_UID_ERROR_MSG;
7869 mHandler.sendMessage(msg);
7870 }
7871 } catch (RemoteException e) {
7872 }
7873
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007874 long ident = Binder.clearCallingIdentity();
7875 try {
7876 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7877 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7878 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7879 broadcastIntentLocked(null, null, intent,
7880 null, null, 0, null, null, null,
7881 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
7882 } finally {
7883 Binder.restoreCallingIdentity(ident);
7884 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007885 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007886 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 }
7888 }
7889
Dan Egnorb7f03672009-12-09 16:22:32 -08007890 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007891 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007893 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007894 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 startAppProblemLocked(app);
7896 app.stopFreezingAllLocked();
7897 return handleAppCrashLocked(app);
7898 }
7899
Dan Egnorb7f03672009-12-09 16:22:32 -08007900 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007901 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007903 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007904 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7905 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 startAppProblemLocked(app);
7907 app.stopFreezingAllLocked();
7908 }
7909
7910 /**
7911 * Generate a process error record, suitable for attachment to a ProcessRecord.
7912 *
7913 * @param app The ProcessRecord in which the error occurred.
7914 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7915 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007916 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 * @param shortMsg Short message describing the crash.
7918 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007919 * @param stackTrace Full crash stack trace, may be null.
7920 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 * @return Returns a fully-formed AppErrorStateInfo record.
7922 */
7923 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007924 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 report.condition = condition;
7928 report.processName = app.processName;
7929 report.pid = app.pid;
7930 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007931 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007932 report.shortMsg = shortMsg;
7933 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007934 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935
7936 return report;
7937 }
7938
Dan Egnor42471dd2010-01-07 17:25:22 -08007939 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 synchronized (this) {
7941 app.crashing = false;
7942 app.crashingReport = null;
7943 app.notResponding = false;
7944 app.notRespondingReport = null;
7945 if (app.anrDialog == fromDialog) {
7946 app.anrDialog = null;
7947 }
7948 if (app.waitDialog == fromDialog) {
7949 app.waitDialog = null;
7950 }
7951 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007952 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007953 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007954 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07007955 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007956 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 }
7959 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007960
Dan Egnorb7f03672009-12-09 16:22:32 -08007961 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007962 if (mHeadless) {
7963 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7964 return false;
7965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 long now = SystemClock.uptimeMillis();
7967
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007968 Long crashTime;
7969 if (!app.isolated) {
7970 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7971 } else {
7972 crashTime = null;
7973 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007974 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007976 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007978 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007979 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007980 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7981 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007983 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007985 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7986 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 }
7988 }
7989 if (!app.persistent) {
7990 // We don't want to start this process again until the user
7991 // explicitly does so... but for persistent process, we really
7992 // need to keep it running. If a persistent process is actually
7993 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007994 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007996 if (!app.isolated) {
7997 // XXX We don't have a way to mark isolated processes
7998 // as bad, since they don't have a peristent identity.
7999 mBadProcesses.put(app.info.processName, app.uid, now);
8000 mProcessCrashTimes.remove(app.info.processName, app.uid);
8001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008004 // Don't let services in this process be restarted and potentially
8005 // annoy the user repeatedly. Unless it is persistent, since those
8006 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008007 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008008 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 return false;
8010 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008011 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008012 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008013 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008014 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008015 // If the top running activity is from this crashing
8016 // process, then terminate it to avoid getting in a loop.
8017 Slog.w(TAG, " Force finishing activity "
8018 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008019 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008020 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008021 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008022 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008023 // stopped, to avoid a situation where one will get
8024 // re-start our crashing activity once it gets resumed again.
8025 index--;
8026 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008027 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008028 if (r.state == ActivityState.RESUMED
8029 || r.state == ActivityState.PAUSING
8030 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008031 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008032 Slog.w(TAG, " Force finishing activity "
8033 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008034 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008035 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008036 }
8037 }
8038 }
8039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 }
8041
8042 // Bump up the crash count of any services currently running in the proc.
8043 if (app.services.size() != 0) {
8044 // Any services running in the application need to be placed
8045 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008046 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008048 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 sr.crashCount++;
8050 }
8051 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008052
8053 // If the crashing process is what we consider to be the "home process" and it has been
8054 // replaced by a third-party app, clear the package preferred activities from packages
8055 // with a home activity running in the process to prevent a repeatedly crashing app
8056 // from blocking the user to manually clear the list.
8057 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8058 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8059 Iterator it = mHomeProcess.activities.iterator();
8060 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008061 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008062 if (r.isHomeActivity) {
8063 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8064 try {
8065 ActivityThread.getPackageManager()
8066 .clearPackagePreferredActivities(r.packageName);
8067 } catch (RemoteException c) {
8068 // pm is in same process, this will never happen.
8069 }
8070 }
8071 }
8072 }
8073
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008074 if (!app.isolated) {
8075 // XXX Can't keep track of crash times for isolated processes,
8076 // because they don't have a perisistent identity.
8077 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8078 }
8079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080 return true;
8081 }
8082
8083 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008084 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8085 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 skipCurrentReceiverLocked(app);
8087 }
8088
8089 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008090 for (BroadcastQueue queue : mBroadcastQueues) {
8091 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 }
8093 }
8094
Dan Egnor60d87622009-12-16 16:32:58 -08008095 /**
8096 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8097 * The application process will exit immediately after this call returns.
8098 * @param app object of the crashing app, null for the system server
8099 * @param crashInfo describing the exception
8100 */
8101 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008102 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008103 final String processName = app == null ? "system_server"
8104 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008105
8106 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008107 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008108 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008109 crashInfo.exceptionClassName,
8110 crashInfo.exceptionMessage,
8111 crashInfo.throwFileName,
8112 crashInfo.throwLineNumber);
8113
Jeff Sharkeya353d262011-10-28 11:12:06 -07008114 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008115
8116 crashApplication(r, crashInfo);
8117 }
8118
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008119 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008120 IBinder app,
8121 int violationMask,
8122 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008123 ProcessRecord r = findAppProcess(app, "StrictMode");
8124 if (r == null) {
8125 return;
8126 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008127
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008128 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008129 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008130 boolean logIt = true;
8131 synchronized (mAlreadyLoggedViolatedStacks) {
8132 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8133 logIt = false;
8134 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008135 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008136 // the relative pain numbers, without logging all
8137 // the stack traces repeatedly. We'd want to do
8138 // likewise in the client code, which also does
8139 // dup suppression, before the Binder call.
8140 } else {
8141 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8142 mAlreadyLoggedViolatedStacks.clear();
8143 }
8144 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8145 }
8146 }
8147 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008148 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008149 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008150 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008151
8152 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8153 AppErrorResult result = new AppErrorResult();
8154 synchronized (this) {
8155 final long origId = Binder.clearCallingIdentity();
8156
8157 Message msg = Message.obtain();
8158 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8159 HashMap<String, Object> data = new HashMap<String, Object>();
8160 data.put("result", result);
8161 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008162 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008163 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008164 msg.obj = data;
8165 mHandler.sendMessage(msg);
8166
8167 Binder.restoreCallingIdentity(origId);
8168 }
8169 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008170 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008171 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008172 }
8173
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008174 // Depending on the policy in effect, there could be a bunch of
8175 // these in quick succession so we try to batch these together to
8176 // minimize disk writes, number of dropbox entries, and maximize
8177 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008178 private void logStrictModeViolationToDropBox(
8179 ProcessRecord process,
8180 StrictMode.ViolationInfo info) {
8181 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008182 return;
8183 }
8184 final boolean isSystemApp = process == null ||
8185 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8186 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008187 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008188 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8189 final DropBoxManager dbox = (DropBoxManager)
8190 mContext.getSystemService(Context.DROPBOX_SERVICE);
8191
8192 // Exit early if the dropbox isn't configured to accept this report type.
8193 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8194
8195 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008196 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008197 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8198 synchronized (sb) {
8199 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008200 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008201 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8202 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008203 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8204 if (info.violationNumThisLoop != 0) {
8205 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8206 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008207 if (info.numAnimationsRunning != 0) {
8208 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8209 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008210 if (info.broadcastIntentAction != null) {
8211 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8212 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008213 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008214 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008215 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008216 if (info.numInstances != -1) {
8217 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8218 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008219 if (info.tags != null) {
8220 for (String tag : info.tags) {
8221 sb.append("Span-Tag: ").append(tag).append("\n");
8222 }
8223 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008224 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008225 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8226 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008227 }
8228 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008229
8230 // Only buffer up to ~64k. Various logging bits truncate
8231 // things at 128k.
8232 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008233 }
8234
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008235 // Flush immediately if the buffer's grown too large, or this
8236 // is a non-system app. Non-system apps are isolated with a
8237 // different tag & policy and not batched.
8238 //
8239 // Batching is useful during internal testing with
8240 // StrictMode settings turned up high. Without batching,
8241 // thousands of separate files could be created on boot.
8242 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008243 new Thread("Error dump: " + dropboxTag) {
8244 @Override
8245 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008246 String report;
8247 synchronized (sb) {
8248 report = sb.toString();
8249 sb.delete(0, sb.length());
8250 sb.trimToSize();
8251 }
8252 if (report.length() != 0) {
8253 dbox.addText(dropboxTag, report);
8254 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008255 }
8256 }.start();
8257 return;
8258 }
8259
8260 // System app batching:
8261 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008262 // An existing dropbox-writing thread is outstanding, so
8263 // we don't need to start it up. The existing thread will
8264 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008265 return;
8266 }
8267
8268 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8269 // (After this point, we shouldn't access AMS internal data structures.)
8270 new Thread("Error dump: " + dropboxTag) {
8271 @Override
8272 public void run() {
8273 // 5 second sleep to let stacks arrive and be batched together
8274 try {
8275 Thread.sleep(5000); // 5 seconds
8276 } catch (InterruptedException e) {}
8277
8278 String errorReport;
8279 synchronized (mStrictModeBuffer) {
8280 errorReport = mStrictModeBuffer.toString();
8281 if (errorReport.length() == 0) {
8282 return;
8283 }
8284 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8285 mStrictModeBuffer.trimToSize();
8286 }
8287 dbox.addText(dropboxTag, errorReport);
8288 }
8289 }.start();
8290 }
8291
Dan Egnor60d87622009-12-16 16:32:58 -08008292 /**
8293 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8294 * @param app object of the crashing app, null for the system server
8295 * @param tag reported by the caller
8296 * @param crashInfo describing the context of the error
8297 * @return true if the process should exit immediately (WTF is fatal)
8298 */
8299 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008300 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008301 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008302 final String processName = app == null ? "system_server"
8303 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008304
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008305 EventLog.writeEvent(EventLogTags.AM_WTF,
8306 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008307 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008308 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008309 tag, crashInfo.exceptionMessage);
8310
Jeff Sharkeya353d262011-10-28 11:12:06 -07008311 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008312
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008313 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008314 Settings.Global.getInt(mContext.getContentResolver(),
8315 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008316 crashApplication(r, crashInfo);
8317 return true;
8318 } else {
8319 return false;
8320 }
8321 }
8322
8323 /**
8324 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8325 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8326 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008327 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008328 if (app == null) {
8329 return null;
8330 }
8331
8332 synchronized (this) {
8333 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8334 final int NA = apps.size();
8335 for (int ia=0; ia<NA; ia++) {
8336 ProcessRecord p = apps.valueAt(ia);
8337 if (p.thread != null && p.thread.asBinder() == app) {
8338 return p;
8339 }
8340 }
8341 }
8342
Dianne Hackborncb44d962011-03-10 17:02:27 -08008343 Slog.w(TAG, "Can't find mystery application for " + reason
8344 + " from pid=" + Binder.getCallingPid()
8345 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008346 return null;
8347 }
8348 }
8349
8350 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008351 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8352 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008353 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008354 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8355 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008356 // Watchdog thread ends up invoking this function (with
8357 // a null ProcessRecord) to add the stack file to dropbox.
8358 // Do not acquire a lock on this (am) in such cases, as it
8359 // could cause a potential deadlock, if and when watchdog
8360 // is invoked due to unavailability of lock on am and it
8361 // would prevent watchdog from killing system_server.
8362 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008363 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008364 return;
8365 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008366 // Note: ProcessRecord 'process' is guarded by the service
8367 // instance. (notably process.pkgList, which could otherwise change
8368 // concurrently during execution of this method)
8369 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008370 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008371 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008372 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008373 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8374 for (String pkg : process.pkgList) {
8375 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008376 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008377 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008378 if (pi != null) {
8379 sb.append(" v").append(pi.versionCode);
8380 if (pi.versionName != null) {
8381 sb.append(" (").append(pi.versionName).append(")");
8382 }
8383 }
8384 } catch (RemoteException e) {
8385 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008386 }
Dan Egnora455d192010-03-12 08:52:28 -08008387 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008388 }
Dan Egnora455d192010-03-12 08:52:28 -08008389 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008390 }
8391
8392 private static String processClass(ProcessRecord process) {
8393 if (process == null || process.pid == MY_PID) {
8394 return "system_server";
8395 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8396 return "system_app";
8397 } else {
8398 return "data_app";
8399 }
8400 }
8401
8402 /**
8403 * Write a description of an error (crash, WTF, ANR) to the drop box.
8404 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8405 * @param process which caused the error, null means the system server
8406 * @param activity which triggered the error, null if unknown
8407 * @param parent activity related to the error, null if unknown
8408 * @param subject line related to the error, null if absent
8409 * @param report in long form describing the error, null if absent
8410 * @param logFile to include in the report, null if none
8411 * @param crashInfo giving an application stack trace, null if absent
8412 */
8413 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008414 ProcessRecord process, String processName, ActivityRecord activity,
8415 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008416 final String report, final File logFile,
8417 final ApplicationErrorReport.CrashInfo crashInfo) {
8418 // NOTE -- this must never acquire the ActivityManagerService lock,
8419 // otherwise the watchdog may be prevented from resetting the system.
8420
8421 final String dropboxTag = processClass(process) + "_" + eventType;
8422 final DropBoxManager dbox = (DropBoxManager)
8423 mContext.getSystemService(Context.DROPBOX_SERVICE);
8424
8425 // Exit early if the dropbox isn't configured to accept this report type.
8426 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8427
8428 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008429 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008430 if (activity != null) {
8431 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8432 }
8433 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8434 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8435 }
8436 if (parent != null && parent != activity) {
8437 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8438 }
8439 if (subject != null) {
8440 sb.append("Subject: ").append(subject).append("\n");
8441 }
8442 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008443 if (Debug.isDebuggerConnected()) {
8444 sb.append("Debugger: Connected\n");
8445 }
Dan Egnora455d192010-03-12 08:52:28 -08008446 sb.append("\n");
8447
8448 // Do the rest in a worker thread to avoid blocking the caller on I/O
8449 // (After this point, we shouldn't access AMS internal data structures.)
8450 Thread worker = new Thread("Error dump: " + dropboxTag) {
8451 @Override
8452 public void run() {
8453 if (report != null) {
8454 sb.append(report);
8455 }
8456 if (logFile != null) {
8457 try {
8458 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8459 } catch (IOException e) {
8460 Slog.e(TAG, "Error reading " + logFile, e);
8461 }
8462 }
8463 if (crashInfo != null && crashInfo.stackTrace != null) {
8464 sb.append(crashInfo.stackTrace);
8465 }
8466
Jeff Sharkey625239a2012-09-26 22:03:49 -07008467 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8468 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008469 if (lines > 0) {
8470 sb.append("\n");
8471
8472 // Merge several logcat streams, and take the last N lines
8473 InputStreamReader input = null;
8474 try {
8475 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8476 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8477 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8478
8479 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8480 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8481 input = new InputStreamReader(logcat.getInputStream());
8482
8483 int num;
8484 char[] buf = new char[8192];
8485 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8486 } catch (IOException e) {
8487 Slog.e(TAG, "Error running logcat", e);
8488 } finally {
8489 if (input != null) try { input.close(); } catch (IOException e) {}
8490 }
8491 }
8492
8493 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008494 }
Dan Egnora455d192010-03-12 08:52:28 -08008495 };
8496
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008497 if (process == null) {
8498 // If process is null, we are being called from some internal code
8499 // and may be about to die -- run this synchronously.
8500 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008501 } else {
8502 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008503 }
8504 }
8505
8506 /**
8507 * Bring up the "unexpected error" dialog box for a crashing app.
8508 * Deal with edge cases (intercepts from instrumented applications,
8509 * ActivityController, error intent receivers, that sort of thing).
8510 * @param r the application crashing
8511 * @param crashInfo describing the failure
8512 */
8513 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008514 long timeMillis = System.currentTimeMillis();
8515 String shortMsg = crashInfo.exceptionClassName;
8516 String longMsg = crashInfo.exceptionMessage;
8517 String stackTrace = crashInfo.stackTrace;
8518 if (shortMsg != null && longMsg != null) {
8519 longMsg = shortMsg + ": " + longMsg;
8520 } else if (shortMsg != null) {
8521 longMsg = shortMsg;
8522 }
8523
Dan Egnor60d87622009-12-16 16:32:58 -08008524 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008526 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008527 try {
8528 String name = r != null ? r.processName : null;
8529 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008530 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008531 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008532 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 + " at watcher's request");
8534 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008535 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 }
8537 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008538 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 }
8540 }
8541
8542 final long origId = Binder.clearCallingIdentity();
8543
8544 // If this process is running instrumentation, finish it.
8545 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008546 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008548 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8549 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 Bundle info = new Bundle();
8551 info.putString("shortMsg", shortMsg);
8552 info.putString("longMsg", longMsg);
8553 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8554 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008555 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 }
8557
Dan Egnor60d87622009-12-16 16:32:58 -08008558 // If we can't identify the process or it's already exceeded its crash quota,
8559 // quit right away without showing a crash dialog.
8560 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008562 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 }
8564
8565 Message msg = Message.obtain();
8566 msg.what = SHOW_ERROR_MSG;
8567 HashMap data = new HashMap();
8568 data.put("result", result);
8569 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 msg.obj = data;
8571 mHandler.sendMessage(msg);
8572
8573 Binder.restoreCallingIdentity(origId);
8574 }
8575
8576 int res = result.get();
8577
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008578 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008580 if (r != null && !r.isolated) {
8581 // XXX Can't keep track of crash time for isolated processes,
8582 // since they don't have a persistent identity.
8583 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 SystemClock.uptimeMillis());
8585 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008586 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008587 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008588 }
8589 }
8590
8591 if (appErrorIntent != null) {
8592 try {
8593 mContext.startActivity(appErrorIntent);
8594 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008595 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008599
8600 Intent createAppErrorIntentLocked(ProcessRecord r,
8601 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8602 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008603 if (report == null) {
8604 return null;
8605 }
8606 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8607 result.setComponent(r.errorReportReceiver);
8608 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8609 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8610 return result;
8611 }
8612
Dan Egnorb7f03672009-12-09 16:22:32 -08008613 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8614 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008615 if (r.errorReportReceiver == null) {
8616 return null;
8617 }
8618
8619 if (!r.crashing && !r.notResponding) {
8620 return null;
8621 }
8622
Dan Egnorb7f03672009-12-09 16:22:32 -08008623 ApplicationErrorReport report = new ApplicationErrorReport();
8624 report.packageName = r.info.packageName;
8625 report.installerPackageName = r.errorReportReceiver.getPackageName();
8626 report.processName = r.processName;
8627 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008628 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008629
Dan Egnorb7f03672009-12-09 16:22:32 -08008630 if (r.crashing) {
8631 report.type = ApplicationErrorReport.TYPE_CRASH;
8632 report.crashInfo = crashInfo;
8633 } else if (r.notResponding) {
8634 report.type = ApplicationErrorReport.TYPE_ANR;
8635 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008636
Dan Egnorb7f03672009-12-09 16:22:32 -08008637 report.anrInfo.activity = r.notRespondingReport.tag;
8638 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8639 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008640 }
8641
Dan Egnorb7f03672009-12-09 16:22:32 -08008642 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008643 }
8644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008646 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008647 // assume our apps are happy - lazy create the list
8648 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8649
Dianne Hackborn0c380492012-08-20 17:23:30 -07008650 final boolean allUsers = ActivityManager.checkUidPermission(
8651 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8652 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8653 int userId = UserHandle.getUserId(Binder.getCallingUid());
8654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 synchronized (this) {
8656
8657 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008658 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8659 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008660 if (!allUsers && app.userId != userId) {
8661 continue;
8662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8664 // This one's in trouble, so we'll generate a report for it
8665 // crashes are higher priority (in case there's a crash *and* an anr)
8666 ActivityManager.ProcessErrorStateInfo report = null;
8667 if (app.crashing) {
8668 report = app.crashingReport;
8669 } else if (app.notResponding) {
8670 report = app.notRespondingReport;
8671 }
8672
8673 if (report != null) {
8674 if (errList == null) {
8675 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8676 }
8677 errList.add(report);
8678 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008679 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 " crashing = " + app.crashing +
8681 " notResponding = " + app.notResponding);
8682 }
8683 }
8684 }
8685 }
8686
8687 return errList;
8688 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008689
8690 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008691 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008692 if (currApp != null) {
8693 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8694 }
8695 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008696 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8697 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008698 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8699 if (currApp != null) {
8700 currApp.lru = 0;
8701 }
8702 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008703 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008704 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8705 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8706 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8707 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8708 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8709 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8710 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8711 } else {
8712 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8713 }
8714 }
8715
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008716 private void fillInProcMemInfo(ProcessRecord app,
8717 ActivityManager.RunningAppProcessInfo outInfo) {
8718 outInfo.pid = app.pid;
8719 outInfo.uid = app.info.uid;
8720 if (mHeavyWeightProcess == app) {
8721 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8722 }
8723 if (app.persistent) {
8724 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8725 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008726 if (app.hasActivities) {
8727 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8728 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008729 outInfo.lastTrimLevel = app.trimMemoryLevel;
8730 int adj = app.curAdj;
8731 outInfo.importance = oomAdjToImportance(adj, outInfo);
8732 outInfo.importanceReasonCode = app.adjTypeCode;
8733 }
8734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008736 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 // Lazy instantiation of list
8738 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008739 final boolean allUsers = ActivityManager.checkUidPermission(
8740 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8741 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8742 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008743 synchronized (this) {
8744 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008745 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8746 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008747 if (!allUsers && app.userId != userId) {
8748 continue;
8749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8751 // Generate process state info for running application
8752 ActivityManager.RunningAppProcessInfo currApp =
8753 new ActivityManager.RunningAppProcessInfo(app.processName,
8754 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008755 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008756 if (app.adjSource instanceof ProcessRecord) {
8757 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008758 currApp.importanceReasonImportance = oomAdjToImportance(
8759 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008760 } else if (app.adjSource instanceof ActivityRecord) {
8761 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008762 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8763 }
8764 if (app.adjTarget instanceof ComponentName) {
8765 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8766 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008767 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 // + " lru=" + currApp.lru);
8769 if (runList == null) {
8770 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8771 }
8772 runList.add(currApp);
8773 }
8774 }
8775 }
8776 return runList;
8777 }
8778
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008779 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008780 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008781 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8782 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8783 if (runningApps != null && runningApps.size() > 0) {
8784 Set<String> extList = new HashSet<String>();
8785 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8786 if (app.pkgList != null) {
8787 for (String pkg : app.pkgList) {
8788 extList.add(pkg);
8789 }
8790 }
8791 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008792 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008793 for (String pkg : extList) {
8794 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008795 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008796 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8797 retList.add(info);
8798 }
8799 } catch (RemoteException e) {
8800 }
8801 }
8802 }
8803 return retList;
8804 }
8805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008807 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8808 enforceNotIsolatedCaller("getMyMemoryState");
8809 synchronized (this) {
8810 ProcessRecord proc;
8811 synchronized (mPidsSelfLocked) {
8812 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8813 }
8814 fillInProcMemInfo(proc, outInfo);
8815 }
8816 }
8817
8818 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008819 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008820 if (checkCallingPermission(android.Manifest.permission.DUMP)
8821 != PackageManager.PERMISSION_GRANTED) {
8822 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8823 + Binder.getCallingPid()
8824 + ", uid=" + Binder.getCallingUid()
8825 + " without permission "
8826 + android.Manifest.permission.DUMP);
8827 return;
8828 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008829
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008830 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008831 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008832 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008833
8834 int opti = 0;
8835 while (opti < args.length) {
8836 String opt = args[opti];
8837 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8838 break;
8839 }
8840 opti++;
8841 if ("-a".equals(opt)) {
8842 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008843 } else if ("-c".equals(opt)) {
8844 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 } else if ("-h".equals(opt)) {
8846 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008847 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008849 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008850 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8851 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8852 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008853 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008854 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008855 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008856 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008857 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008858 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008859 pw.println(" all: dump all activities");
8860 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008861 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008862 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8863 pw.println(" a partial substring in a component name, a");
8864 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008865 pw.println(" -a: include all available server state.");
8866 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008868 } else {
8869 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008871 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008872
8873 long origId = Binder.clearCallingIdentity();
8874 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008875 // Is the caller requesting to dump a particular piece of data?
8876 if (opti < args.length) {
8877 String cmd = args[opti];
8878 opti++;
8879 if ("activities".equals(cmd) || "a".equals(cmd)) {
8880 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008881 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008883 } else if ("broadcasts".equals(cmd) || "b".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 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008899 } else if ("intents".equals(cmd) || "i".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 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008914 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008915 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008916 String[] newArgs;
8917 String name;
8918 if (opti >= args.length) {
8919 name = null;
8920 newArgs = EMPTY_STRING_ARRAY;
8921 } else {
8922 name = args[opti];
8923 opti++;
8924 newArgs = new String[args.length - opti];
8925 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8926 args.length - opti);
8927 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008928 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008929 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008930 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008931 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8932 synchronized (this) {
8933 dumpOomLocked(fd, pw, args, opti, true);
8934 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008935 } else if ("provider".equals(cmd)) {
8936 String[] newArgs;
8937 String name;
8938 if (opti >= args.length) {
8939 name = null;
8940 newArgs = EMPTY_STRING_ARRAY;
8941 } else {
8942 name = args[opti];
8943 opti++;
8944 newArgs = new String[args.length - opti];
8945 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8946 }
8947 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8948 pw.println("No providers match: " + name);
8949 pw.println("Use -h for help.");
8950 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008951 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8952 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008953 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008954 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008955 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008956 String[] newArgs;
8957 String name;
8958 if (opti >= args.length) {
8959 name = null;
8960 newArgs = EMPTY_STRING_ARRAY;
8961 } else {
8962 name = args[opti];
8963 opti++;
8964 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008965 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8966 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008967 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008968 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008969 pw.println("No services match: " + name);
8970 pw.println("Use -h for help.");
8971 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008972 } else if ("package".equals(cmd)) {
8973 String[] newArgs;
8974 if (opti >= args.length) {
8975 pw.println("package: no package name specified");
8976 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008977 } else {
8978 dumpPackage = args[opti];
8979 opti++;
8980 newArgs = new String[args.length - opti];
8981 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8982 args.length - opti);
8983 args = newArgs;
8984 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008985 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008986 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008987 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8988 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008989 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008991 } else {
8992 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008993 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8994 pw.println("Bad activity command, or no activities match: " + cmd);
8995 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008996 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008997 }
8998 if (!more) {
8999 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009000 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009002 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009003
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009004 // No piece of data specified, dump everything.
9005 synchronized (this) {
9006 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009007 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009008 if (needSep) {
9009 pw.println(" ");
9010 }
9011 if (dumpAll) {
9012 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009014 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 if (needSep) {
9016 pw.println(" ");
9017 }
9018 if (dumpAll) {
9019 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009021 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022 if (needSep) {
9023 pw.println(" ");
9024 }
9025 if (dumpAll) {
9026 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009027 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009028 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009029 if (needSep) {
9030 pw.println(" ");
9031 }
9032 if (dumpAll) {
9033 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009034 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009036 if (needSep) {
9037 pw.println(" ");
9038 }
9039 if (dumpAll) {
9040 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009041 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009042 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009044 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009045 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009046
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009047 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009048 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009049 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9050 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9052 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009053 pw.println(" ");
9054 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009055 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9056 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009057 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009060 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009061 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009063 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009064 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009065 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009066 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009067 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009069 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9070 pw.println(" ");
9071 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009072 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009073 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009074 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009075 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009076 pw.println(" ");
9077 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009078 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009079 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009082 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009083 if (mMainStack.mPausingActivity != null) {
9084 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009085 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009086 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009087 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009088 if (dumpAll) {
9089 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9090 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009091 pw.println(" mDismissKeyguardOnNextActivity: "
9092 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009095 if (mRecentTasks.size() > 0) {
9096 pw.println();
9097 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009098
9099 final int N = mRecentTasks.size();
9100 for (int i=0; i<N; i++) {
9101 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009102 if (dumpPackage != null) {
9103 if (tr.realActivity == null ||
9104 !dumpPackage.equals(tr.realActivity)) {
9105 continue;
9106 }
9107 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009108 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9109 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009110 if (dumpAll) {
9111 mRecentTasks.get(i).dump(pw, " ");
9112 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009113 }
9114 }
9115
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009116 if (dumpAll) {
9117 pw.println(" ");
9118 pw.println(" mCurTask: " + mCurTask);
9119 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009120
9121 return true;
9122 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009123
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009124 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009125 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009126 boolean needSep = false;
9127 int numPers = 0;
9128
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009129 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9130
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009131 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9133 final int NA = procs.size();
9134 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009135 ProcessRecord r = procs.valueAt(ia);
9136 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9137 continue;
9138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009139 if (!needSep) {
9140 pw.println(" All known processes:");
9141 needSep = true;
9142 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009143 pw.print(r.persistent ? " *PERS*" : " *APP*");
9144 pw.print(" UID "); pw.print(procs.keyAt(ia));
9145 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 r.dump(pw, " ");
9147 if (r.persistent) {
9148 numPers++;
9149 }
9150 }
9151 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009152 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009153
9154 if (mIsolatedProcesses.size() > 0) {
9155 if (needSep) pw.println(" ");
9156 needSep = true;
9157 pw.println(" Isolated process list (sorted by uid):");
9158 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9159 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9160 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9161 continue;
9162 }
9163 pw.println(String.format("%sIsolated #%2d: %s",
9164 " ", i, r.toString()));
9165 }
9166 }
9167
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009168 if (mLruProcesses.size() > 0) {
9169 if (needSep) pw.println(" ");
9170 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009171 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009172 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009173 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009174 needSep = true;
9175 }
9176
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009177 if (dumpAll) {
9178 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009179 boolean printed = false;
9180 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9181 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9182 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9183 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009184 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009185 if (!printed) {
9186 if (needSep) pw.println(" ");
9187 needSep = true;
9188 pw.println(" PID mappings:");
9189 printed = true;
9190 }
9191 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9192 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 }
9194 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009195 }
9196
9197 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009198 synchronized (mPidsSelfLocked) {
9199 boolean printed = false;
9200 for (int i=0; i<mForegroundProcesses.size(); i++) {
9201 ProcessRecord r = mPidsSelfLocked.get(
9202 mForegroundProcesses.valueAt(i).pid);
9203 if (dumpPackage != null && (r == null
9204 || !dumpPackage.equals(r.info.packageName))) {
9205 continue;
9206 }
9207 if (!printed) {
9208 if (needSep) pw.println(" ");
9209 needSep = true;
9210 pw.println(" Foreground Processes:");
9211 printed = true;
9212 }
9213 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9214 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009217 }
9218
9219 if (mPersistentStartingProcesses.size() > 0) {
9220 if (needSep) pw.println(" ");
9221 needSep = true;
9222 pw.println(" Persisent processes that are starting:");
9223 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009224 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009226
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009227 if (mRemovedProcesses.size() > 0) {
9228 if (needSep) pw.println(" ");
9229 needSep = true;
9230 pw.println(" Processes that are being removed:");
9231 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009232 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009233 }
9234
9235 if (mProcessesOnHold.size() > 0) {
9236 if (needSep) pw.println(" ");
9237 needSep = true;
9238 pw.println(" Processes that are on old until the system is ready:");
9239 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009240 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009243 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009244
9245 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009246 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009247 long now = SystemClock.uptimeMillis();
9248 for (Map.Entry<String, SparseArray<Long>> procs
9249 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009250 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009251 SparseArray<Long> uids = procs.getValue();
9252 final int N = uids.size();
9253 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009254 int puid = uids.keyAt(i);
9255 ProcessRecord r = mProcessNames.get(pname, puid);
9256 if (dumpPackage != null && (r == null
9257 || !dumpPackage.equals(r.info.packageName))) {
9258 continue;
9259 }
9260 if (!printed) {
9261 if (needSep) pw.println(" ");
9262 needSep = true;
9263 pw.println(" Time since processes crashed:");
9264 printed = true;
9265 }
9266 pw.print(" Process "); pw.print(pname);
9267 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009268 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009269 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9270 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009271 }
9272 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009274
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009275 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009276 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009277 for (Map.Entry<String, SparseArray<Long>> procs
9278 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009279 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009280 SparseArray<Long> uids = procs.getValue();
9281 final int N = uids.size();
9282 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009283 int puid = uids.keyAt(i);
9284 ProcessRecord r = mProcessNames.get(pname, puid);
9285 if (dumpPackage != null && (r == null
9286 || !dumpPackage.equals(r.info.packageName))) {
9287 continue;
9288 }
9289 if (!printed) {
9290 if (needSep) pw.println(" ");
9291 needSep = true;
9292 pw.println(" Bad processes:");
9293 }
9294 pw.print(" Bad process "); pw.print(pname);
9295 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009296 pw.print(": crashed at time ");
9297 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009298 }
9299 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009302 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009303 pw.println(" mStartedUsers:");
9304 for (int i=0; i<mStartedUsers.size(); i++) {
9305 UserStartedState uss = mStartedUsers.valueAt(i);
9306 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009307 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009308 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009309 pw.print(" mUserLru: [");
9310 for (int i=0; i<mUserLru.size(); i++) {
9311 if (i > 0) pw.print(", ");
9312 pw.print(mUserLru.get(i));
9313 }
9314 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009315 if (dumpAll) {
9316 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9317 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009318 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009319 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009320 if (dumpAll) {
9321 StringBuilder sb = new StringBuilder(128);
9322 sb.append(" mPreviousProcessVisibleTime: ");
9323 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9324 pw.println(sb);
9325 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009326 if (mHeavyWeightProcess != null) {
9327 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9328 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009329 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009330 if (dumpAll) {
9331 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009332 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009333 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009334 for (Map.Entry<String, Integer> entry
9335 : mCompatModePackages.getPackages().entrySet()) {
9336 String pkg = entry.getKey();
9337 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009338 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9339 continue;
9340 }
9341 if (!printed) {
9342 pw.println(" mScreenCompatPackages:");
9343 printed = true;
9344 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009345 pw.print(" "); pw.print(pkg); pw.print(": ");
9346 pw.print(mode); pw.println();
9347 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009348 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009349 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009350 if (mSleeping || mWentToSleep || mLockScreenShown) {
9351 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9352 + " mLockScreenShown " + mLockScreenShown);
9353 }
9354 if (mShuttingDown) {
9355 pw.println(" mShuttingDown=" + mShuttingDown);
9356 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9358 || mOrigWaitForDebugger) {
9359 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9360 + " mDebugTransient=" + mDebugTransient
9361 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9362 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009363 if (mOpenGlTraceApp != null) {
9364 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9365 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009366 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9367 || mProfileFd != null) {
9368 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9369 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9370 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9371 + mAutoStopProfiler);
9372 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009373 if (mAlwaysFinishActivities || mController != null) {
9374 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9375 + " mController=" + mController);
9376 }
9377 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009380 + " mProcessesReady=" + mProcessesReady
9381 + " mSystemReady=" + mSystemReady);
9382 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 + " mBooted=" + mBooted
9384 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009385 pw.print(" mLastPowerCheckRealtime=");
9386 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9387 pw.println("");
9388 pw.print(" mLastPowerCheckUptime=");
9389 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9390 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009391 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9392 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009393 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009394 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9395 + " mNumHiddenProcs=" + mNumHiddenProcs
9396 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009397 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009399
9400 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
9402
Dianne Hackborn287952c2010-09-22 22:34:31 -07009403 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009404 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009405 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009406 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009407 long now = SystemClock.uptimeMillis();
9408 for (int i=0; i<mProcessesToGc.size(); i++) {
9409 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009410 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9411 continue;
9412 }
9413 if (!printed) {
9414 if (needSep) pw.println(" ");
9415 needSep = true;
9416 pw.println(" Processes that are waiting to GC:");
9417 printed = true;
9418 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009419 pw.print(" Process "); pw.println(proc);
9420 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9421 pw.print(", last gced=");
9422 pw.print(now-proc.lastRequestedGc);
9423 pw.print(" ms ago, last lowMem=");
9424 pw.print(now-proc.lastLowMemory);
9425 pw.println(" ms ago");
9426
9427 }
9428 }
9429 return needSep;
9430 }
9431
9432 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9433 int opti, boolean dumpAll) {
9434 boolean needSep = false;
9435
9436 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009437 if (needSep) pw.println(" ");
9438 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009439 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009440 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009441 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009442 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9443 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9444 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9445 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9446 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009447 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009448 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009449 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009450 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009451 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009452 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009453
9454 if (needSep) pw.println(" ");
9455 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009456 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009457 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009458 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009459 needSep = true;
9460 }
9461
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009462 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009463
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009464 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009465 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009466 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009467 if (mHeavyWeightProcess != null) {
9468 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9469 }
9470
9471 return true;
9472 }
9473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009474 /**
9475 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009476 * - no provider specified: dump all the providers
9477 * - a flattened component name that matched an existing provider was specified as the
9478 * first arg: dump that one provider
9479 * - the first arg isn't the flattened component name of an existing provider:
9480 * dump all providers whose component contains the first arg as a substring
9481 */
9482 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9483 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009484 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009485 }
9486
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009487 static class ItemMatcher {
9488 ArrayList<ComponentName> components;
9489 ArrayList<String> strings;
9490 ArrayList<Integer> objects;
9491 boolean all;
9492
9493 ItemMatcher() {
9494 all = true;
9495 }
9496
9497 void build(String name) {
9498 ComponentName componentName = ComponentName.unflattenFromString(name);
9499 if (componentName != null) {
9500 if (components == null) {
9501 components = new ArrayList<ComponentName>();
9502 }
9503 components.add(componentName);
9504 all = false;
9505 } else {
9506 int objectId = 0;
9507 // Not a '/' separated full component name; maybe an object ID?
9508 try {
9509 objectId = Integer.parseInt(name, 16);
9510 if (objects == null) {
9511 objects = new ArrayList<Integer>();
9512 }
9513 objects.add(objectId);
9514 all = false;
9515 } catch (RuntimeException e) {
9516 // Not an integer; just do string match.
9517 if (strings == null) {
9518 strings = new ArrayList<String>();
9519 }
9520 strings.add(name);
9521 all = false;
9522 }
9523 }
9524 }
9525
9526 int build(String[] args, int opti) {
9527 for (; opti<args.length; opti++) {
9528 String name = args[opti];
9529 if ("--".equals(name)) {
9530 return opti+1;
9531 }
9532 build(name);
9533 }
9534 return opti;
9535 }
9536
9537 boolean match(Object object, ComponentName comp) {
9538 if (all) {
9539 return true;
9540 }
9541 if (components != null) {
9542 for (int i=0; i<components.size(); i++) {
9543 if (components.get(i).equals(comp)) {
9544 return true;
9545 }
9546 }
9547 }
9548 if (objects != null) {
9549 for (int i=0; i<objects.size(); i++) {
9550 if (System.identityHashCode(object) == objects.get(i)) {
9551 return true;
9552 }
9553 }
9554 }
9555 if (strings != null) {
9556 String flat = comp.flattenToString();
9557 for (int i=0; i<strings.size(); i++) {
9558 if (flat.contains(strings.get(i))) {
9559 return true;
9560 }
9561 }
9562 }
9563 return false;
9564 }
9565 }
9566
Dianne Hackborn625ac272010-09-17 18:29:22 -07009567 /**
9568 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009569 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009570 * - the cmd arg isn't the flattened component name of an existing activity:
9571 * dump all activity whose component contains the cmd as a substring
9572 * - A hex number of the ActivityRecord object instance.
9573 */
9574 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9575 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009576 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009577
9578 if ("all".equals(name)) {
9579 synchronized (this) {
9580 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009581 activities.add(r1);
9582 }
9583 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009584 } else if ("top".equals(name)) {
9585 synchronized (this) {
9586 final int N = mMainStack.mHistory.size();
9587 if (N > 0) {
9588 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9589 }
9590 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009591 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009592 ItemMatcher matcher = new ItemMatcher();
9593 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009594
9595 synchronized (this) {
9596 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009597 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009598 activities.add(r1);
9599 }
9600 }
9601 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009602 }
9603
9604 if (activities.size() <= 0) {
9605 return false;
9606 }
9607
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009608 String[] newArgs = new String[args.length - opti];
9609 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9610
Dianne Hackborn30d71892010-12-11 10:37:55 -08009611 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009612 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009613 for (int i=activities.size()-1; i>=0; i--) {
9614 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009615 if (needSep) {
9616 pw.println();
9617 }
9618 needSep = true;
9619 synchronized (this) {
9620 if (lastTask != r.task) {
9621 lastTask = r.task;
9622 pw.print("TASK "); pw.print(lastTask.affinity);
9623 pw.print(" id="); pw.println(lastTask.taskId);
9624 if (dumpAll) {
9625 lastTask.dump(pw, " ");
9626 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009627 }
9628 }
9629 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009630 }
9631 return true;
9632 }
9633
9634 /**
9635 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9636 * there is a thread associated with the activity.
9637 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009638 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009639 final ActivityRecord r, String[] args, boolean dumpAll) {
9640 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009641 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009642 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9643 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9644 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009645 if (r.app != null) pw.println(r.app.pid);
9646 else pw.println("(not running)");
9647 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009648 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009649 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009650 }
9651 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009652 // flush anything that is already in the PrintWriter since the thread is going
9653 // to write to the file descriptor directly
9654 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009655 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009656 TransferPipe tp = new TransferPipe();
9657 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009658 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9659 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009660 tp.go(fd);
9661 } finally {
9662 tp.kill();
9663 }
9664 } catch (IOException e) {
9665 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009666 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009667 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009668 }
9669 }
9670 }
9671
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009672 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009673 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009674 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009675 boolean onlyHistory = false;
9676
9677 if ("history".equals(dumpPackage)) {
9678 onlyHistory = true;
9679 dumpPackage = null;
9680 }
9681
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009682 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009683 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009684 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009686 Iterator it = mRegisteredReceivers.values().iterator();
9687 while (it.hasNext()) {
9688 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009689 if (dumpPackage != null && (r.app == null ||
9690 !dumpPackage.equals(r.app.info.packageName))) {
9691 continue;
9692 }
9693 if (!printed) {
9694 pw.println(" Registered Receivers:");
9695 needSep = true;
9696 printed = true;
9697 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009698 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 r.dump(pw, " ");
9700 }
9701 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009702
9703 if (mReceiverResolver.dump(pw, needSep ?
9704 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9705 " ", dumpPackage, false)) {
9706 needSep = true;
9707 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009708 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009709
9710 for (BroadcastQueue q : mBroadcastQueues) {
9711 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009713
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009714 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009715
Dianne Hackborn786b4402012-08-27 15:14:02 -07009716 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009717 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9718 if (needSep) {
9719 pw.println();
9720 }
9721 needSep = true;
9722 pw.print(" Sticky broadcasts for user ");
9723 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9724 StringBuilder sb = new StringBuilder(128);
9725 for (Map.Entry<String, ArrayList<Intent>> ent
9726 : mStickyBroadcasts.valueAt(user).entrySet()) {
9727 pw.print(" * Sticky action "); pw.print(ent.getKey());
9728 if (dumpAll) {
9729 pw.println(":");
9730 ArrayList<Intent> intents = ent.getValue();
9731 final int N = intents.size();
9732 for (int i=0; i<N; i++) {
9733 sb.setLength(0);
9734 sb.append(" Intent: ");
9735 intents.get(i).toShortString(sb, false, true, false, false);
9736 pw.println(sb.toString());
9737 Bundle bundle = intents.get(i).getExtras();
9738 if (bundle != null) {
9739 pw.print(" ");
9740 pw.println(bundle.toString());
9741 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009742 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009743 } else {
9744 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009745 }
9746 }
9747 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009748 }
9749
Dianne Hackborn786b4402012-08-27 15:14:02 -07009750 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009751 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009752 for (BroadcastQueue queue : mBroadcastQueues) {
9753 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9754 + queue.mBroadcastsScheduled);
9755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 pw.println(" mHandler:");
9757 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009758 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009759 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009760
9761 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009762 }
9763
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009764 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009765 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009766 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009767
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009768 ItemMatcher matcher = new ItemMatcher();
9769 matcher.build(args, opti);
9770
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009771 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009772
9773 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009774
9775 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009776 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009777 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009778 ContentProviderRecord r = mLaunchingProviders.get(i);
9779 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9780 continue;
9781 }
9782 if (!printed) {
9783 if (needSep) pw.println(" ");
9784 needSep = true;
9785 pw.println(" Launching content providers:");
9786 printed = true;
9787 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009788 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009789 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009790 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009791 }
9792
9793 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009794 if (needSep) pw.println();
9795 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009796 pw.println("Granted Uri Permissions:");
9797 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9798 int uid = mGrantedUriPermissions.keyAt(i);
9799 HashMap<Uri, UriPermission> perms
9800 = mGrantedUriPermissions.valueAt(i);
9801 pw.print(" * UID "); pw.print(uid);
9802 pw.println(" holds:");
9803 for (UriPermission perm : perms.values()) {
9804 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009805 if (dumpAll) {
9806 perm.dump(pw, " ");
9807 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009808 }
9809 }
9810 needSep = true;
9811 }
9812
9813 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009814 }
9815
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009816 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009817 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009818 boolean needSep = false;
9819
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009820 if (mIntentSenderRecords.size() > 0) {
9821 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009822 Iterator<WeakReference<PendingIntentRecord>> it
9823 = mIntentSenderRecords.values().iterator();
9824 while (it.hasNext()) {
9825 WeakReference<PendingIntentRecord> ref = it.next();
9826 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009827 if (dumpPackage != null && (rec == null
9828 || !dumpPackage.equals(rec.key.packageName))) {
9829 continue;
9830 }
9831 if (!printed) {
9832 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9833 printed = true;
9834 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009835 needSep = true;
9836 if (rec != null) {
9837 pw.print(" * "); pw.println(rec);
9838 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009839 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009840 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009841 } else {
9842 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009843 }
9844 }
9845 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009846
9847 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009848 }
9849
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009850 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009851 String prefix, String label, boolean complete, boolean brief, boolean client,
9852 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009853 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009854 boolean needNL = false;
9855 final String innerPrefix = prefix + " ";
9856 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009857 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009858 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009859 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9860 continue;
9861 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009862 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009863 if (needNL) {
9864 pw.println(" ");
9865 needNL = false;
9866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009867 if (lastTask != r.task) {
9868 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009869 pw.print(prefix);
9870 pw.print(full ? "* " : " ");
9871 pw.println(lastTask);
9872 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009873 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009874 } else if (complete) {
9875 // Complete + brief == give a summary. Isn't that obvious?!?
9876 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009877 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009878 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009879 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009881 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009882 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9883 pw.print(" #"); pw.print(i); pw.print(": ");
9884 pw.println(r);
9885 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009886 r.dump(pw, innerPrefix);
9887 } else if (complete) {
9888 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009889 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009890 if (r.app != null) {
9891 pw.print(innerPrefix); pw.println(r.app);
9892 }
9893 }
9894 if (client && r.app != null && r.app.thread != null) {
9895 // flush anything that is already in the PrintWriter since the thread is going
9896 // to write to the file descriptor directly
9897 pw.flush();
9898 try {
9899 TransferPipe tp = new TransferPipe();
9900 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009901 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9902 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009903 // Short timeout, since blocking here can
9904 // deadlock with the application.
9905 tp.go(fd, 2000);
9906 } finally {
9907 tp.kill();
9908 }
9909 } catch (IOException e) {
9910 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9911 } catch (RemoteException e) {
9912 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9913 }
9914 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009916 }
9917 }
9918
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009919 private static String buildOomTag(String prefix, String space, int val, int base) {
9920 if (val == base) {
9921 if (space == null) return prefix;
9922 return prefix + " ";
9923 }
9924 return prefix + "+" + Integer.toString(val-base);
9925 }
9926
9927 private static final int dumpProcessList(PrintWriter pw,
9928 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009929 String prefix, String normalLabel, String persistentLabel,
9930 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009931 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009932 final int N = list.size()-1;
9933 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009934 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009935 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9936 continue;
9937 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009938 pw.println(String.format("%s%s #%2d: %s",
9939 prefix, (r.persistent ? persistentLabel : normalLabel),
9940 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009941 if (r.persistent) {
9942 numPers++;
9943 }
9944 }
9945 return numPers;
9946 }
9947
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009948 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009949 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009950 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009951 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009952
Dianne Hackborn905577f2011-09-07 18:31:28 -07009953 ArrayList<Pair<ProcessRecord, Integer>> list
9954 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9955 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009956 ProcessRecord r = origList.get(i);
9957 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9958 continue;
9959 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009960 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9961 }
9962
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009963 if (list.size() <= 0) {
9964 return false;
9965 }
9966
Dianne Hackborn905577f2011-09-07 18:31:28 -07009967 Comparator<Pair<ProcessRecord, Integer>> comparator
9968 = new Comparator<Pair<ProcessRecord, Integer>>() {
9969 @Override
9970 public int compare(Pair<ProcessRecord, Integer> object1,
9971 Pair<ProcessRecord, Integer> object2) {
9972 if (object1.first.setAdj != object2.first.setAdj) {
9973 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9974 }
9975 if (object1.second.intValue() != object2.second.intValue()) {
9976 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9977 }
9978 return 0;
9979 }
9980 };
9981
9982 Collections.sort(list, comparator);
9983
Dianne Hackborn287952c2010-09-22 22:34:31 -07009984 final long curRealtime = SystemClock.elapsedRealtime();
9985 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9986 final long curUptime = SystemClock.uptimeMillis();
9987 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9988
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009989 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009990 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009991 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009992 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009993 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009994 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9995 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009996 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9997 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009998 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9999 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010000 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10001 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010002 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010003 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010004 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10005 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10006 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10007 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10008 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10009 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10010 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10011 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010012 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10013 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010014 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10015 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010016 } else {
10017 oomAdj = Integer.toString(r.setAdj);
10018 }
10019 String schedGroup;
10020 switch (r.setSchedGroup) {
10021 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10022 schedGroup = "B";
10023 break;
10024 case Process.THREAD_GROUP_DEFAULT:
10025 schedGroup = "F";
10026 break;
10027 default:
10028 schedGroup = Integer.toString(r.setSchedGroup);
10029 break;
10030 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010031 String foreground;
10032 if (r.foregroundActivities) {
10033 foreground = "A";
10034 } else if (r.foregroundServices) {
10035 foreground = "S";
10036 } else {
10037 foreground = " ";
10038 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010039 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010040 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010041 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10042 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010043 if (r.adjSource != null || r.adjTarget != null) {
10044 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010045 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010046 if (r.adjTarget instanceof ComponentName) {
10047 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10048 } else if (r.adjTarget != null) {
10049 pw.print(r.adjTarget.toString());
10050 } else {
10051 pw.print("{null}");
10052 }
10053 pw.print("<=");
10054 if (r.adjSource instanceof ProcessRecord) {
10055 pw.print("Proc{");
10056 pw.print(((ProcessRecord)r.adjSource).toShortString());
10057 pw.println("}");
10058 } else if (r.adjSource != null) {
10059 pw.println(r.adjSource.toString());
10060 } else {
10061 pw.println("{null}");
10062 }
10063 }
10064 if (inclDetails) {
10065 pw.print(prefix);
10066 pw.print(" ");
10067 pw.print("oom: max="); pw.print(r.maxAdj);
10068 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010069 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010070 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010071 pw.print(" curRaw="); pw.print(r.curRawAdj);
10072 pw.print(" setRaw="); pw.print(r.setRawAdj);
10073 pw.print(" cur="); pw.print(r.curAdj);
10074 pw.print(" set="); pw.println(r.setAdj);
10075 pw.print(prefix);
10076 pw.print(" ");
10077 pw.print("keeping="); pw.print(r.keeping);
10078 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010079 pw.print(" empty="); pw.print(r.empty);
10080 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010081
10082 if (!r.keeping) {
10083 if (r.lastWakeTime != 0) {
10084 long wtime;
10085 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10086 synchronized (stats) {
10087 wtime = stats.getProcessWakeTime(r.info.uid,
10088 r.pid, curRealtime);
10089 }
10090 long timeUsed = wtime - r.lastWakeTime;
10091 pw.print(prefix);
10092 pw.print(" ");
10093 pw.print("keep awake over ");
10094 TimeUtils.formatDuration(realtimeSince, pw);
10095 pw.print(" used ");
10096 TimeUtils.formatDuration(timeUsed, pw);
10097 pw.print(" (");
10098 pw.print((timeUsed*100)/realtimeSince);
10099 pw.println("%)");
10100 }
10101 if (r.lastCpuTime != 0) {
10102 long timeUsed = r.curCpuTime - r.lastCpuTime;
10103 pw.print(prefix);
10104 pw.print(" ");
10105 pw.print("run cpu over ");
10106 TimeUtils.formatDuration(uptimeSince, pw);
10107 pw.print(" used ");
10108 TimeUtils.formatDuration(timeUsed, pw);
10109 pw.print(" (");
10110 pw.print((timeUsed*100)/uptimeSince);
10111 pw.println("%)");
10112 }
10113 }
10114 }
10115 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010116 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010117 }
10118
Dianne Hackbornb437e092011-08-05 17:50:29 -070010119 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010120 ArrayList<ProcessRecord> procs;
10121 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010122 if (args != null && args.length > start
10123 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010124 procs = new ArrayList<ProcessRecord>();
10125 int pid = -1;
10126 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010127 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010128 } catch (NumberFormatException e) {
10129
10130 }
10131 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10132 ProcessRecord proc = mLruProcesses.get(i);
10133 if (proc.pid == pid) {
10134 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010135 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010136 procs.add(proc);
10137 }
10138 }
10139 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010140 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010141 return null;
10142 }
10143 } else {
10144 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10145 }
10146 }
10147 return procs;
10148 }
10149
10150 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10151 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010152 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010153 if (procs == null) {
10154 return;
10155 }
10156
10157 long uptime = SystemClock.uptimeMillis();
10158 long realtime = SystemClock.elapsedRealtime();
10159 pw.println("Applications Graphics Acceleration Info:");
10160 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10161
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010162 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10163 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010164 if (r.thread != null) {
10165 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10166 pw.flush();
10167 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010168 TransferPipe tp = new TransferPipe();
10169 try {
10170 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10171 tp.go(fd);
10172 } finally {
10173 tp.kill();
10174 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010175 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010176 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010177 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010178 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010179 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010180 pw.flush();
10181 }
10182 }
10183 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010184 }
10185
Jeff Brown6754ba22011-12-14 20:20:01 -080010186 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10187 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10188 if (procs == null) {
10189 return;
10190 }
10191
10192 pw.println("Applications Database Info:");
10193
10194 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10195 ProcessRecord r = procs.get(i);
10196 if (r.thread != null) {
10197 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10198 pw.flush();
10199 try {
10200 TransferPipe tp = new TransferPipe();
10201 try {
10202 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10203 tp.go(fd);
10204 } finally {
10205 tp.kill();
10206 }
10207 } catch (IOException e) {
10208 pw.println("Failure while dumping the app: " + r);
10209 pw.flush();
10210 } catch (RemoteException e) {
10211 pw.println("Got a RemoteException while dumping the app " + r);
10212 pw.flush();
10213 }
10214 }
10215 }
10216 }
10217
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010218 final static class MemItem {
10219 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010220 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010221 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010222 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010223 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010224
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010225 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010226 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010227 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010228 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010229 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010230 }
10231 }
10232
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010233 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010234 boolean sort) {
10235 if (sort) {
10236 Collections.sort(items, new Comparator<MemItem>() {
10237 @Override
10238 public int compare(MemItem lhs, MemItem rhs) {
10239 if (lhs.pss < rhs.pss) {
10240 return 1;
10241 } else if (lhs.pss > rhs.pss) {
10242 return -1;
10243 }
10244 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010245 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010246 });
10247 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010248
10249 for (int i=0; i<items.size(); i++) {
10250 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010251 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010252 if (mi.subitems != null) {
10253 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10254 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010255 }
10256 }
10257
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010258 // These are in KB.
10259 static final long[] DUMP_MEM_BUCKETS = new long[] {
10260 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10261 120*1024, 160*1024, 200*1024,
10262 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10263 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10264 };
10265
Dianne Hackborn672342c2011-11-29 11:29:02 -080010266 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10267 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010268 int start = label.lastIndexOf('.');
10269 if (start >= 0) start++;
10270 else start = 0;
10271 int end = label.length();
10272 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10273 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10274 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10275 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010276 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010277 out.append(label, start, end);
10278 return;
10279 }
10280 }
10281 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010282 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010283 out.append(label, start, end);
10284 }
10285
10286 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10287 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10288 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10289 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10290 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10291 };
10292 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10293 "System", "Persistent", "Foreground",
10294 "Visible", "Perceptible", "Heavy Weight",
10295 "Backup", "A Services", "Home", "Previous",
10296 "B Services", "Background"
10297 };
10298
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010299 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010300 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010301 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010302 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010303 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010304
10305 int opti = 0;
10306 while (opti < args.length) {
10307 String opt = args[opti];
10308 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10309 break;
10310 }
10311 opti++;
10312 if ("-a".equals(opt)) {
10313 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010314 } else if ("--oom".equals(opt)) {
10315 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010316 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010317 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010318 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010319 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320 pw.println("If [process] is specified it can be the name or ");
10321 pw.println("pid of a specific process to dump.");
10322 return;
10323 } else {
10324 pw.println("Unknown argument: " + opt + "; use -h for help");
10325 }
10326 }
10327
10328 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010329 if (procs == null) {
10330 return;
10331 }
10332
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010333 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010334 long uptime = SystemClock.uptimeMillis();
10335 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010336
10337 if (procs.size() == 1 || isCheckinRequest) {
10338 dumpAll = true;
10339 }
10340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010341 if (isCheckinRequest) {
10342 // short checkin version
10343 pw.println(uptime + "," + realtime);
10344 pw.flush();
10345 } else {
10346 pw.println("Applications Memory Usage (kB):");
10347 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10348 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010349
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350 String[] innerArgs = new String[args.length-opti];
10351 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10352
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010353 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10354 long nativePss=0, dalvikPss=0, otherPss=0;
10355 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10356
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010357 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10358 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10359 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010360
10361 long totalPss = 0;
10362
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010363 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10364 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010365 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010366 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10368 pw.flush();
10369 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010370 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010371 if (dumpAll) {
10372 try {
10373 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10374 } catch (RemoteException e) {
10375 if (!isCheckinRequest) {
10376 pw.println("Got RemoteException!");
10377 pw.flush();
10378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010379 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010380 } else {
10381 mi = new Debug.MemoryInfo();
10382 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010383 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010384
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010385 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010386 long myTotalPss = mi.getTotalPss();
10387 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010388 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010389 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010390 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010391
10392 nativePss += mi.nativePss;
10393 dalvikPss += mi.dalvikPss;
10394 otherPss += mi.otherPss;
10395 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10396 long mem = mi.getOtherPss(j);
10397 miscPss[j] += mem;
10398 otherPss -= mem;
10399 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010400
10401 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010402 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10403 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010404 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010405 if (oomProcs[oomIndex] == null) {
10406 oomProcs[oomIndex] = new ArrayList<MemItem>();
10407 }
10408 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010409 break;
10410 }
10411 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 }
10414 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010415
10416 if (!isCheckinRequest && procs.size() > 1) {
10417 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10418
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010419 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10420 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10421 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010422 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010423 String label = Debug.MemoryInfo.getOtherLabel(j);
10424 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010425 }
10426
Dianne Hackbornb437e092011-08-05 17:50:29 -070010427 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10428 for (int j=0; j<oomPss.length; j++) {
10429 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010430 String label = DUMP_MEM_OOM_LABEL[j];
10431 MemItem item = new MemItem(label, label, oomPss[j],
10432 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010433 item.subitems = oomProcs[j];
10434 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010435 }
10436 }
10437
Dianne Hackborn672342c2011-11-29 11:29:02 -080010438 if (outTag != null || outStack != null) {
10439 if (outTag != null) {
10440 appendMemBucket(outTag, totalPss, "total", false);
10441 }
10442 if (outStack != null) {
10443 appendMemBucket(outStack, totalPss, "total", true);
10444 }
10445 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010446 for (int i=0; i<oomMems.size(); i++) {
10447 MemItem miCat = oomMems.get(i);
10448 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10449 continue;
10450 }
10451 if (miCat.id < ProcessList.SERVICE_ADJ
10452 || miCat.id == ProcessList.HOME_APP_ADJ
10453 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010454 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10455 outTag.append(" / ");
10456 }
10457 if (outStack != null) {
10458 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10459 if (firstLine) {
10460 outStack.append(":");
10461 firstLine = false;
10462 }
10463 outStack.append("\n\t at ");
10464 } else {
10465 outStack.append("$");
10466 }
10467 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010468 for (int j=0; j<miCat.subitems.size(); j++) {
10469 MemItem mi = miCat.subitems.get(j);
10470 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010471 if (outTag != null) {
10472 outTag.append(" ");
10473 }
10474 if (outStack != null) {
10475 outStack.append("$");
10476 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010477 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010478 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10479 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10480 }
10481 if (outStack != null) {
10482 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10483 }
10484 }
10485 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10486 outStack.append("(");
10487 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10488 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10489 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10490 outStack.append(":");
10491 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10492 }
10493 }
10494 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010495 }
10496 }
10497 }
10498 }
10499
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010500 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010501 pw.println();
10502 pw.println("Total PSS by process:");
10503 dumpMemItems(pw, " ", procMems, true);
10504 pw.println();
10505 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010506 pw.println("Total PSS by OOM adjustment:");
10507 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010508 if (!oomOnly) {
10509 PrintWriter out = categoryPw != null ? categoryPw : pw;
10510 out.println();
10511 out.println("Total PSS by category:");
10512 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010513 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010514 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010515 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010516 final int[] SINGLE_LONG_FORMAT = new int[] {
10517 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10518 };
10519 long[] longOut = new long[1];
10520 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10521 SINGLE_LONG_FORMAT, null, longOut, null);
10522 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10523 longOut[0] = 0;
10524 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10525 SINGLE_LONG_FORMAT, null, longOut, null);
10526 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10527 longOut[0] = 0;
10528 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10529 SINGLE_LONG_FORMAT, null, longOut, null);
10530 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10531 longOut[0] = 0;
10532 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10533 SINGLE_LONG_FORMAT, null, longOut, null);
10534 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10535 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10536 pw.print(shared); pw.println(" kB");
10537 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10538 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010540 }
10541
10542 /**
10543 * Searches array of arguments for the specified string
10544 * @param args array of argument strings
10545 * @param value value to search for
10546 * @return true if the value is contained in the array
10547 */
10548 private static boolean scanArgs(String[] args, String value) {
10549 if (args != null) {
10550 for (String arg : args) {
10551 if (value.equals(arg)) {
10552 return true;
10553 }
10554 }
10555 }
10556 return false;
10557 }
10558
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010559 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10560 ContentProviderRecord cpr, boolean always) {
10561 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10562
10563 if (!inLaunching || always) {
10564 synchronized (cpr) {
10565 cpr.launchingApp = null;
10566 cpr.notifyAll();
10567 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010568 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010569 String names[] = cpr.info.authority.split(";");
10570 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010571 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 }
10573 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010574
10575 for (int i=0; i<cpr.connections.size(); i++) {
10576 ContentProviderConnection conn = cpr.connections.get(i);
10577 if (conn.waiting) {
10578 // If this connection is waiting for the provider, then we don't
10579 // need to mess with its process unless we are always removing
10580 // or for some reason the provider is not currently launching.
10581 if (inLaunching && !always) {
10582 continue;
10583 }
10584 }
10585 ProcessRecord capp = conn.client;
10586 conn.dead = true;
10587 if (conn.stableCount > 0) {
10588 if (!capp.persistent && capp.thread != null
10589 && capp.pid != 0
10590 && capp.pid != MY_PID) {
10591 Slog.i(TAG, "Kill " + capp.processName
10592 + " (pid " + capp.pid + "): provider " + cpr.info.name
10593 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010594 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010595 capp.processName, capp.setAdj, "dying provider "
10596 + cpr.name.toShortString());
10597 Process.killProcessQuiet(capp.pid);
10598 }
10599 } else if (capp.thread != null && conn.provider.provider != null) {
10600 try {
10601 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10602 } catch (RemoteException e) {
10603 }
10604 // In the protocol here, we don't expect the client to correctly
10605 // clean up this connection, we'll just remove it.
10606 cpr.connections.remove(i);
10607 conn.client.conProviders.remove(conn);
10608 }
10609 }
10610
10611 if (inLaunching && always) {
10612 mLaunchingProviders.remove(cpr);
10613 }
10614 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010615 }
10616
10617 /**
10618 * Main code for cleaning up a process when it has gone away. This is
10619 * called both as a result of the process dying, or directly when stopping
10620 * a process when running in single process mode.
10621 */
10622 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010623 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010624 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010625 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010626 }
10627
Dianne Hackborn36124872009-10-08 16:22:03 -070010628 mProcessesToGc.remove(app);
10629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 // Dismiss any open dialogs.
10631 if (app.crashDialog != null) {
10632 app.crashDialog.dismiss();
10633 app.crashDialog = null;
10634 }
10635 if (app.anrDialog != null) {
10636 app.anrDialog.dismiss();
10637 app.anrDialog = null;
10638 }
10639 if (app.waitDialog != null) {
10640 app.waitDialog.dismiss();
10641 app.waitDialog = null;
10642 }
10643
10644 app.crashing = false;
10645 app.notResponding = false;
10646
10647 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010648 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010649 app.thread = null;
10650 app.forcingToForeground = null;
10651 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010652 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010653 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010654 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010655
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010656 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657
10658 boolean restart = false;
10659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 // Remove published content providers.
10661 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010662 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010664 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010665
10666 final boolean always = app.bad || !allowRestart;
10667 if (removeDyingProviderLocked(app, cpr, always) || always) {
10668 // We left the provider in the launching list, need to
10669 // restart it.
10670 restart = true;
10671 }
10672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010674 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 }
10676 app.pubProviders.clear();
10677 }
10678
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010679 // Take care of any launching providers waiting for this process.
10680 if (checkAppInLaunchingProvidersLocked(app, false)) {
10681 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010682 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684 // Unregister from connected content providers.
10685 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010686 for (int i=0; i<app.conProviders.size(); i++) {
10687 ContentProviderConnection conn = app.conProviders.get(i);
10688 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 }
10690 app.conProviders.clear();
10691 }
10692
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010693 // At this point there may be remaining entries in mLaunchingProviders
10694 // where we were the only one waiting, so they are no longer of use.
10695 // Look for these and clean up if found.
10696 // XXX Commented out for now. Trying to figure out a way to reproduce
10697 // the actual situation to identify what is actually going on.
10698 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010699 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010700 ContentProviderRecord cpr = (ContentProviderRecord)
10701 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010702 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010703 synchronized (cpr) {
10704 cpr.launchingApp = null;
10705 cpr.notifyAll();
10706 }
10707 }
10708 }
10709 }
10710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010711 skipCurrentReceiverLocked(app);
10712
10713 // Unregister any receivers.
10714 if (app.receivers.size() > 0) {
10715 Iterator<ReceiverList> it = app.receivers.iterator();
10716 while (it.hasNext()) {
10717 removeReceiverLocked(it.next());
10718 }
10719 app.receivers.clear();
10720 }
10721
Christopher Tate181fafa2009-05-14 11:12:14 -070010722 // If the app is undergoing backup, tell the backup manager about it
10723 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010724 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010725 try {
10726 IBackupManager bm = IBackupManager.Stub.asInterface(
10727 ServiceManager.getService(Context.BACKUP_SERVICE));
10728 bm.agentDisconnected(app.info.packageName);
10729 } catch (RemoteException e) {
10730 // can't happen; backup manager is local
10731 }
10732 }
10733
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010734 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10735 ProcessChangeItem item = mPendingProcessChanges.get(i);
10736 if (item.pid == app.pid) {
10737 mPendingProcessChanges.remove(i);
10738 mAvailProcessChanges.add(item);
10739 }
10740 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010741 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743 // If the caller is restarting this app, then leave it in its
10744 // current lists and let the caller take care of it.
10745 if (restarting) {
10746 return;
10747 }
10748
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010749 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010750 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010751 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010752 mProcessNames.remove(app.processName, app.uid);
10753 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010754 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010755 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10756 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010757 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759 } else if (!app.removed) {
10760 // This app is persistent, so we need to keep its record around.
10761 // If it is not already on the pending app list, add it there
10762 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10764 mPersistentStartingProcesses.add(app);
10765 restart = true;
10766 }
10767 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010768 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10769 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 mProcessesOnHold.remove(app);
10771
The Android Open Source Project4df24232009-03-05 14:34:35 -080010772 if (app == mHomeProcess) {
10773 mHomeProcess = null;
10774 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010775 if (app == mPreviousProcess) {
10776 mPreviousProcess = null;
10777 }
10778
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010779 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010780 // We have components that still need to be running in the
10781 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010782 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 startProcessLocked(app, "restart", app.processName);
10784 } else if (app.pid > 0 && app.pid != MY_PID) {
10785 // Goodbye!
10786 synchronized (mPidsSelfLocked) {
10787 mPidsSelfLocked.remove(app.pid);
10788 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10789 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010790 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 }
10792 }
10793
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010794 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10795 // Look through the content providers we are waiting to have launched,
10796 // and if any run in this process then either schedule a restart of
10797 // the process or kill the client waiting for it if this process has
10798 // gone bad.
10799 int NL = mLaunchingProviders.size();
10800 boolean restart = false;
10801 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010802 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010803 if (cpr.launchingApp == app) {
10804 if (!alwaysBad && !app.bad) {
10805 restart = true;
10806 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010807 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010808 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010809 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010810 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010811 }
10812 }
10813 }
10814 return restart;
10815 }
10816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 // =========================================================
10818 // SERVICES
10819 // =========================================================
10820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10822 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010823 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010825 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 }
10827 }
10828
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010829 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010830 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010831 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010832 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010833 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010834 }
10835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010837 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010838 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010839 // Refuse possible leaked file descriptors
10840 if (service != null && service.hasFileDescriptors() == true) {
10841 throw new IllegalArgumentException("File descriptors passed in Intent");
10842 }
10843
Amith Yamasani742a6712011-05-04 14:49:28 -070010844 if (DEBUG_SERVICE)
10845 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010846 synchronized(this) {
10847 final int callingPid = Binder.getCallingPid();
10848 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010849 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010850 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010851 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010852 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010853 Binder.restoreCallingIdentity(origId);
10854 return res;
10855 }
10856 }
10857
10858 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010859 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010861 if (DEBUG_SERVICE)
10862 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010864 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010865 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 Binder.restoreCallingIdentity(origId);
10867 return res;
10868 }
10869 }
10870
10871 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010872 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010873 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874 // Refuse possible leaked file descriptors
10875 if (service != null && service.hasFileDescriptors() == true) {
10876 throw new IllegalArgumentException("File descriptors passed in Intent");
10877 }
10878
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010879 checkValidCaller(Binder.getCallingUid(), userId);
10880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010882 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010884 }
10885
10886 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010887 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 // Refuse possible leaked file descriptors
10889 if (service != null && service.hasFileDescriptors() == true) {
10890 throw new IllegalArgumentException("File descriptors passed in Intent");
10891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010893 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 }
10896
10897 public boolean stopServiceToken(ComponentName className, IBinder token,
10898 int startId) {
10899 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010900 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010902 }
10903
10904 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010905 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010906 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010907 mServices.setServiceForegroundLocked(className, token, id, notification,
10908 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 }
10910 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010911
Dianne Hackborn41203752012-08-31 14:05:51 -070010912 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10913 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010914 final int callingUserId = UserHandle.getUserId(callingUid);
10915 if (callingUserId != userId) {
10916 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10917 if ((requireFull || checkComponentPermission(
10918 android.Manifest.permission.INTERACT_ACROSS_USERS,
10919 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10920 && checkComponentPermission(
10921 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10922 callingPid, callingUid, -1, true)
10923 != PackageManager.PERMISSION_GRANTED) {
10924 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10925 // In this case, they would like to just execute as their
10926 // owner user instead of failing.
10927 userId = callingUserId;
10928 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010929 StringBuilder builder = new StringBuilder(128);
10930 builder.append("Permission Denial: ");
10931 builder.append(name);
10932 if (callerPackage != null) {
10933 builder.append(" from ");
10934 builder.append(callerPackage);
10935 }
10936 builder.append(" asks to run as user ");
10937 builder.append(userId);
10938 builder.append(" but is calling from user ");
10939 builder.append(UserHandle.getUserId(callingUid));
10940 builder.append("; this requires ");
10941 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10942 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010943 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010944 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10945 }
10946 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010947 Slog.w(TAG, msg);
10948 throw new SecurityException(msg);
10949 }
10950 }
10951 }
10952 if (userId == UserHandle.USER_CURRENT
10953 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070010954 // Note that we may be accessing this outside of a lock...
10955 // shouldn't be a big deal, if this is being called outside
10956 // of a locked context there is intrinsically a race with
10957 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010958 userId = mCurrentUserId;
10959 }
10960 if (!allowAll && userId < 0) {
10961 throw new IllegalArgumentException(
10962 "Call does not support special user #" + userId);
10963 }
10964 }
10965 return userId;
10966 }
10967
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010968 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10969 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010970 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010971 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010972 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10973 if (ActivityManager.checkUidPermission(
10974 android.Manifest.permission.INTERACT_ACROSS_USERS,
10975 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10976 ComponentName comp = new ComponentName(aInfo.packageName, className);
10977 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10978 + " requests FLAG_SINGLE_USER, but app does not hold "
10979 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10980 Slog.w(TAG, msg);
10981 throw new SecurityException(msg);
10982 }
10983 result = true;
10984 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010985 } else if (componentProcessName == aInfo.packageName) {
10986 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10987 } else if ("system".equals(componentProcessName)) {
10988 result = true;
10989 }
10990 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010991 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10992 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010993 }
10994 return result;
10995 }
10996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 public int bindService(IApplicationThread caller, IBinder token,
10998 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010999 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011000 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 // Refuse possible leaked file descriptors
11002 if (service != null && service.hasFileDescriptors() == true) {
11003 throw new IllegalArgumentException("File descriptors passed in Intent");
11004 }
11005
11006 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011007 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11008 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 }
11010 }
11011
11012 public boolean unbindService(IServiceConnection connection) {
11013 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011014 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016 }
11017
11018 public void publishService(IBinder token, Intent intent, IBinder service) {
11019 // Refuse possible leaked file descriptors
11020 if (intent != null && intent.hasFileDescriptors() == true) {
11021 throw new IllegalArgumentException("File descriptors passed in Intent");
11022 }
11023
11024 synchronized(this) {
11025 if (!(token instanceof ServiceRecord)) {
11026 throw new IllegalArgumentException("Invalid service token");
11027 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011028 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 }
11030 }
11031
11032 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11033 // Refuse possible leaked file descriptors
11034 if (intent != null && intent.hasFileDescriptors() == true) {
11035 throw new IllegalArgumentException("File descriptors passed in Intent");
11036 }
11037
11038 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011039 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 }
11041 }
11042
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011043 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044 synchronized(this) {
11045 if (!(token instanceof ServiceRecord)) {
11046 throw new IllegalArgumentException("Invalid service token");
11047 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011048 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011050 }
11051
11052 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011053 // BACKUP AND RESTORE
11054 // =========================================================
11055
11056 // Cause the target app to be launched if necessary and its backup agent
11057 // instantiated. The backup agent will invoke backupAgentCreated() on the
11058 // activity manager to announce its creation.
11059 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011060 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011061 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11062
11063 synchronized(this) {
11064 // !!! TODO: currently no check here that we're already bound
11065 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11066 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11067 synchronized (stats) {
11068 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11069 }
11070
Dianne Hackborne7f97212011-02-24 14:40:20 -080011071 // Backup agent is now in use, its package can't be stopped.
11072 try {
11073 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011074 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011075 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011076 } catch (IllegalArgumentException e) {
11077 Slog.w(TAG, "Failed trying to unstop package "
11078 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011079 }
11080
Christopher Tate181fafa2009-05-14 11:12:14 -070011081 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011082 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11083 ? new ComponentName(app.packageName, app.backupAgentName)
11084 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011085 // startProcessLocked() returns existing proc's record if it's already running
11086 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011087 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011088 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011089 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011090 return false;
11091 }
11092
11093 r.app = proc;
11094 mBackupTarget = r;
11095 mBackupAppName = app.packageName;
11096
Christopher Tate6fa95972009-06-05 18:43:55 -070011097 // Try not to kill the process during backup
11098 updateOomAdjLocked(proc);
11099
Christopher Tate181fafa2009-05-14 11:12:14 -070011100 // If the process is already attached, schedule the creation of the backup agent now.
11101 // If it is not yet live, this will be done when it attaches to the framework.
11102 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011103 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011104 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011105 proc.thread.scheduleCreateBackupAgent(app,
11106 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011107 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011108 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011109 }
11110 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011111 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011112 }
11113 // Invariants: at this point, the target app process exists and the application
11114 // is either already running or in the process of coming up. mBackupTarget and
11115 // mBackupAppName describe the app, so that when it binds back to the AM we
11116 // know that it's scheduled for a backup-agent operation.
11117 }
11118
11119 return true;
11120 }
11121
11122 // A backup agent has just come up
11123 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011124 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011125 + " = " + agent);
11126
11127 synchronized(this) {
11128 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011129 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011130 return;
11131 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011132 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011133
Dianne Hackborn06740692010-09-22 22:46:21 -070011134 long oldIdent = Binder.clearCallingIdentity();
11135 try {
11136 IBackupManager bm = IBackupManager.Stub.asInterface(
11137 ServiceManager.getService(Context.BACKUP_SERVICE));
11138 bm.agentConnected(agentPackageName, agent);
11139 } catch (RemoteException e) {
11140 // can't happen; the backup manager service is local
11141 } catch (Exception e) {
11142 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11143 e.printStackTrace();
11144 } finally {
11145 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011146 }
11147 }
11148
11149 // done with this agent
11150 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011151 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011152 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011153 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011154 return;
11155 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011156
11157 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011158 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011159 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011160 return;
11161 }
11162
Christopher Tate181fafa2009-05-14 11:12:14 -070011163 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011164 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011165 return;
11166 }
11167
Christopher Tate6fa95972009-06-05 18:43:55 -070011168 ProcessRecord proc = mBackupTarget.app;
11169 mBackupTarget = null;
11170 mBackupAppName = null;
11171
11172 // Not backing this app up any more; reset its OOM adjustment
11173 updateOomAdjLocked(proc);
11174
Christopher Tatec7b31e32009-06-10 15:49:30 -070011175 // If the app crashed during backup, 'thread' will be null here
11176 if (proc.thread != null) {
11177 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011178 proc.thread.scheduleDestroyBackupAgent(appInfo,
11179 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011180 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011181 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011182 e.printStackTrace();
11183 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011184 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011185 }
11186 }
11187 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 // BROADCASTS
11189 // =========================================================
11190
Josh Bartel7f208742010-02-25 11:01:44 -060011191 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011192 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011194 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11195 if (stickies == null) {
11196 return cur;
11197 }
11198 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011199 if (list == null) {
11200 return cur;
11201 }
11202 int N = list.size();
11203 for (int i=0; i<N; i++) {
11204 Intent intent = list.get(i);
11205 if (filter.match(resolver, intent, true, TAG) >= 0) {
11206 if (cur == null) {
11207 cur = new ArrayList<Intent>();
11208 }
11209 cur.add(intent);
11210 }
11211 }
11212 return cur;
11213 }
11214
Christopher Tatef46723b2012-01-26 14:19:24 -080011215 boolean isPendingBroadcastProcessLocked(int pid) {
11216 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11217 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219
Christopher Tatef46723b2012-01-26 14:19:24 -080011220 void skipPendingBroadcastLocked(int pid) {
11221 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11222 for (BroadcastQueue queue : mBroadcastQueues) {
11223 queue.skipPendingBroadcastLocked(pid);
11224 }
11225 }
11226
11227 // The app just attached; send any pending broadcasts that it should receive
11228 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11229 boolean didSomething = false;
11230 for (BroadcastQueue queue : mBroadcastQueues) {
11231 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011233 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011234 }
11235
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011236 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011237 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011238 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011239 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011240 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011241 synchronized(this) {
11242 ProcessRecord callerApp = null;
11243 if (caller != null) {
11244 callerApp = getRecordForAppLocked(caller);
11245 if (callerApp == null) {
11246 throw new SecurityException(
11247 "Unable to find app for caller " + caller
11248 + " (pid=" + Binder.getCallingPid()
11249 + ") when registering receiver " + receiver);
11250 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011251 if (callerApp.info.uid != Process.SYSTEM_UID &&
11252 !callerApp.pkgList.contains(callerPackage)) {
11253 throw new SecurityException("Given caller package " + callerPackage
11254 + " is not running in process " + callerApp);
11255 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011256 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011257 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011258 } else {
11259 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011260 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011261 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011262 }
11263
Dianne Hackborn139748f2012-09-24 11:36:57 -070011264 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011265 true, true, "registerReceiver", callerPackage);
11266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011267 List allSticky = null;
11268
11269 // Look for any matching sticky broadcasts...
11270 Iterator actions = filter.actionsIterator();
11271 if (actions != null) {
11272 while (actions.hasNext()) {
11273 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011274 allSticky = getStickiesLocked(action, filter, allSticky,
11275 UserHandle.USER_ALL);
11276 allSticky = getStickiesLocked(action, filter, allSticky,
11277 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 }
11279 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011280 allSticky = getStickiesLocked(null, filter, allSticky,
11281 UserHandle.USER_ALL);
11282 allSticky = getStickiesLocked(null, filter, allSticky,
11283 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011284 }
11285
11286 // The first sticky in the list is returned directly back to
11287 // the client.
11288 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11289
Joe Onorato8a9b2202010-02-26 18:56:32 -080011290 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011291 + ": " + sticky);
11292
11293 if (receiver == null) {
11294 return sticky;
11295 }
11296
11297 ReceiverList rl
11298 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11299 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011300 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11301 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011302 if (rl.app != null) {
11303 rl.app.receivers.add(rl);
11304 } else {
11305 try {
11306 receiver.asBinder().linkToDeath(rl, 0);
11307 } catch (RemoteException e) {
11308 return sticky;
11309 }
11310 rl.linkedToDeath = true;
11311 }
11312 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011313 } else if (rl.uid != callingUid) {
11314 throw new IllegalArgumentException(
11315 "Receiver requested to register for uid " + callingUid
11316 + " was previously registered for uid " + rl.uid);
11317 } else if (rl.pid != callingPid) {
11318 throw new IllegalArgumentException(
11319 "Receiver requested to register for pid " + callingPid
11320 + " was previously registered for pid " + rl.pid);
11321 } else if (rl.userId != userId) {
11322 throw new IllegalArgumentException(
11323 "Receiver requested to register for user " + userId
11324 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011326 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011327 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 rl.add(bf);
11329 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011330 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 }
11332 mReceiverResolver.addFilter(bf);
11333
11334 // Enqueue broadcasts for all existing stickies that match
11335 // this filter.
11336 if (allSticky != null) {
11337 ArrayList receivers = new ArrayList();
11338 receivers.add(bf);
11339
11340 int N = allSticky.size();
11341 for (int i=0; i<N; i++) {
11342 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011343 BroadcastQueue queue = broadcastQueueForIntent(intent);
11344 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011346 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011347 queue.enqueueParallelBroadcastLocked(r);
11348 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011349 }
11350 }
11351
11352 return sticky;
11353 }
11354 }
11355
11356 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011357 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358
Christopher Tatef46723b2012-01-26 14:19:24 -080011359 final long origId = Binder.clearCallingIdentity();
11360 try {
11361 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362
Christopher Tatef46723b2012-01-26 14:19:24 -080011363 synchronized(this) {
11364 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011366 if (rl != null) {
11367 if (rl.curBroadcast != null) {
11368 BroadcastRecord r = rl.curBroadcast;
11369 final boolean doNext = finishReceiverLocked(
11370 receiver.asBinder(), r.resultCode, r.resultData,
11371 r.resultExtras, r.resultAbort, true);
11372 if (doNext) {
11373 doTrim = true;
11374 r.queue.processNextBroadcast(false);
11375 }
11376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377
Christopher Tatef46723b2012-01-26 14:19:24 -080011378 if (rl.app != null) {
11379 rl.app.receivers.remove(rl);
11380 }
11381 removeReceiverLocked(rl);
11382 if (rl.linkedToDeath) {
11383 rl.linkedToDeath = false;
11384 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 }
11387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388
Christopher Tatef46723b2012-01-26 14:19:24 -080011389 // If we actually concluded any broadcasts, we might now be able
11390 // to trim the recipients' apps from our working set
11391 if (doTrim) {
11392 trimApplications();
11393 return;
11394 }
11395
11396 } finally {
11397 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011399 }
11400
11401 void removeReceiverLocked(ReceiverList rl) {
11402 mRegisteredReceivers.remove(rl.receiver.asBinder());
11403 int N = rl.size();
11404 for (int i=0; i<N; i++) {
11405 mReceiverResolver.removeFilter(rl.get(i));
11406 }
11407 }
11408
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011409 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011410 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11411 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011412 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011413 try {
11414 r.thread.dispatchPackageBroadcast(cmd, packages);
11415 } catch (RemoteException ex) {
11416 }
11417 }
11418 }
11419 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011420
11421 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11422 int[] users) {
11423 List<ResolveInfo> receivers = null;
11424 try {
11425 HashSet<ComponentName> singleUserReceivers = null;
11426 boolean scannedFirstReceivers = false;
11427 for (int user : users) {
11428 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11429 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11430 if (newReceivers != null && newReceivers.size() == 0) {
11431 newReceivers = null;
11432 }
11433 if (receivers == null) {
11434 receivers = newReceivers;
11435 } else if (newReceivers != null) {
11436 // We need to concatenate the additional receivers
11437 // found with what we have do far. This would be easy,
11438 // but we also need to de-dup any receivers that are
11439 // singleUser.
11440 if (!scannedFirstReceivers) {
11441 // Collect any single user receivers we had already retrieved.
11442 scannedFirstReceivers = true;
11443 for (int i=0; i<receivers.size(); i++) {
11444 ResolveInfo ri = receivers.get(i);
11445 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11446 ComponentName cn = new ComponentName(
11447 ri.activityInfo.packageName, ri.activityInfo.name);
11448 if (singleUserReceivers == null) {
11449 singleUserReceivers = new HashSet<ComponentName>();
11450 }
11451 singleUserReceivers.add(cn);
11452 }
11453 }
11454 }
11455 // Add the new results to the existing results, tracking
11456 // and de-dupping single user receivers.
11457 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011458 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011459 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11460 ComponentName cn = new ComponentName(
11461 ri.activityInfo.packageName, ri.activityInfo.name);
11462 if (singleUserReceivers == null) {
11463 singleUserReceivers = new HashSet<ComponentName>();
11464 }
11465 if (!singleUserReceivers.contains(cn)) {
11466 singleUserReceivers.add(cn);
11467 receivers.add(ri);
11468 }
11469 } else {
11470 receivers.add(ri);
11471 }
11472 }
11473 }
11474 }
11475 } catch (RemoteException ex) {
11476 // pm is in same process, this will never happen.
11477 }
11478 return receivers;
11479 }
11480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481 private final int broadcastIntentLocked(ProcessRecord callerApp,
11482 String callerPackage, Intent intent, String resolvedType,
11483 IIntentReceiver resultTo, int resultCode, String resultData,
11484 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011485 boolean ordered, boolean sticky, int callingPid, int callingUid,
11486 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011487 intent = new Intent(intent);
11488
Dianne Hackborne7f97212011-02-24 14:40:20 -080011489 // By default broadcasts do not go to stopped apps.
11490 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11491
Joe Onorato8a9b2202010-02-26 18:56:32 -080011492 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011494 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011495 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011496 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011498
Dianne Hackborn139748f2012-09-24 11:36:57 -070011499 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011500 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011501
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011502 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011503 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011504 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011505 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11506 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11507 Slog.w(TAG, "Skipping broadcast of " + intent
11508 + ": user " + userId + " is stopped");
11509 return ActivityManager.BROADCAST_SUCCESS;
11510 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011511 }
11512
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011513 /*
11514 * Prevent non-system code (defined here to be non-persistent
11515 * processes) from sending protected broadcasts.
11516 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011517 int callingAppId = UserHandle.getAppId(callingUid);
11518 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11519 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011520 callingUid == 0) {
11521 // Always okay.
11522 } else if (callerApp == null || !callerApp.persistent) {
11523 try {
11524 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11525 intent.getAction())) {
11526 String msg = "Permission Denial: not allowed to send broadcast "
11527 + intent.getAction() + " from pid="
11528 + callingPid + ", uid=" + callingUid;
11529 Slog.w(TAG, msg);
11530 throw new SecurityException(msg);
11531 }
11532 } catch (RemoteException e) {
11533 Slog.w(TAG, "Remote exception", e);
11534 return ActivityManager.BROADCAST_SUCCESS;
11535 }
11536 }
11537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 // Handle special intents: if this broadcast is from the package
11539 // manager about a package being removed, we need to remove all of
11540 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011541 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011542 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011543 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11544 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011545 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 || uidRemoved) {
11547 if (checkComponentPermission(
11548 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011549 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550 == PackageManager.PERMISSION_GRANTED) {
11551 if (uidRemoved) {
11552 final Bundle intentExtras = intent.getExtras();
11553 final int uid = intentExtras != null
11554 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11555 if (uid >= 0) {
11556 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11557 synchronized (bs) {
11558 bs.removeUidStatsLocked(uid);
11559 }
11560 }
11561 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011562 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011563 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011564 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011565 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11566 if (list != null && (list.length > 0)) {
11567 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011568 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011569 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011570 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011571 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011572 }
11573 } else {
11574 Uri data = intent.getData();
11575 String ssp;
11576 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11577 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11578 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011579 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11580 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011581 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011582 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011583 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011584 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011586 }
11587 }
11588 }
11589 } else {
11590 String msg = "Permission Denial: " + intent.getAction()
11591 + " broadcast from " + callerPackage + " (pid=" + callingPid
11592 + ", uid=" + callingUid + ")"
11593 + " requires "
11594 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011595 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 throw new SecurityException(msg);
11597 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011598
11599 // Special case for adding a package: by default turn on compatibility
11600 // mode.
11601 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011602 Uri data = intent.getData();
11603 String ssp;
11604 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11605 mCompatModePackages.handlePackageAddedLocked(ssp,
11606 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 }
11609
11610 /*
11611 * If this is the time zone changed action, queue up a message that will reset the timezone
11612 * of all currently running processes. This message will get queued up before the broadcast
11613 * happens.
11614 */
11615 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11616 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11617 }
11618
Robert Greenwalt03595d02010-11-02 14:08:23 -070011619 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11620 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11621 }
11622
Robert Greenwalt434203a2010-10-11 16:00:27 -070011623 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11624 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11625 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11626 }
11627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628 // Add to the sticky list if requested.
11629 if (sticky) {
11630 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11631 callingPid, callingUid)
11632 != PackageManager.PERMISSION_GRANTED) {
11633 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11634 + callingPid + ", uid=" + callingUid
11635 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011636 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011637 throw new SecurityException(msg);
11638 }
11639 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011640 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011642 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011643 }
11644 if (intent.getComponent() != null) {
11645 throw new SecurityException(
11646 "Sticky broadcasts can't target a specific component");
11647 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011648 // We use userId directly here, since the "all" target is maintained
11649 // as a separate set of sticky broadcasts.
11650 if (userId != UserHandle.USER_ALL) {
11651 // But first, if this is not a broadcast to all users, then
11652 // make sure it doesn't conflict with an existing broadcast to
11653 // all users.
11654 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11655 UserHandle.USER_ALL);
11656 if (stickies != null) {
11657 ArrayList<Intent> list = stickies.get(intent.getAction());
11658 if (list != null) {
11659 int N = list.size();
11660 int i;
11661 for (i=0; i<N; i++) {
11662 if (intent.filterEquals(list.get(i))) {
11663 throw new IllegalArgumentException(
11664 "Sticky broadcast " + intent + " for user "
11665 + userId + " conflicts with existing global broadcast");
11666 }
11667 }
11668 }
11669 }
11670 }
11671 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11672 if (stickies == null) {
11673 stickies = new HashMap<String, ArrayList<Intent>>();
11674 mStickyBroadcasts.put(userId, stickies);
11675 }
11676 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011677 if (list == null) {
11678 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011679 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011680 }
11681 int N = list.size();
11682 int i;
11683 for (i=0; i<N; i++) {
11684 if (intent.filterEquals(list.get(i))) {
11685 // This sticky already exists, replace it.
11686 list.set(i, new Intent(intent));
11687 break;
11688 }
11689 }
11690 if (i >= N) {
11691 list.add(new Intent(intent));
11692 }
11693 }
11694
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011695 int[] users;
11696 if (userId == UserHandle.USER_ALL) {
11697 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011698 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011699 } else {
11700 // Caller wants broadcast to go to one specific user.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011701 users = mCurrentUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011702 }
11703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011704 // Figure out who all will receive this broadcast.
11705 List receivers = null;
11706 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011707 // Need to resolve the intent to interested receivers...
11708 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11709 == 0) {
11710 receivers = collectReceiverComponents(intent, resolvedType, users);
11711 }
11712 if (intent.getComponent() == null) {
11713 registeredReceivers = mReceiverResolver.queryIntent(intent,
11714 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 }
11716
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011717 final boolean replacePending =
11718 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11719
Joe Onorato8a9b2202010-02-26 18:56:32 -080011720 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011721 + " replacePending=" + replacePending);
11722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011723 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11724 if (!ordered && NR > 0) {
11725 // If we are not serializing this broadcast, then send the
11726 // registered receivers separately so they don't wait for the
11727 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011728 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11729 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730 callerPackage, callingPid, callingUid, requiredPermission,
11731 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011732 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011733 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011734 TAG, "Enqueueing parallel broadcast " + r);
11735 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011736 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011737 queue.enqueueParallelBroadcastLocked(r);
11738 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 registeredReceivers = null;
11741 NR = 0;
11742 }
11743
11744 // Merge into one list.
11745 int ir = 0;
11746 if (receivers != null) {
11747 // A special case for PACKAGE_ADDED: do not allow the package
11748 // being added to see this broadcast. This prevents them from
11749 // using this as a back door to get run as soon as they are
11750 // installed. Maybe in the future we want to have a special install
11751 // broadcast or such for apps, but we'd like to deliberately make
11752 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011753 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011754 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11755 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11756 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011757 Uri data = intent.getData();
11758 if (data != null) {
11759 String pkgName = data.getSchemeSpecificPart();
11760 if (pkgName != null) {
11761 skipPackages = new String[] { pkgName };
11762 }
11763 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011764 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011765 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011766 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011767 if (skipPackages != null && (skipPackages.length > 0)) {
11768 for (String skipPackage : skipPackages) {
11769 if (skipPackage != null) {
11770 int NT = receivers.size();
11771 for (int it=0; it<NT; it++) {
11772 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11773 if (curt.activityInfo.packageName.equals(skipPackage)) {
11774 receivers.remove(it);
11775 it--;
11776 NT--;
11777 }
11778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 }
11780 }
11781 }
11782
11783 int NT = receivers != null ? receivers.size() : 0;
11784 int it = 0;
11785 ResolveInfo curt = null;
11786 BroadcastFilter curr = null;
11787 while (it < NT && ir < NR) {
11788 if (curt == null) {
11789 curt = (ResolveInfo)receivers.get(it);
11790 }
11791 if (curr == null) {
11792 curr = registeredReceivers.get(ir);
11793 }
11794 if (curr.getPriority() >= curt.priority) {
11795 // Insert this broadcast record into the final list.
11796 receivers.add(it, curr);
11797 ir++;
11798 curr = null;
11799 it++;
11800 NT++;
11801 } else {
11802 // Skip to the next ResolveInfo in the final list.
11803 it++;
11804 curt = null;
11805 }
11806 }
11807 }
11808 while (ir < NR) {
11809 if (receivers == null) {
11810 receivers = new ArrayList();
11811 }
11812 receivers.add(registeredReceivers.get(ir));
11813 ir++;
11814 }
11815
11816 if ((receivers != null && receivers.size() > 0)
11817 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011818 BroadcastQueue queue = broadcastQueueForIntent(intent);
11819 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011821 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011822 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011823 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011825 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011826 if (DEBUG_BROADCAST) {
11827 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011828 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011829 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011830 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011831 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011832 queue.enqueueOrderedBroadcastLocked(r);
11833 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011835 }
11836
Dianne Hackborna4972e92012-03-14 10:38:05 -070011837 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838 }
11839
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011840 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011841 // Refuse possible leaked file descriptors
11842 if (intent != null && intent.hasFileDescriptors() == true) {
11843 throw new IllegalArgumentException("File descriptors passed in Intent");
11844 }
11845
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011846 int flags = intent.getFlags();
11847
11848 if (!mProcessesReady) {
11849 // if the caller really truly claims to know what they're doing, go
11850 // ahead and allow the broadcast without launching any receivers
11851 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11852 intent = new Intent(intent);
11853 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11854 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11855 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11856 + " before boot completion");
11857 throw new IllegalStateException("Cannot broadcast before boot completed");
11858 }
11859 }
11860
11861 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11862 throw new IllegalArgumentException(
11863 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11864 }
11865
11866 return intent;
11867 }
11868
11869 public final int broadcastIntent(IApplicationThread caller,
11870 Intent intent, String resolvedType, IIntentReceiver resultTo,
11871 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011872 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011873 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011875 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11878 final int callingPid = Binder.getCallingPid();
11879 final int callingUid = Binder.getCallingUid();
11880 final long origId = Binder.clearCallingIdentity();
11881 int res = broadcastIntentLocked(callerApp,
11882 callerApp != null ? callerApp.info.packageName : null,
11883 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011884 resultCode, resultData, map, requiredPermission, serialized, sticky,
11885 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011886 Binder.restoreCallingIdentity(origId);
11887 return res;
11888 }
11889 }
11890
11891 int broadcastIntentInPackage(String packageName, int uid,
11892 Intent intent, String resolvedType, IIntentReceiver resultTo,
11893 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011894 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011895 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011896 intent = verifyBroadcastLocked(intent);
11897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011898 final long origId = Binder.clearCallingIdentity();
11899 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11900 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011901 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011902 Binder.restoreCallingIdentity(origId);
11903 return res;
11904 }
11905 }
11906
Amith Yamasani742a6712011-05-04 14:49:28 -070011907 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011908 // Refuse possible leaked file descriptors
11909 if (intent != null && intent.hasFileDescriptors() == true) {
11910 throw new IllegalArgumentException("File descriptors passed in Intent");
11911 }
11912
Dianne Hackborn139748f2012-09-24 11:36:57 -070011913 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011914 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011916 synchronized(this) {
11917 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11918 != PackageManager.PERMISSION_GRANTED) {
11919 String msg = "Permission Denial: unbroadcastIntent() from pid="
11920 + Binder.getCallingPid()
11921 + ", uid=" + Binder.getCallingUid()
11922 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011923 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924 throw new SecurityException(msg);
11925 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011926 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11927 if (stickies != null) {
11928 ArrayList<Intent> list = stickies.get(intent.getAction());
11929 if (list != null) {
11930 int N = list.size();
11931 int i;
11932 for (i=0; i<N; i++) {
11933 if (intent.filterEquals(list.get(i))) {
11934 list.remove(i);
11935 break;
11936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011938 if (list.size() <= 0) {
11939 stickies.remove(intent.getAction());
11940 }
11941 }
11942 if (stickies.size() <= 0) {
11943 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 }
11945 }
11946 }
11947 }
11948
11949 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11950 String resultData, Bundle resultExtras, boolean resultAbort,
11951 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011952 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11953 if (r == null) {
11954 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011955 return false;
11956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957
Christopher Tatef46723b2012-01-26 14:19:24 -080011958 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11959 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011960 }
11961
11962 public void finishReceiver(IBinder who, int resultCode, String resultData,
11963 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011964 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011965
11966 // Refuse possible leaked file descriptors
11967 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11968 throw new IllegalArgumentException("File descriptors passed in Bundle");
11969 }
11970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011971 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011972 try {
11973 boolean doNext = false;
11974 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975
Christopher Tatef46723b2012-01-26 14:19:24 -080011976 synchronized(this) {
11977 r = broadcastRecordForReceiverLocked(who);
11978 if (r != null) {
11979 doNext = r.queue.finishReceiverLocked(r, resultCode,
11980 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011983
Christopher Tatef46723b2012-01-26 14:19:24 -080011984 if (doNext) {
11985 r.queue.processNextBroadcast(false);
11986 }
11987 trimApplications();
11988 } finally {
11989 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011993 // =========================================================
11994 // INSTRUMENTATION
11995 // =========================================================
11996
11997 public boolean startInstrumentation(ComponentName className,
11998 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011999 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012000 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012001 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012002 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 // Refuse possible leaked file descriptors
12004 if (arguments != null && arguments.hasFileDescriptors()) {
12005 throw new IllegalArgumentException("File descriptors passed in Bundle");
12006 }
12007
12008 synchronized(this) {
12009 InstrumentationInfo ii = null;
12010 ApplicationInfo ai = null;
12011 try {
12012 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012013 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012014 ai = AppGlobals.getPackageManager().getApplicationInfo(
12015 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012017 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012018 }
12019 if (ii == null) {
12020 reportStartInstrumentationFailure(watcher, className,
12021 "Unable to find instrumentation info for: " + className);
12022 return false;
12023 }
12024 if (ai == null) {
12025 reportStartInstrumentationFailure(watcher, className,
12026 "Unable to find instrumentation target package: " + ii.targetPackage);
12027 return false;
12028 }
12029
12030 int match = mContext.getPackageManager().checkSignatures(
12031 ii.targetPackage, ii.packageName);
12032 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12033 String msg = "Permission Denial: starting instrumentation "
12034 + className + " from pid="
12035 + Binder.getCallingPid()
12036 + ", uid=" + Binder.getCallingPid()
12037 + " not allowed because package " + ii.packageName
12038 + " does not have a signature matching the target "
12039 + ii.targetPackage;
12040 reportStartInstrumentationFailure(watcher, className, msg);
12041 throw new SecurityException(msg);
12042 }
12043
12044 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012045 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012046 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012047 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012048 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012049 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012050 app.instrumentationProfileFile = profileFile;
12051 app.instrumentationArguments = arguments;
12052 app.instrumentationWatcher = watcher;
12053 app.instrumentationResultClass = className;
12054 Binder.restoreCallingIdentity(origId);
12055 }
12056
12057 return true;
12058 }
12059
12060 /**
12061 * Report errors that occur while attempting to start Instrumentation. Always writes the
12062 * error to the logs, but if somebody is watching, send the report there too. This enables
12063 * the "am" command to report errors with more information.
12064 *
12065 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12066 * @param cn The component name of the instrumentation.
12067 * @param report The error report.
12068 */
12069 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12070 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012071 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012072 try {
12073 if (watcher != null) {
12074 Bundle results = new Bundle();
12075 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12076 results.putString("Error", report);
12077 watcher.instrumentationStatus(cn, -1, results);
12078 }
12079 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012080 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012081 }
12082 }
12083
12084 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12085 if (app.instrumentationWatcher != null) {
12086 try {
12087 // NOTE: IInstrumentationWatcher *must* be oneway here
12088 app.instrumentationWatcher.instrumentationFinished(
12089 app.instrumentationClass,
12090 resultCode,
12091 results);
12092 } catch (RemoteException e) {
12093 }
12094 }
12095 app.instrumentationWatcher = null;
12096 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012097 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012098 app.instrumentationProfileFile = null;
12099 app.instrumentationArguments = null;
12100
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012101 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012102 }
12103
12104 public void finishInstrumentation(IApplicationThread target,
12105 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012106 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 // Refuse possible leaked file descriptors
12108 if (results != null && results.hasFileDescriptors()) {
12109 throw new IllegalArgumentException("File descriptors passed in Intent");
12110 }
12111
12112 synchronized(this) {
12113 ProcessRecord app = getRecordForAppLocked(target);
12114 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012115 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012116 return;
12117 }
12118 final long origId = Binder.clearCallingIdentity();
12119 finishInstrumentationLocked(app, resultCode, results);
12120 Binder.restoreCallingIdentity(origId);
12121 }
12122 }
12123
12124 // =========================================================
12125 // CONFIGURATION
12126 // =========================================================
12127
12128 public ConfigurationInfo getDeviceConfigurationInfo() {
12129 ConfigurationInfo config = new ConfigurationInfo();
12130 synchronized (this) {
12131 config.reqTouchScreen = mConfiguration.touchscreen;
12132 config.reqKeyboardType = mConfiguration.keyboard;
12133 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012134 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12135 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012136 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12137 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012138 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12139 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012140 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12141 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012142 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012143 }
12144 return config;
12145 }
12146
12147 public Configuration getConfiguration() {
12148 Configuration ci;
12149 synchronized(this) {
12150 ci = new Configuration(mConfiguration);
12151 }
12152 return ci;
12153 }
12154
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012155 public void updatePersistentConfiguration(Configuration values) {
12156 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12157 "updateConfiguration()");
12158 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12159 "updateConfiguration()");
12160 if (values == null) {
12161 throw new NullPointerException("Configuration must not be null");
12162 }
12163
12164 synchronized(this) {
12165 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012166 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012167 Binder.restoreCallingIdentity(origId);
12168 }
12169 }
12170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012171 public void updateConfiguration(Configuration values) {
12172 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12173 "updateConfiguration()");
12174
12175 synchronized(this) {
12176 if (values == null && mWindowManager != null) {
12177 // sentinel: fetch the current configuration from the window manager
12178 values = mWindowManager.computeNewConfiguration();
12179 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012180
12181 if (mWindowManager != null) {
12182 mProcessList.applyDisplaySize(mWindowManager);
12183 }
12184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012185 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012186 if (values != null) {
12187 Settings.System.clearConfiguration(values);
12188 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012189 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012190 Binder.restoreCallingIdentity(origId);
12191 }
12192 }
12193
12194 /**
12195 * Do either or both things: (1) change the current configuration, and (2)
12196 * make sure the given activity is running with the (now) current
12197 * configuration. Returns true if the activity has been left running, or
12198 * false if <var>starting</var> is being destroyed to match the new
12199 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012200 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012201 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012202 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012203 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012204 // do nothing if we are headless
12205 if (mHeadless) return true;
12206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012207 int changes = 0;
12208
12209 boolean kept = true;
12210
12211 if (values != null) {
12212 Configuration newConfig = new Configuration(mConfiguration);
12213 changes = newConfig.updateFrom(values);
12214 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012215 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012216 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 }
12218
Doug Zongker2bec3d42009-12-04 12:52:44 -080012219 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220
Dianne Hackborn813075a62011-11-14 17:45:19 -080012221 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222 saveLocaleLocked(values.locale,
12223 !values.locale.equals(mConfiguration.locale),
12224 values.userSetLocale);
12225 }
12226
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012227 mConfigurationSeq++;
12228 if (mConfigurationSeq <= 0) {
12229 mConfigurationSeq = 1;
12230 }
12231 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012232 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012233 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012234
12235 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012236
12237 // TODO: If our config changes, should we auto dismiss any currently
12238 // showing dialogs?
12239 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012240
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012241 AttributeCache ac = AttributeCache.instance();
12242 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012243 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012246 // Make sure all resources in our process are updated
12247 // right now, so that anyone who is going to retrieve
12248 // resource values after we return will be sure to get
12249 // the new ones. This is especially important during
12250 // boot, where the first config change needs to guarantee
12251 // all resources have that config before following boot
12252 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012253 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012254
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012255 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012256 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012257 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012258 mHandler.sendMessage(msg);
12259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012260
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012261 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12262 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012263 try {
12264 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012265 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012266 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012267 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012268 }
12269 } catch (Exception e) {
12270 }
12271 }
12272 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012273 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12274 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012275 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012276 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012277 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12278 broadcastIntentLocked(null, null,
12279 new Intent(Intent.ACTION_LOCALE_CHANGED),
12280 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012281 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 }
12284 }
12285
12286 if (changes != 0 && starting == null) {
12287 // If the configuration changed, and the caller is not already
12288 // in the process of starting an activity, then find the top
12289 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012290 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012291 }
12292
12293 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012294 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012295 // And we need to make sure at this point that all other activities
12296 // are made visible with the correct configuration.
12297 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012298 }
12299
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012300 if (values != null && mWindowManager != null) {
12301 mWindowManager.setNewConfiguration(mConfiguration);
12302 }
12303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012304 return kept;
12305 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012306
12307 /**
12308 * Decide based on the configuration whether we should shouw the ANR,
12309 * crash, etc dialogs. The idea is that if there is no affordnace to
12310 * press the on-screen buttons, we shouldn't show the dialog.
12311 *
12312 * A thought: SystemUI might also want to get told about this, the Power
12313 * dialog / global actions also might want different behaviors.
12314 */
12315 private static final boolean shouldShowDialogs(Configuration config) {
12316 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12317 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012319
12320 /**
12321 * Save the locale. You must be inside a synchronized (this) block.
12322 */
12323 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12324 if(isDiff) {
12325 SystemProperties.set("user.language", l.getLanguage());
12326 SystemProperties.set("user.region", l.getCountry());
12327 }
12328
12329 if(isPersist) {
12330 SystemProperties.set("persist.sys.language", l.getLanguage());
12331 SystemProperties.set("persist.sys.country", l.getCountry());
12332 SystemProperties.set("persist.sys.localevar", l.getVariant());
12333 }
12334 }
12335
Adam Powelldd8fab22012-03-22 17:47:27 -070012336 @Override
12337 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12338 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012339 return srec != null && srec.task.affinity != null &&
12340 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012341 }
12342
12343 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12344 Intent resultData) {
12345 ComponentName dest = destIntent.getComponent();
12346
12347 synchronized (this) {
12348 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012349 if (srec == null) {
12350 return false;
12351 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012352 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12353 final int start = history.indexOf(srec);
12354 if (start < 0) {
12355 // Current activity is not in history stack; do nothing.
12356 return false;
12357 }
12358 int finishTo = start - 1;
12359 ActivityRecord parent = null;
12360 boolean foundParentInTask = false;
12361 if (dest != null) {
12362 TaskRecord tr = srec.task;
12363 for (int i = start - 1; i >= 0; i--) {
12364 ActivityRecord r = history.get(i);
12365 if (tr != r.task) {
12366 // Couldn't find parent in the same task; stop at the one above this.
12367 // (Root of current task; in-app "home" behavior)
12368 // Always at least finish the current activity.
12369 finishTo = Math.min(start - 1, i + 1);
12370 parent = history.get(finishTo);
12371 break;
12372 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12373 r.info.name.equals(dest.getClassName())) {
12374 finishTo = i;
12375 parent = r;
12376 foundParentInTask = true;
12377 break;
12378 }
12379 }
12380 }
12381
12382 if (mController != null) {
12383 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12384 if (next != null) {
12385 // ask watcher if this is allowed
12386 boolean resumeOK = true;
12387 try {
12388 resumeOK = mController.activityResuming(next.packageName);
12389 } catch (RemoteException e) {
12390 mController = null;
12391 }
12392
12393 if (!resumeOK) {
12394 return false;
12395 }
12396 }
12397 }
12398 final long origId = Binder.clearCallingIdentity();
12399 for (int i = start; i > finishTo; i--) {
12400 ActivityRecord r = history.get(i);
12401 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012402 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012403 // Only return the supplied result for the first activity finished
12404 resultCode = Activity.RESULT_CANCELED;
12405 resultData = null;
12406 }
12407
12408 if (parent != null && foundParentInTask) {
12409 final int parentLaunchMode = parent.info.launchMode;
12410 final int destIntentFlags = destIntent.getFlags();
12411 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12412 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12413 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12414 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012415 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012416 } else {
12417 try {
12418 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012419 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012420 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12421 null, aInfo, parent.appToken, null,
12422 0, -1, parent.launchedFromUid, 0, null, true, null);
12423 foundParentInTask = res == ActivityManager.START_SUCCESS;
12424 } catch (RemoteException e) {
12425 foundParentInTask = false;
12426 }
12427 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012428 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012429 }
12430 }
12431 Binder.restoreCallingIdentity(origId);
12432 return foundParentInTask;
12433 }
12434 }
12435
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012436 public int getLaunchedFromUid(IBinder activityToken) {
12437 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12438 if (srec == null) {
12439 return -1;
12440 }
12441 return srec.launchedFromUid;
12442 }
12443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012444 // =========================================================
12445 // LIFETIME MANAGEMENT
12446 // =========================================================
12447
Christopher Tatef46723b2012-01-26 14:19:24 -080012448 // Returns which broadcast queue the app is the current [or imminent] receiver
12449 // on, or 'null' if the app is not an active broadcast recipient.
12450 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12451 BroadcastRecord r = app.curReceiver;
12452 if (r != null) {
12453 return r.queue;
12454 }
12455
12456 // It's not the current receiver, but it might be starting up to become one
12457 synchronized (this) {
12458 for (BroadcastQueue queue : mBroadcastQueues) {
12459 r = queue.mPendingBroadcast;
12460 if (r != null && r.curApp == app) {
12461 // found it; report which queue it's in
12462 return queue;
12463 }
12464 }
12465 }
12466
12467 return null;
12468 }
12469
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012470 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012471 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012472 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012473 // This adjustment has already been computed. If we are calling
12474 // from the top, we may have already computed our adjustment with
12475 // an earlier hidden adjustment that isn't really for us... if
12476 // so, use the new hidden adjustment.
12477 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012478 if (app.hasActivities) {
12479 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12480 } else if (app.hasClientActivities) {
12481 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12482 } else {
12483 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12484 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012485 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012486 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012487 }
12488
12489 if (app.thread == null) {
12490 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012491 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012492 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012493 }
12494
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012495 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12496 app.adjSource = null;
12497 app.adjTarget = null;
12498 app.empty = false;
12499 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012500 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012501
12502 final int activitiesSize = app.activities.size();
12503
Dianne Hackborn7d608422011-08-07 16:24:18 -070012504 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012505 // The max adjustment doesn't allow this app to be anything
12506 // below foreground, so it is not worth doing work for it.
12507 app.adjType = "fixed";
12508 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012509 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012510 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012511 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012512 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012513 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012514 // System process can do UI, and when they do we want to have
12515 // them trim their memory after the user leaves the UI. To
12516 // facilitate this, here we need to determine whether or not it
12517 // is currently showing UI.
12518 app.systemNoUi = true;
12519 if (app == TOP_APP) {
12520 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012521 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012522 } else if (activitiesSize > 0) {
12523 for (int j = 0; j < activitiesSize; j++) {
12524 final ActivityRecord r = app.activities.get(j);
12525 if (r.visible) {
12526 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012527 }
12528 if (r.app == app) {
12529 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012530 }
12531 }
12532 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012533 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012534 }
12535
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012536 app.keeping = false;
12537 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012538 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539
The Android Open Source Project4df24232009-03-05 14:34:35 -080012540 // Determine the importance of the process, starting with most
12541 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012542 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012543 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012544 boolean foregroundActivities = false;
12545 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012546 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012547 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012548 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012549 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012550 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012551 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012552 foregroundActivities = true;
12553 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012554 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012555 } else if (app.instrumentationClass != null) {
12556 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012557 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012558 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012559 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012560 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012561 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012563 // counts as being in the foreground for OOM killer purposes.
12564 // It's placed in a sched group based on the nature of the
12565 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012566 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012567 schedGroup = (queue == mFgBroadcastQueue)
12568 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012569 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012570 } else if (app.executingServices.size() > 0) {
12571 // An app that is currently executing a service callback also
12572 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012573 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012574 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012575 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012576 } else {
12577 // Assume process is hidden (has activities); we will correct
12578 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012579 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012580 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012581 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012582 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012583 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012584
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012585 boolean hasStoppingActivities = false;
12586
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012587 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012588 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012589 for (int j = 0; j < activitiesSize; j++) {
12590 final ActivityRecord r = app.activities.get(j);
12591 if (r.visible) {
12592 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012593 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12594 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012595 app.adjType = "visible";
12596 }
12597 schedGroup = Process.THREAD_GROUP_DEFAULT;
12598 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012599 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012600 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012601 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012602 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012603 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12604 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012605 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012606 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012607 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012608 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012609 } else if (r.state == ActivityState.STOPPING) {
12610 // We will apply the actual adjustment later, because
12611 // we want to allow this process to immediately go through
12612 // any memory trimming that is in effect.
12613 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012614 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012615 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012616 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012617 if (r.app == app) {
12618 app.hasActivities = true;
12619 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012620 }
12621 }
12622
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012623 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012624 if (app.hasClientActivities) {
12625 adj = clientHiddenAdj;
12626 app.adjType = "bg-client-act";
12627 } else {
12628 // Whoops, this process is completely empty as far as we know
12629 // at this point.
12630 adj = emptyAdj;
12631 app.empty = true;
12632 app.adjType = "bg-empty";
12633 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012634 }
12635
Dianne Hackborn7d608422011-08-07 16:24:18 -070012636 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012637 if (app.foregroundServices) {
12638 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012639 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012640 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012641 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012642 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012643 } else if (app.forcingToForeground != null) {
12644 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012645 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012646 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012647 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012648 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012649 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012650 }
12651 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012652
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012653 if (app.foregroundServices) {
12654 interesting = true;
12655 }
12656
Dianne Hackborn7d608422011-08-07 16:24:18 -070012657 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012658 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012659 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012660 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012661 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012662 app.adjType = "heavy";
12663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664
Dianne Hackborn7d608422011-08-07 16:24:18 -070012665 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012666 // This process is hosting what we currently consider to be the
12667 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012668 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012669 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012670 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012671 app.adjType = "home";
12672 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012673
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012674 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12675 && app.activities.size() > 0) {
12676 // This was the previous process that showed UI to the user.
12677 // We want to try to keep it around more aggressively, to give
12678 // a good experience around switching between two apps.
12679 adj = ProcessList.PREVIOUS_APP_ADJ;
12680 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12681 app.hidden = false;
12682 app.adjType = "previous";
12683 }
12684
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012685 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12686 + " reason=" + app.adjType);
12687
The Android Open Source Project4df24232009-03-05 14:34:35 -080012688 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012689 // there are applications dependent on our services or providers, but
12690 // this gives us a baseline and makes sure we don't get into an
12691 // infinite recursion.
12692 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012693 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012694
Christopher Tate6fa95972009-06-05 18:43:55 -070012695 if (mBackupTarget != null && app == mBackupTarget.app) {
12696 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012697 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012698 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012699 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012700 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012701 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012702 }
12703 }
12704
Dianne Hackborn7d608422011-08-07 16:24:18 -070012705 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012706 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012707 final long now = SystemClock.uptimeMillis();
12708 // This process is more important if the top activity is
12709 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012710 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012711 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012712 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012713 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012714 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012715 // If this process has shown some UI, let it immediately
12716 // go to the LRU list because it may be pretty heavy with
12717 // UI stuff. We'll tag it with a label just to help
12718 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012719 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012720 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012722 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012723 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012724 // This service has seen some activity within
12725 // recent memory, so we will keep its process ahead
12726 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012727 if (adj > ProcessList.SERVICE_ADJ) {
12728 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012729 app.adjType = "started-services";
12730 app.hidden = false;
12731 }
12732 }
12733 // If we have let the service slide into the background
12734 // state, still have some text describing what it is doing
12735 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012736 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012737 app.adjType = "started-bg-services";
12738 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012739 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012740 // Don't kill this process because it is doing work; it
12741 // has said it is doing work.
12742 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012743 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012744 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012745 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012746 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012747 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012748 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012749 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012750 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012751 // XXX should compute this based on the max of
12752 // all connected clients.
12753 ConnectionRecord cr = clist.get(i);
12754 if (cr.binding.client == app) {
12755 // Binding to ourself is not interesting.
12756 continue;
12757 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012758 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012759 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012760 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012761 int myHiddenAdj = hiddenAdj;
12762 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012763 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012764 myHiddenAdj = client.hiddenAdj;
12765 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012766 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012767 }
12768 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012769 int myClientHiddenAdj = clientHiddenAdj;
12770 if (myClientHiddenAdj > client.clientHiddenAdj) {
12771 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12772 myClientHiddenAdj = client.clientHiddenAdj;
12773 } else {
12774 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12775 }
12776 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012777 int myEmptyAdj = emptyAdj;
12778 if (myEmptyAdj > client.emptyAdj) {
12779 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12780 myEmptyAdj = client.emptyAdj;
12781 } else {
12782 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12783 }
12784 }
12785 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012786 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012787 String adjType = null;
12788 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12789 // Not doing bind OOM management, so treat
12790 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012791 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012792 // If this process has shown some UI, let it immediately
12793 // go to the LRU list because it may be pretty heavy with
12794 // UI stuff. We'll tag it with a label just to help
12795 // debug and understand what is going on.
12796 if (adj > clientAdj) {
12797 adjType = "bound-bg-ui-services";
12798 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012799 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012800 clientAdj = adj;
12801 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012802 if (now >= (s.lastActivity
12803 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012804 // This service has not seen activity within
12805 // recent memory, so allow it to drop to the
12806 // LRU list if there is no other reason to keep
12807 // it around. We'll also tag it with a label just
12808 // to help debug and undertand what is going on.
12809 if (adj > clientAdj) {
12810 adjType = "bound-bg-services";
12811 }
12812 clientAdj = adj;
12813 }
12814 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012815 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12816 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12817 // If this connection is keeping the service
12818 // created, then we want to try to better follow
12819 // its memory management semantics for activities.
12820 // That is, if it is sitting in the background
12821 // LRU list as a hidden process (with activities),
12822 // we don't want the service it is connected to
12823 // to go into the empty LRU and quickly get killed,
12824 // because I'll we'll do is just end up restarting
12825 // the service.
12826 app.hasClientActivities |= client.hasActivities;
12827 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012828 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012829 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012830 // If this process has recently shown UI, and
12831 // the process that is binding to it is less
12832 // important than being visible, then we don't
12833 // care about the binding as much as we care
12834 // about letting this process get into the LRU
12835 // list to be killed and restarted if needed for
12836 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012837 if (app.hasShownUi && app != mHomeProcess
12838 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012839 adjType = "bound-bg-ui-services";
12840 } else {
12841 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12842 |Context.BIND_IMPORTANT)) != 0) {
12843 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012844 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12845 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12846 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12847 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12848 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012849 adj = clientAdj;
12850 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012851 app.pendingUiClean = true;
12852 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12853 adj = ProcessList.VISIBLE_APP_ADJ;
12854 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012855 }
12856 if (!client.hidden) {
12857 app.hidden = false;
12858 }
12859 if (client.keeping) {
12860 app.keeping = true;
12861 }
12862 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012863 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012864 }
12865 if (adjType != null) {
12866 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012867 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12868 .REASON_SERVICE_IN_USE;
12869 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012870 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012871 app.adjTarget = s.name;
12872 }
12873 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12874 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12875 schedGroup = Process.THREAD_GROUP_DEFAULT;
12876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012877 }
12878 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012879 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012880 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012881 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012882 (a.visible || a.state == ActivityState.RESUMED
12883 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012884 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012885 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12886 schedGroup = Process.THREAD_GROUP_DEFAULT;
12887 }
12888 app.hidden = false;
12889 app.adjType = "service";
12890 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12891 .REASON_SERVICE_IN_USE;
12892 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012893 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012894 app.adjTarget = s.name;
12895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 }
12898 }
12899 }
12900 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012901
Dianne Hackborn287952c2010-09-22 22:34:31 -070012902 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012903 // would like to avoid killing it unless it would prevent the current
12904 // application from running. By default we put the process in
12905 // with the rest of the background processes; as we scan through
12906 // its services we may bump it up from there.
12907 if (adj > hiddenAdj) {
12908 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012909 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012910 app.adjType = "bg-services";
12911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012912 }
12913
Dianne Hackborn7d608422011-08-07 16:24:18 -070012914 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012915 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012916 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012917 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012918 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012919 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012920 for (int i = cpr.connections.size()-1;
12921 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12922 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12923 i--) {
12924 ContentProviderConnection conn = cpr.connections.get(i);
12925 ProcessRecord client = conn.client;
12926 if (client == app) {
12927 // Being our own client is not interesting.
12928 continue;
12929 }
12930 int myHiddenAdj = hiddenAdj;
12931 if (myHiddenAdj > client.hiddenAdj) {
12932 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12933 myHiddenAdj = client.hiddenAdj;
12934 } else {
12935 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012936 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012937 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012938 int myClientHiddenAdj = clientHiddenAdj;
12939 if (myClientHiddenAdj > client.clientHiddenAdj) {
12940 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
12941 myClientHiddenAdj = client.clientHiddenAdj;
12942 } else {
12943 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
12944 }
12945 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012946 int myEmptyAdj = emptyAdj;
12947 if (myEmptyAdj > client.emptyAdj) {
12948 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12949 myEmptyAdj = client.emptyAdj;
12950 } else {
12951 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12952 }
12953 }
12954 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012955 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012956 if (adj > clientAdj) {
12957 if (app.hasShownUi && app != mHomeProcess
12958 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12959 app.adjType = "bg-ui-provider";
12960 } else {
12961 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12962 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12963 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012965 if (!client.hidden) {
12966 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012968 if (client.keeping) {
12969 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012970 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012971 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12972 .REASON_PROVIDER_IN_USE;
12973 app.adjSource = client;
12974 app.adjSourceOom = clientAdj;
12975 app.adjTarget = cpr.name;
12976 }
12977 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12978 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012979 }
12980 }
12981 // If the provider has external (non-framework) process
12982 // dependencies, ensure that its adjustment is at least
12983 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012984 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012985 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12986 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012987 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012988 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012989 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012990 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012991 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012992 }
12993 }
12994 }
12995 }
12996
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012997 if (adj == ProcessList.SERVICE_ADJ) {
12998 if (doingAll) {
12999 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13000 mNewNumServiceProcs++;
13001 }
13002 if (app.serviceb) {
13003 adj = ProcessList.SERVICE_B_ADJ;
13004 }
13005 } else {
13006 app.serviceb = false;
13007 }
13008
13009 app.nonStoppingAdj = adj;
13010
13011 if (hasStoppingActivities) {
13012 // Only upgrade adjustment.
13013 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13014 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13015 app.adjType = "stopping";
13016 }
13017 }
13018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 app.curRawAdj = adj;
13020
Joe Onorato8a9b2202010-02-26 18:56:32 -080013021 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013022 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13023 if (adj > app.maxAdj) {
13024 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013025 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013026 schedGroup = Process.THREAD_GROUP_DEFAULT;
13027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013029 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013030 app.keeping = true;
13031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013032
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013033 if (app.hasAboveClient) {
13034 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13035 // then we need to drop its adjustment to be lower than the service's
13036 // in order to honor the request. We want to drop it by one adjustment
13037 // level... but there is special meaning applied to various levels so
13038 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013039 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013040 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013041 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13042 adj = ProcessList.VISIBLE_APP_ADJ;
13043 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13044 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13045 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13046 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013047 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013048 adj++;
13049 }
13050 }
13051
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013052 int importance = app.memImportance;
13053 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13054 app.curAdj = adj;
13055 app.curSchedGroup = schedGroup;
13056 if (!interesting) {
13057 // For this reporting, if there is not something explicitly
13058 // interesting in this process then we will push it to the
13059 // background importance.
13060 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13061 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13062 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13063 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13064 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13065 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13066 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13067 } else if (adj >= ProcessList.SERVICE_ADJ) {
13068 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13069 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13070 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13071 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13072 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13073 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13074 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13075 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13076 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13077 } else {
13078 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13079 }
13080 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013081
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013082 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13083 if (foregroundActivities != app.foregroundActivities) {
13084 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13085 }
13086 if (changes != 0) {
13087 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13088 app.memImportance = importance;
13089 app.foregroundActivities = foregroundActivities;
13090 int i = mPendingProcessChanges.size()-1;
13091 ProcessChangeItem item = null;
13092 while (i >= 0) {
13093 item = mPendingProcessChanges.get(i);
13094 if (item.pid == app.pid) {
13095 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13096 break;
13097 }
13098 i--;
13099 }
13100 if (i < 0) {
13101 // No existing item in pending changes; need a new one.
13102 final int NA = mAvailProcessChanges.size();
13103 if (NA > 0) {
13104 item = mAvailProcessChanges.remove(NA-1);
13105 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13106 } else {
13107 item = new ProcessChangeItem();
13108 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13109 }
13110 item.changes = 0;
13111 item.pid = app.pid;
13112 item.uid = app.info.uid;
13113 if (mPendingProcessChanges.size() == 0) {
13114 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13115 "*** Enqueueing dispatch processes changed!");
13116 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13117 }
13118 mPendingProcessChanges.add(item);
13119 }
13120 item.changes |= changes;
13121 item.importance = importance;
13122 item.foregroundActivities = foregroundActivities;
13123 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13124 + Integer.toHexString(System.identityHashCode(item))
13125 + " " + app.toShortString() + ": changes=" + item.changes
13126 + " importance=" + item.importance
13127 + " foreground=" + item.foregroundActivities
13128 + " type=" + app.adjType + " source=" + app.adjSource
13129 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013130 }
13131
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013132 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013133 }
13134
13135 /**
13136 * Ask a given process to GC right now.
13137 */
13138 final void performAppGcLocked(ProcessRecord app) {
13139 try {
13140 app.lastRequestedGc = SystemClock.uptimeMillis();
13141 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013142 if (app.reportLowMemory) {
13143 app.reportLowMemory = false;
13144 app.thread.scheduleLowMemory();
13145 } else {
13146 app.thread.processInBackground();
13147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013148 }
13149 } catch (Exception e) {
13150 // whatever.
13151 }
13152 }
13153
13154 /**
13155 * Returns true if things are idle enough to perform GCs.
13156 */
Josh Bartel7f208742010-02-25 11:01:44 -060013157 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013158 boolean processingBroadcasts = false;
13159 for (BroadcastQueue q : mBroadcastQueues) {
13160 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13161 processingBroadcasts = true;
13162 }
13163 }
13164 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013165 && (mSleeping || (mMainStack.mResumedActivity != null &&
13166 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167 }
13168
13169 /**
13170 * Perform GCs on all processes that are waiting for it, but only
13171 * if things are idle.
13172 */
13173 final void performAppGcsLocked() {
13174 final int N = mProcessesToGc.size();
13175 if (N <= 0) {
13176 return;
13177 }
Josh Bartel7f208742010-02-25 11:01:44 -060013178 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 while (mProcessesToGc.size() > 0) {
13180 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013181 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013182 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13183 <= SystemClock.uptimeMillis()) {
13184 // To avoid spamming the system, we will GC processes one
13185 // at a time, waiting a few seconds between each.
13186 performAppGcLocked(proc);
13187 scheduleAppGcsLocked();
13188 return;
13189 } else {
13190 // It hasn't been long enough since we last GCed this
13191 // process... put it in the list to wait for its time.
13192 addProcessToGcListLocked(proc);
13193 break;
13194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013195 }
13196 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013197
13198 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013199 }
13200 }
13201
13202 /**
13203 * If all looks good, perform GCs on all processes waiting for them.
13204 */
13205 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013206 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 performAppGcsLocked();
13208 return;
13209 }
13210 // Still not idle, wait some more.
13211 scheduleAppGcsLocked();
13212 }
13213
13214 /**
13215 * Schedule the execution of all pending app GCs.
13216 */
13217 final void scheduleAppGcsLocked() {
13218 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013219
13220 if (mProcessesToGc.size() > 0) {
13221 // Schedule a GC for the time to the next process.
13222 ProcessRecord proc = mProcessesToGc.get(0);
13223 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13224
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013225 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013226 long now = SystemClock.uptimeMillis();
13227 if (when < (now+GC_TIMEOUT)) {
13228 when = now + GC_TIMEOUT;
13229 }
13230 mHandler.sendMessageAtTime(msg, when);
13231 }
13232 }
13233
13234 /**
13235 * Add a process to the array of processes waiting to be GCed. Keeps the
13236 * list in sorted order by the last GC time. The process can't already be
13237 * on the list.
13238 */
13239 final void addProcessToGcListLocked(ProcessRecord proc) {
13240 boolean added = false;
13241 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13242 if (mProcessesToGc.get(i).lastRequestedGc <
13243 proc.lastRequestedGc) {
13244 added = true;
13245 mProcessesToGc.add(i+1, proc);
13246 break;
13247 }
13248 }
13249 if (!added) {
13250 mProcessesToGc.add(0, proc);
13251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 }
13253
13254 /**
13255 * Set up to ask a process to GC itself. This will either do it
13256 * immediately, or put it on the list of processes to gc the next
13257 * time things are idle.
13258 */
13259 final void scheduleAppGcLocked(ProcessRecord app) {
13260 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013261 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262 return;
13263 }
13264 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013265 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013266 scheduleAppGcsLocked();
13267 }
13268 }
13269
Dianne Hackborn287952c2010-09-22 22:34:31 -070013270 final void checkExcessivePowerUsageLocked(boolean doKills) {
13271 updateCpuStatsNow();
13272
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013273 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013274 boolean doWakeKills = doKills;
13275 boolean doCpuKills = doKills;
13276 if (mLastPowerCheckRealtime == 0) {
13277 doWakeKills = false;
13278 }
13279 if (mLastPowerCheckUptime == 0) {
13280 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013281 }
13282 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013283 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013284 }
13285 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013286 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13287 final long curUptime = SystemClock.uptimeMillis();
13288 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13289 mLastPowerCheckRealtime = curRealtime;
13290 mLastPowerCheckUptime = curUptime;
13291 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13292 doWakeKills = false;
13293 }
13294 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13295 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013296 }
13297 int i = mLruProcesses.size();
13298 while (i > 0) {
13299 i--;
13300 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013301 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013302 long wtime;
13303 synchronized (stats) {
13304 wtime = stats.getProcessWakeTime(app.info.uid,
13305 app.pid, curRealtime);
13306 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013307 long wtimeUsed = wtime - app.lastWakeTime;
13308 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13309 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013310 StringBuilder sb = new StringBuilder(128);
13311 sb.append("Wake for ");
13312 app.toShortString(sb);
13313 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013314 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013315 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013316 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013317 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013318 sb.append((wtimeUsed*100)/realtimeSince);
13319 sb.append("%)");
13320 Slog.i(TAG, sb.toString());
13321 sb.setLength(0);
13322 sb.append("CPU for ");
13323 app.toShortString(sb);
13324 sb.append(": over ");
13325 TimeUtils.formatDuration(uptimeSince, sb);
13326 sb.append(" used ");
13327 TimeUtils.formatDuration(cputimeUsed, sb);
13328 sb.append(" (");
13329 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013330 sb.append("%)");
13331 Slog.i(TAG, sb.toString());
13332 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013333 // If a process has held a wake lock for more
13334 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013335 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013336 if (doWakeKills && realtimeSince > 0
13337 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13338 synchronized (stats) {
13339 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13340 realtimeSince, wtimeUsed);
13341 }
13342 Slog.w(TAG, "Excessive wake lock in " + app.processName
13343 + " (pid " + app.pid + "): held " + wtimeUsed
13344 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013345 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013346 app.processName, app.setAdj, "excessive wake lock");
13347 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013348 } else if (doCpuKills && uptimeSince > 0
13349 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13350 synchronized (stats) {
13351 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13352 uptimeSince, cputimeUsed);
13353 }
13354 Slog.w(TAG, "Excessive CPU in " + app.processName
13355 + " (pid " + app.pid + "): used " + cputimeUsed
13356 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013357 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013358 app.processName, app.setAdj, "excessive cpu");
13359 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013360 } else {
13361 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013362 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013363 }
13364 }
13365 }
13366 }
13367
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013368 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013369 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013370 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013371 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013372 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013373
13374 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013375 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013376 }
13377
Dianne Hackborn287952c2010-09-22 22:34:31 -070013378 final boolean wasKeeping = app.keeping;
13379
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013380 boolean success = true;
13381
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013382 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013383
Jeff Brown10e89712011-07-08 18:52:57 -070013384 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013385 if (wasKeeping && !app.keeping) {
13386 // This app is no longer something we want to keep. Note
13387 // its current wake lock time to later know to kill it if
13388 // it is not behaving well.
13389 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13390 synchronized (stats) {
13391 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13392 app.pid, SystemClock.elapsedRealtime());
13393 }
13394 app.lastCpuTime = app.curCpuTime;
13395 }
13396
13397 app.setRawAdj = app.curRawAdj;
13398 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013399
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013400 if (app.curAdj != app.setAdj) {
13401 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013402 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013403 TAG, "Set " + app.pid + " " + app.processName +
13404 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013405 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013406 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013407 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013408 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013409 }
13410 }
13411 if (app.setSchedGroup != app.curSchedGroup) {
13412 app.setSchedGroup = app.curSchedGroup;
13413 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13414 "Setting process group of " + app.processName
13415 + " to " + app.curSchedGroup);
13416 if (app.waitingToKill != null &&
13417 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13418 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013419 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013420 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013421 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013422 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013423 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013424 } else {
13425 if (true) {
13426 long oldId = Binder.clearCallingIdentity();
13427 try {
13428 Process.setProcessGroup(app.pid, app.curSchedGroup);
13429 } catch (Exception e) {
13430 Slog.w(TAG, "Failed setting process group of " + app.pid
13431 + " to " + app.curSchedGroup);
13432 e.printStackTrace();
13433 } finally {
13434 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013435 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013436 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013437 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013438 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013439 app.thread.setSchedulingGroup(app.curSchedGroup);
13440 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013441 }
13442 }
13443 }
13444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013445 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013446 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013447 }
13448
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013449 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013450 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013451 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013452 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013453 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013454 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013455 }
13456 }
13457 return resumedActivity;
13458 }
13459
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013460 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013461 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013462 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13463 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013464 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13465 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013466
13467 mAdjSeq++;
13468
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013469 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13470 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013471 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13472 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013473 if (nowHidden != wasHidden) {
13474 // Changed to/from hidden state, so apps after it in the LRU
13475 // list may also be changed.
13476 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013477 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013478 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479 }
13480
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013481 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013482 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013483 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013484 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013485
13486 if (false) {
13487 RuntimeException e = new RuntimeException();
13488 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013489 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013490 }
13491
13492 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013493 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013494
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013495 final int emptyProcessLimit;
13496 final int hiddenProcessLimit;
13497 if (mProcessLimit <= 0) {
13498 emptyProcessLimit = hiddenProcessLimit = 0;
13499 } else if (mProcessLimit == 1) {
13500 emptyProcessLimit = 1;
13501 hiddenProcessLimit = 0;
13502 } else {
13503 emptyProcessLimit = (mProcessLimit*2)/3;
13504 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13505 }
13506
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013507 // Let's determine how many processes we have running vs.
13508 // how many slots we have for background processes; we may want
13509 // to put multiple processes in a slot of there are enough of
13510 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013511 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13512 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013513 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13514 if (numEmptyProcs > hiddenProcessLimit) {
13515 // If there are more empty processes than our limit on hidden
13516 // processes, then use the hidden process limit for the factor.
13517 // This ensures that the really old empty processes get pushed
13518 // down to the bottom, so if we are running low on memory we will
13519 // have a better chance at keeping around more hidden processes
13520 // instead of a gazillion empty processes.
13521 numEmptyProcs = hiddenProcessLimit;
13522 }
13523 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013524 if (emptyFactor < 1) emptyFactor = 1;
13525 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13526 if (hiddenFactor < 1) hiddenFactor = 1;
13527 int stepHidden = 0;
13528 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013529 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013530 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013531 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013532
13533 mNumNonHiddenProcs = 0;
13534 mNumHiddenProcs = 0;
13535
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013536 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013538 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013539 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013540 int nextHiddenAdj = curHiddenAdj+1;
13541 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13542 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013543 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013544 while (i > 0) {
13545 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013546 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013547 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013548 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013549 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013550 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13551 // This process was assigned as a hidden process... step the
13552 // hidden level.
13553 mNumHiddenProcs++;
13554 if (curHiddenAdj != nextHiddenAdj) {
13555 stepHidden++;
13556 if (stepHidden >= hiddenFactor) {
13557 stepHidden = 0;
13558 curHiddenAdj = nextHiddenAdj;
13559 nextHiddenAdj += 2;
13560 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13561 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13562 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013563 if (curClientHiddenAdj <= curHiddenAdj) {
13564 curClientHiddenAdj = curHiddenAdj + 1;
13565 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13566 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13567 }
13568 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013569 }
13570 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013571 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013572 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013573 Slog.i(TAG, "No longer want " + app.processName
13574 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013575 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013576 app.processName, app.setAdj, "too many background");
13577 app.killedBackground = true;
13578 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013579 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013580 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13581 // This process has a client that has activities. We will have
13582 // given it the current hidden adj; here we will just leave it
13583 // without stepping the hidden adj.
13584 curClientHiddenAdj++;
13585 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13586 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13587 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013588 } else {
13589 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13590 // This process was assigned as an empty process... step the
13591 // empty level.
13592 if (curEmptyAdj != nextEmptyAdj) {
13593 stepEmpty++;
13594 if (stepEmpty >= emptyFactor) {
13595 stepEmpty = 0;
13596 curEmptyAdj = nextEmptyAdj;
13597 nextEmptyAdj += 2;
13598 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13599 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13600 }
13601 }
13602 }
13603 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13604 mNumNonHiddenProcs++;
13605 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013606 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13607 && !app.hasClientActivities) {
13608 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13609 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013610 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013611 + " (pid " + app.pid + "): empty for "
13612 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13613 / 1000) + "s");
13614 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13615 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013616 app.killedBackground = true;
13617 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013618 } else {
13619 numEmpty++;
13620 if (numEmpty > emptyProcessLimit) {
13621 Slog.i(TAG, "No longer want " + app.processName
13622 + " (pid " + app.pid + "): empty #" + numEmpty);
13623 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13624 app.processName, app.setAdj, "too many background");
13625 app.killedBackground = true;
13626 Process.killProcessQuiet(app.pid);
13627 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013628 }
13629 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013630 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013631 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013632 // If this is an isolated process, and there are no
13633 // services running in it, then the process is no longer
13634 // needed. We agressively kill these because we can by
13635 // definition not re-use the same process again, and it is
13636 // good to avoid having whatever code was running in them
13637 // left sitting around after no longer needed.
13638 Slog.i(TAG, "Isolated process " + app.processName
13639 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013640 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013641 app.processName, app.setAdj, "isolated not needed");
13642 app.killedBackground = true;
13643 Process.killProcessQuiet(app.pid);
13644 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013645 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13646 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13647 && !app.killedBackground) {
13648 numTrimming++;
13649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013650 }
13651 }
13652
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013653 mNumServiceProcs = mNewNumServiceProcs;
13654
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013655 // Now determine the memory trimming level of background processes.
13656 // Unfortunately we need to start at the back of the list to do this
13657 // properly. We only do this if the number of background apps we
13658 // are managing to keep around is less than half the maximum we desire;
13659 // if we are keeping a good number around, we'll let them use whatever
13660 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013661 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13662 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013663 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013664 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013665 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013666 int minFactor = 2;
13667 if (mHomeProcess != null) minFactor++;
13668 if (mPreviousProcess != null) minFactor++;
13669 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013670 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013671 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013672 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013673 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013674 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013675 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13676 } else {
13677 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13678 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013679 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013680 for (i=0; i<N; i++) {
13681 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013682 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13683 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013684 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013685 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13686 try {
13687 app.thread.scheduleTrimMemory(curLevel);
13688 } catch (RemoteException e) {
13689 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013690 if (false) {
13691 // For now we won't do this; our memory trimming seems
13692 // to be good enough at this point that destroying
13693 // activities causes more harm than good.
13694 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13695 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013696 // Need to do this on its own message because the stack may not
13697 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013698 // For these apps we will also finish their activities
13699 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013700 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013701 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013702 }
13703 }
13704 app.trimMemoryLevel = curLevel;
13705 step++;
13706 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013707 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013708 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013709 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13710 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013711 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013712 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13713 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013714 break;
13715 }
13716 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013717 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013718 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013719 && app.thread != null) {
13720 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013721 app.thread.scheduleTrimMemory(
13722 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013723 } catch (RemoteException e) {
13724 }
13725 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013726 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013727 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013728 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013729 && app.pendingUiClean) {
13730 // If this application is now in the background and it
13731 // had done UI, then give it the special trim level to
13732 // have it free UI resources.
13733 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13734 if (app.trimMemoryLevel < level && app.thread != null) {
13735 try {
13736 app.thread.scheduleTrimMemory(level);
13737 } catch (RemoteException e) {
13738 }
13739 }
13740 app.pendingUiClean = false;
13741 }
13742 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013743 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013744 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013745 } catch (RemoteException e) {
13746 }
13747 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013748 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013749 }
13750 }
13751 } else {
13752 final int N = mLruProcesses.size();
13753 for (i=0; i<N; i++) {
13754 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013755 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013756 && app.pendingUiClean) {
13757 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13758 && app.thread != null) {
13759 try {
13760 app.thread.scheduleTrimMemory(
13761 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13762 } catch (RemoteException e) {
13763 }
13764 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013765 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013766 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013767 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013768 }
13769 }
13770
13771 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013772 // Need to do this on its own message because the stack may not
13773 // be in a consistent state at this point.
13774 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013776 }
13777
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013778 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013779 synchronized (this) {
13780 int i;
13781
13782 // First remove any unused application processes whose package
13783 // has been removed.
13784 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13785 final ProcessRecord app = mRemovedProcesses.get(i);
13786 if (app.activities.size() == 0
13787 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013788 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013789 TAG, "Exiting empty application process "
13790 + app.processName + " ("
13791 + (app.thread != null ? app.thread.asBinder() : null)
13792 + ")\n");
13793 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013794 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013795 app.processName, app.setAdj, "empty");
13796 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013797 } else {
13798 try {
13799 app.thread.scheduleExit();
13800 } catch (Exception e) {
13801 // Ignore exceptions.
13802 }
13803 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013804 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013805 mRemovedProcesses.remove(i);
13806
13807 if (app.persistent) {
13808 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013809 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013810 }
13811 }
13812 }
13813 }
13814
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013815 // Now update the oom adj for all processes.
13816 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 }
13818 }
13819
13820 /** This method sends the specified signal to each of the persistent apps */
13821 public void signalPersistentProcesses(int sig) throws RemoteException {
13822 if (sig != Process.SIGNAL_USR1) {
13823 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13824 }
13825
13826 synchronized (this) {
13827 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13828 != PackageManager.PERMISSION_GRANTED) {
13829 throw new SecurityException("Requires permission "
13830 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13831 }
13832
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013833 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13834 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013835 if (r.thread != null && r.persistent) {
13836 Process.sendSignal(r.pid, sig);
13837 }
13838 }
13839 }
13840 }
13841
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013842 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13843 if (proc == null || proc == mProfileProc) {
13844 proc = mProfileProc;
13845 path = mProfileFile;
13846 profileType = mProfileType;
13847 clearProfilerLocked();
13848 }
13849 if (proc == null) {
13850 return;
13851 }
13852 try {
13853 proc.thread.profilerControl(false, path, null, profileType);
13854 } catch (RemoteException e) {
13855 throw new IllegalStateException("Process disappeared");
13856 }
13857 }
13858
13859 private void clearProfilerLocked() {
13860 if (mProfileFd != null) {
13861 try {
13862 mProfileFd.close();
13863 } catch (IOException e) {
13864 }
13865 }
13866 mProfileApp = null;
13867 mProfileProc = null;
13868 mProfileFile = null;
13869 mProfileType = 0;
13870 mAutoStopProfiler = false;
13871 }
13872
Dianne Hackborn1676c852012-09-10 14:52:30 -070013873 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013874 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013875
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013876 try {
13877 synchronized (this) {
13878 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13879 // its own permission.
13880 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13881 != PackageManager.PERMISSION_GRANTED) {
13882 throw new SecurityException("Requires permission "
13883 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013884 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013885
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013886 if (start && fd == null) {
13887 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013888 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013889
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013890 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013891 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013892 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013893 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013894
13895 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013896 throw new IllegalArgumentException("Unknown process: " + process);
13897 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013898
13899 if (start) {
13900 stopProfilerLocked(null, null, 0);
13901 setProfileApp(proc.info, proc.processName, path, fd, false);
13902 mProfileProc = proc;
13903 mProfileType = profileType;
13904 try {
13905 fd = fd.dup();
13906 } catch (IOException e) {
13907 fd = null;
13908 }
13909 proc.thread.profilerControl(start, path, fd, profileType);
13910 fd = null;
13911 mProfileFd = null;
13912 } else {
13913 stopProfilerLocked(proc, path, profileType);
13914 if (fd != null) {
13915 try {
13916 fd.close();
13917 } catch (IOException e) {
13918 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013919 }
13920 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013921
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013922 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013923 }
13924 } catch (RemoteException e) {
13925 throw new IllegalStateException("Process disappeared");
13926 } finally {
13927 if (fd != null) {
13928 try {
13929 fd.close();
13930 } catch (IOException e) {
13931 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013932 }
13933 }
13934 }
Andy McFadden824c5102010-07-09 16:26:57 -070013935
Dianne Hackborn1676c852012-09-10 14:52:30 -070013936 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070013937 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070013938 userId, true, true, callName, null);
13939 ProcessRecord proc = null;
13940 try {
13941 int pid = Integer.parseInt(process);
13942 synchronized (mPidsSelfLocked) {
13943 proc = mPidsSelfLocked.get(pid);
13944 }
13945 } catch (NumberFormatException e) {
13946 }
13947
13948 if (proc == null) {
13949 HashMap<String, SparseArray<ProcessRecord>> all
13950 = mProcessNames.getMap();
13951 SparseArray<ProcessRecord> procs = all.get(process);
13952 if (procs != null && procs.size() > 0) {
13953 proc = procs.valueAt(0);
13954 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13955 for (int i=1; i<procs.size(); i++) {
13956 ProcessRecord thisProc = procs.valueAt(i);
13957 if (thisProc.userId == userId) {
13958 proc = thisProc;
13959 break;
13960 }
13961 }
13962 }
13963 }
13964 }
13965
13966 return proc;
13967 }
13968
13969 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013970 String path, ParcelFileDescriptor fd) throws RemoteException {
13971
13972 try {
13973 synchronized (this) {
13974 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13975 // its own permission (same as profileControl).
13976 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13977 != PackageManager.PERMISSION_GRANTED) {
13978 throw new SecurityException("Requires permission "
13979 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13980 }
13981
13982 if (fd == null) {
13983 throw new IllegalArgumentException("null fd");
13984 }
13985
Dianne Hackborn1676c852012-09-10 14:52:30 -070013986 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013987 if (proc == null || proc.thread == null) {
13988 throw new IllegalArgumentException("Unknown process: " + process);
13989 }
13990
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013991 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13992 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013993 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13994 throw new SecurityException("Process not debuggable: " + proc);
13995 }
13996 }
13997
13998 proc.thread.dumpHeap(managed, path, fd);
13999 fd = null;
14000 return true;
14001 }
14002 } catch (RemoteException e) {
14003 throw new IllegalStateException("Process disappeared");
14004 } finally {
14005 if (fd != null) {
14006 try {
14007 fd.close();
14008 } catch (IOException e) {
14009 }
14010 }
14011 }
14012 }
14013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014014 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14015 public void monitor() {
14016 synchronized (this) { }
14017 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014018
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014019 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014020 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14021 ProcessRecord processRecord = mLruProcesses.get(i);
14022 try {
14023 if (processRecord.thread != null) {
14024 processRecord.thread.setCoreSettings(settings);
14025 }
14026 } catch (RemoteException re) {
14027 /* ignore */
14028 }
14029 }
14030 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014031
14032 // Multi-user methods
14033
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014034 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070014035 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014036 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14037 != PackageManager.PERMISSION_GRANTED) {
14038 String msg = "Permission Denial: switchUser() from pid="
14039 + Binder.getCallingPid()
14040 + ", uid=" + Binder.getCallingUid()
14041 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14042 Slog.w(TAG, msg);
14043 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014044 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014045
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014046 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014047 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014048 synchronized (this) {
14049 final int oldUserId = mCurrentUserId;
14050 if (oldUserId == userId) {
14051 return true;
14052 }
14053
14054 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14055 if (userInfo == null) {
14056 Slog.w(TAG, "No user info for user #" + userId);
14057 return false;
14058 }
14059
14060 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14061 R.anim.screen_user_enter);
14062
14063 // If the user we are switching to is not currently started, then
14064 // we need to start it now.
14065 if (mStartedUsers.get(userId) == null) {
14066 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014067 updateStartedUserArrayLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014068 }
14069
14070 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014071 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014072 final Integer userIdInt = Integer.valueOf(userId);
14073 mUserLru.remove(userIdInt);
14074 mUserLru.add(userIdInt);
14075
Craig Mautnerf1b67412012-09-19 13:18:29 -070014076 mWindowManager.setCurrentUser(userId);
14077
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014078 final UserStartedState uss = mStartedUsers.get(userId);
14079
14080 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14081 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14082 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14083 oldUserId, userId, uss));
14084 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14085 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
14086 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14087 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14088 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);
14096 broadcastIntentLocked(null, null, intent, null,
14097 new IIntentReceiver.Stub() {
14098 public void performReceive(Intent intent, int resultCode,
14099 String data, Bundle extras, boolean ordered,
14100 boolean sticky, int sendingUser) {
14101 synchronized (ActivityManagerService.this) {
14102 getUserManagerLocked().makeInitialized(userInfo.id);
14103 }
14104 }
14105 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14106 userId);
14107 } 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);
14133 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14134 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14135 broadcastIntentLocked(null, null, intent,
14136 null, null, 0, null, null, null,
14137 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14138 }
14139 if (newUserId >= 0) {
14140 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
14141 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14142 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14143 broadcastIntentLocked(null, null, intent,
14144 null, null, 0, null, null, null,
14145 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14146 intent = new Intent(Intent.ACTION_USER_SWITCHED);
14147 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14148 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14149 broadcastIntentLocked(null, null, intent,
14150 null, null, 0, null, null,
14151 android.Manifest.permission.MANAGE_USERS,
14152 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14153 }
14154 } finally {
14155 Binder.restoreCallingIdentity(ident);
14156 }
14157 }
14158
14159 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14160 final int newUserId) {
14161 final int N = mUserSwitchObservers.beginBroadcast();
14162 if (N > 0) {
14163 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14164 int mCount = 0;
14165 @Override
14166 public void sendResult(Bundle data) throws RemoteException {
14167 synchronized (ActivityManagerService.this) {
14168 if (mCurUserSwitchCallback == this) {
14169 mCount++;
14170 if (mCount == N) {
14171 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14172 }
14173 }
14174 }
14175 }
14176 };
14177 synchronized (this) {
14178 mCurUserSwitchCallback = callback;
14179 }
14180 for (int i=0; i<N; i++) {
14181 try {
14182 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14183 newUserId, callback);
14184 } catch (RemoteException e) {
14185 }
14186 }
14187 } else {
14188 synchronized (this) {
14189 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14190 }
14191 }
14192 mUserSwitchObservers.finishBroadcast();
14193 }
14194
14195 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14196 synchronized (this) {
14197 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14198 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14199 }
14200 }
14201
14202 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14203 mCurUserSwitchCallback = null;
14204 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14205 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14206 oldUserId, newUserId, uss));
14207 }
14208
14209 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14210 final int N = mUserSwitchObservers.beginBroadcast();
14211 for (int i=0; i<N; i++) {
14212 try {
14213 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14214 } catch (RemoteException e) {
14215 }
14216 }
14217 mUserSwitchObservers.finishBroadcast();
14218 synchronized (this) {
14219 mWindowManager.stopFreezingScreen();
14220 }
14221 }
14222
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014223 void finishUserSwitch(UserStartedState uss) {
14224 synchronized (this) {
14225 if (uss.mState == UserStartedState.STATE_BOOTING
14226 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14227 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014228 final int userId = uss.mHandle.getIdentifier();
14229 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14230 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14231 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014232 null, null, 0, null, null,
14233 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014234 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014235 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014236 int num = mUserLru.size();
14237 int i = 0;
14238 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14239 Integer oldUserId = mUserLru.get(i);
14240 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14241 if (oldUss == null) {
14242 // Shouldn't happen, but be sane if it does.
14243 mUserLru.remove(i);
14244 num--;
14245 continue;
14246 }
14247 if (oldUss.mState == UserStartedState.STATE_STOPPING) {
14248 // This user is already stopping, doesn't count.
14249 num--;
14250 i++;
14251 continue;
14252 }
14253 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14254 // Owner and current can't be stopped, but count as running.
14255 i++;
14256 continue;
14257 }
14258 // This is a user to be stopped.
14259 stopUserLocked(oldUserId, null);
14260 num--;
14261 i++;
14262 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014263 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014264 }
14265
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014266 @Override
14267 public int stopUser(final int userId, final IStopUserCallback callback) {
14268 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14269 != PackageManager.PERMISSION_GRANTED) {
14270 String msg = "Permission Denial: switchUser() from pid="
14271 + Binder.getCallingPid()
14272 + ", uid=" + Binder.getCallingUid()
14273 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14274 Slog.w(TAG, msg);
14275 throw new SecurityException(msg);
14276 }
14277 if (userId <= 0) {
14278 throw new IllegalArgumentException("Can't stop primary user " + userId);
14279 }
Amith Yamasani13593602012-03-22 16:16:17 -070014280 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014281 return stopUserLocked(userId, callback);
14282 }
14283 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014284
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014285 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14286 if (mCurrentUserId == userId) {
14287 return ActivityManager.USER_OP_IS_CURRENT;
14288 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014289
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014290 final UserStartedState uss = mStartedUsers.get(userId);
14291 if (uss == null) {
14292 // User is not started, nothing to do... but we do need to
14293 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014294 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014295 mHandler.post(new Runnable() {
14296 @Override
14297 public void run() {
14298 try {
14299 callback.userStopped(userId);
14300 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014301 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014302 }
14303 });
14304 }
14305 return ActivityManager.USER_OP_SUCCESS;
14306 }
14307
14308 if (callback != null) {
14309 uss.mStopCallbacks.add(callback);
14310 }
14311
14312 if (uss.mState != UserStartedState.STATE_STOPPING) {
14313 uss.mState = UserStartedState.STATE_STOPPING;
14314
14315 long ident = Binder.clearCallingIdentity();
14316 try {
14317 // Inform of user switch
14318 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
14319 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
14320 @Override
14321 public void performReceive(Intent intent, int resultCode, String data,
14322 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14323 finishUserStop(uss);
14324 }
14325 };
14326 broadcastIntentLocked(null, null, intent,
14327 null, resultReceiver, 0, null, null, null,
14328 true, false, MY_PID, Process.SYSTEM_UID, userId);
14329 } finally {
14330 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014331 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014332 }
Amith Yamasani13593602012-03-22 16:16:17 -070014333
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014334 return ActivityManager.USER_OP_SUCCESS;
14335 }
14336
14337 void finishUserStop(UserStartedState uss) {
14338 final int userId = uss.mHandle.getIdentifier();
14339 boolean stopped;
14340 ArrayList<IStopUserCallback> callbacks;
14341 synchronized (this) {
14342 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
14343 if (uss.mState != UserStartedState.STATE_STOPPING
14344 || mStartedUsers.get(userId) != uss) {
14345 stopped = false;
14346 } else {
14347 stopped = true;
14348 // User can no longer run.
14349 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014350 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014351 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014352
14353 // Clean up all state and processes associated with the user.
14354 // Kill all the processes for the user.
14355 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014356 }
14357 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014358
14359 for (int i=0; i<callbacks.size(); i++) {
14360 try {
14361 if (stopped) callbacks.get(i).userStopped(userId);
14362 else callbacks.get(i).userStopAborted(userId);
14363 } catch (RemoteException e) {
14364 }
14365 }
14366 }
14367
14368 @Override
14369 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014370 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14371 != PackageManager.PERMISSION_GRANTED) && (
14372 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14373 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014374 String msg = "Permission Denial: getCurrentUser() from pid="
14375 + Binder.getCallingPid()
14376 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014377 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014378 Slog.w(TAG, msg);
14379 throw new SecurityException(msg);
14380 }
14381 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014382 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014383 }
Amith Yamasani13593602012-03-22 16:16:17 -070014384 }
14385
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014386 int getCurrentUserIdLocked() {
14387 return mCurrentUserId;
14388 }
14389
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014390 @Override
14391 public boolean isUserRunning(int userId) {
14392 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14393 != PackageManager.PERMISSION_GRANTED) {
14394 String msg = "Permission Denial: isUserRunning() from pid="
14395 + Binder.getCallingPid()
14396 + ", uid=" + Binder.getCallingUid()
14397 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14398 Slog.w(TAG, msg);
14399 throw new SecurityException(msg);
14400 }
14401 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014402 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014403 }
14404 }
14405
Dianne Hackborn1676c852012-09-10 14:52:30 -070014406 boolean isUserRunningLocked(int userId) {
14407 UserStartedState state = mStartedUsers.get(userId);
14408 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014409 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014410
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014411 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014412 public int[] getRunningUserIds() {
14413 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14414 != PackageManager.PERMISSION_GRANTED) {
14415 String msg = "Permission Denial: isUserRunning() from pid="
14416 + Binder.getCallingPid()
14417 + ", uid=" + Binder.getCallingUid()
14418 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14419 Slog.w(TAG, msg);
14420 throw new SecurityException(msg);
14421 }
14422 synchronized (this) {
14423 return mStartedUserArray;
14424 }
14425 }
14426
14427 private void updateStartedUserArrayLocked() {
14428 mStartedUserArray = new int[mStartedUsers.size()];
14429 for (int i=0; i<mStartedUsers.size(); i++) {
14430 mStartedUserArray[i] = mStartedUsers.keyAt(i);
14431 }
14432 }
14433
14434 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014435 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14436 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14437 != PackageManager.PERMISSION_GRANTED) {
14438 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14439 + Binder.getCallingPid()
14440 + ", uid=" + Binder.getCallingUid()
14441 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14442 Slog.w(TAG, msg);
14443 throw new SecurityException(msg);
14444 }
14445
14446 mUserSwitchObservers.register(observer);
14447 }
14448
14449 @Override
14450 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14451 mUserSwitchObservers.unregister(observer);
14452 }
14453
Dianne Hackborn1676c852012-09-10 14:52:30 -070014454 private boolean userExists(int userId) {
14455 if (userId == 0) {
14456 return true;
14457 }
14458 UserManagerService ums = getUserManagerLocked();
14459 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14460 }
14461
14462 int[] getUsersLocked() {
14463 UserManagerService ums = getUserManagerLocked();
14464 return ums != null ? ums.getUserIds() : new int[] { 0 };
14465 }
14466
14467 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014468 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014469 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14470 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014471 }
14472 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014473 }
14474
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014475 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014476 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014477
14478 throw new SecurityException("Caller uid=" + uid
14479 + " is not privileged to communicate with user=" + userId);
14480 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014481
14482 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014483 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014484 }
14485
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014486 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014487 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014488 ApplicationInfo newInfo = new ApplicationInfo(info);
14489 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014490 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14491 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014492 return newInfo;
14493 }
14494
14495 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014496 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014497 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014498 return aInfo;
14499 }
14500
14501 ActivityInfo info = new ActivityInfo(aInfo);
14502 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14503 return info;
14504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014505}