blob: b8072b3d9e718c8f2ae341f496df8c3b9c4c08c5 [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 Hackborn287952c2010-09-22 22:34:31 -0700150import java.util.Collections;
151import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152import java.util.HashMap;
153import java.util.HashSet;
154import java.util.Iterator;
155import java.util.List;
156import java.util.Locale;
157import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700158import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700159import java.util.concurrent.atomic.AtomicBoolean;
160import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700162public final class ActivityManagerService extends ActivityManagerNative
163 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700166 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400168 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean DEBUG_SWITCH = localLOGV || false;
170 static final boolean DEBUG_TASKS = localLOGV || false;
171 static final boolean DEBUG_PAUSE = localLOGV || false;
172 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
173 static final boolean DEBUG_TRANSITION = localLOGV || false;
174 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800175 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700176 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700178 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 static final boolean DEBUG_VISBILITY = localLOGV || false;
180 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700181 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700182 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800183 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700185 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700186 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700187 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700188 static final boolean DEBUG_POWER = localLOGV || false;
189 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700190 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 static final boolean VALIDATE_TOKENS = false;
192 static final boolean SHOW_ACTIVITY_START_TIME = true;
193
194 // Control over CPU and battery monitoring.
195 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
196 static final boolean MONITOR_CPU_USAGE = true;
197 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
198 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
199 static final boolean MONITOR_THREAD_CPU_USAGE = false;
200
Dianne Hackborn1655be42009-05-08 14:29:01 -0700201 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700202 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700203
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800204 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700206 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 // Maximum number of recent tasks that we can remember.
209 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700210
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700211 // Amount of time after a call to stopAppSwitches() during which we will
212 // prevent further untrusted switches from happening.
213 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real.
217 static final int PROC_START_TIMEOUT = 10*1000;
218
Jeff Brown3f9dd282011-07-08 20:02:19 -0700219 // How long we wait for a launched process to attach to the activity manager
220 // before we decide it's never going to come up for real, when the process was
221 // started with a wrapper for instrumentation (such as Valgrind) because it
222 // could take much longer than usual.
223 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 // How long to wait after going idle before forcing apps to GC.
226 static final int GC_TIMEOUT = 5*1000;
227
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700228 // The minimum amount of time between successive GC requests for a process.
229 static final int GC_MIN_INTERVAL = 60*1000;
230
Dianne Hackborn287952c2010-09-22 22:34:31 -0700231 // The rate at which we check for apps using excessive power -- 15 mins.
232 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on wake locks to start killing things.
236 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
237
238 // The minimum sample duration we will allow before deciding we have
239 // enough data on CPU usage to start killing things.
240 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800243 static final int BROADCAST_FG_TIMEOUT = 10*1000;
244 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // How long we wait until we timeout on key dispatching.
247 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // How long we wait until we timeout on key dispatching during instrumentation.
250 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
251
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700252 // Amount of time we wait for observers to handle a user switch before
253 // giving up on them and unfreezing the screen.
254 static final int USER_SWITCH_TIMEOUT = 2*1000;
255
Dan Egnor42471dd2010-01-07 17:25:22 -0800256 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257
258 static final String[] EMPTY_STRING_ARRAY = new String[0];
259
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700260 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700261
262 private final boolean mHeadless;
263
Joe Onorato54a4a412011-11-02 20:50:08 -0700264 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
265 // default actuion automatically. Important for devices without direct input
266 // devices.
267 private boolean mShowDialogs = true;
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700270 * Description of a request to start a new activity, which has been held
271 * due to app switches being disabled.
272 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700273 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700274 ActivityRecord r;
275 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700276 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700277 }
278
279 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
280 = new ArrayList<PendingActivityLaunch>();
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800283 BroadcastQueue mFgBroadcastQueue;
284 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800285 // Convenient for easy iteration over the queues. Foreground is first
286 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800287 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800288
289 BroadcastQueue broadcastQueueForIntent(Intent intent) {
290 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
291 if (DEBUG_BACKGROUND_BROADCAST) {
292 Slog.i(TAG, "Broadcast intent " + intent + " on "
293 + (isFg ? "foreground" : "background")
294 + " queue");
295 }
296 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
297 }
298
299 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
300 for (BroadcastQueue queue : mBroadcastQueues) {
301 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
302 if (r != null) {
303 return r;
304 }
305 }
306 return null;
307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308
309 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 * Activity we have told the window manager to have key focus.
311 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700312 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700313 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 * List of intents that were used to start the most recent tasks.
315 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700316 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317
318 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700319 * Process management.
320 */
321 final ProcessList mProcessList = new ProcessList();
322
323 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 * All of the applications we currently have running organized by name.
325 * The keys are strings of the application package name (as
326 * returned by the package manager), and the keys are ApplicationRecord
327 * objects.
328 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700329 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330
331 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800332 * The currently running isolated processes.
333 */
334 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
335
336 /**
337 * Counter for assigning isolated process uids, to avoid frequently reusing the
338 * same ones.
339 */
340 int mNextIsolatedProcessUid = 0;
341
342 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700343 * The currently running heavy-weight process, if any.
344 */
345 ProcessRecord mHeavyWeightProcess = null;
346
347 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 * The last time that various processes have crashed.
349 */
350 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
351
352 /**
353 * Set of applications that we consider to be bad, and will reject
354 * incoming broadcasts from (which the user has no control over).
355 * Processes are added to this set when they have crashed twice within
356 * a minimum amount of time; they are removed from it when they are
357 * later restarted (hopefully due to some user action). The value is the
358 * time it was added to the list.
359 */
360 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
361
362 /**
363 * All of the processes we currently have running organized by pid.
364 * The keys are the pid running the application.
365 *
366 * <p>NOTE: This object is protected by its own lock, NOT the global
367 * activity manager lock!
368 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700369 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370
371 /**
372 * All of the processes that have been forced to be foreground. The key
373 * is the pid of the caller who requested it (we hold a death
374 * link on it).
375 */
376 abstract class ForegroundToken implements IBinder.DeathRecipient {
377 int pid;
378 IBinder token;
379 }
380 final SparseArray<ForegroundToken> mForegroundProcesses
381 = new SparseArray<ForegroundToken>();
382
383 /**
384 * List of records for processes that someone had tried to start before the
385 * system was ready. We don't start them at that point, but ensure they
386 * are started by the time booting is complete.
387 */
388 final ArrayList<ProcessRecord> mProcessesOnHold
389 = new ArrayList<ProcessRecord>();
390
391 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 * List of persistent applications that are in the process
393 * of being started.
394 */
395 final ArrayList<ProcessRecord> mPersistentStartingProcesses
396 = new ArrayList<ProcessRecord>();
397
398 /**
399 * Processes that are being forcibly torn down.
400 */
401 final ArrayList<ProcessRecord> mRemovedProcesses
402 = new ArrayList<ProcessRecord>();
403
404 /**
405 * List of running applications, sorted by recent usage.
406 * The first entry in the list is the least recently used.
407 * It contains ApplicationRecord objects. This list does NOT include
408 * any persistent application records (since we never want to exit them).
409 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800410 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 = new ArrayList<ProcessRecord>();
412
413 /**
414 * List of processes that should gc as soon as things are idle.
415 */
416 final ArrayList<ProcessRecord> mProcessesToGc
417 = new ArrayList<ProcessRecord>();
418
419 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800420 * This is the process holding what we currently consider to be
421 * the "home" activity.
422 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700423 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800424
425 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700426 * This is the process holding the activity the user last visited that
427 * is in a different process from the one they are currently in.
428 */
429 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800430
431 /**
432 * The time at which the previous process was last visible.
433 */
434 long mPreviousProcessVisibleTime;
435
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700436 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700437 * Which uses have been started, so are allowed to run code.
438 */
439 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
440
441 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700442 * LRU list of history of current users. Most recently current is at the end.
443 */
444 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
445
446 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700447 * Registered observers of the user switching mechanics.
448 */
449 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
450 = new RemoteCallbackList<IUserSwitchObserver>();
451
452 /**
453 * Currently active user switch.
454 */
455 Object mCurUserSwitchCallback;
456
457 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458 * Packages that the user has asked to have run in screen size
459 * compatibility mode instead of filling the screen.
460 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700461 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400462
463 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 * Set of PendingResultRecord objects that are currently active.
465 */
466 final HashSet mPendingResultRecords = new HashSet();
467
468 /**
469 * Set of IntentSenderRecord objects that are currently active.
470 */
471 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
472 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
473
474 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800475 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700476 * already logged DropBox entries for. Guarded by itself. If
477 * something (rogue user app) forces this over
478 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
479 */
480 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
481 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
482
483 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700484 * Strict Mode background batched logging state.
485 *
486 * The string buffer is guarded by itself, and its lock is also
487 * used to determine if another batched write is already
488 * in-flight.
489 */
490 private final StringBuilder mStrictModeBuffer = new StringBuilder();
491
492 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 * Keeps track of all IIntentReceivers that have been registered for
494 * broadcasts. Hash keys are the receiver IBinder, hash value is
495 * a ReceiverList.
496 */
497 final HashMap mRegisteredReceivers = new HashMap();
498
499 /**
500 * Resolver for broadcast intents to registered receivers.
501 * Holds BroadcastFilter (subclass of IntentFilter).
502 */
503 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
504 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
505 @Override
506 protected boolean allowFilterResult(
507 BroadcastFilter filter, List<BroadcastFilter> dest) {
508 IBinder target = filter.receiverList.receiver.asBinder();
509 for (int i=dest.size()-1; i>=0; i--) {
510 if (dest.get(i).receiverList.receiver.asBinder() == target) {
511 return false;
512 }
513 }
514 return true;
515 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700516
517 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700518 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700519 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
520 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700521 return super.newResult(filter, match, userId);
522 }
523 return null;
524 }
525
526 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700527 protected BroadcastFilter[] newArray(int size) {
528 return new BroadcastFilter[size];
529 }
530
531 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700532 protected String packageForFilter(BroadcastFilter filter) {
533 return filter.packageName;
534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 };
536
537 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700538 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700540 * that action (which should usually be one). The SparseArray is keyed
541 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
542 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700544 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
545 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700547 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548
549 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700550 * Backup/restore process management
551 */
552 String mBackupAppName = null;
553 BackupRecord mBackupTarget = null;
554
555 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 * List of PendingThumbnailsRecord objects of clients who are still
557 * waiting to receive all of the thumbnails for a task.
558 */
559 final ArrayList mPendingThumbnails = new ArrayList();
560
561 /**
562 * List of HistoryRecord objects that have been finished and must
563 * still report back to a pending thumbnail receiver.
564 */
565 final ArrayList mCancelledThumbnails = new ArrayList();
566
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700567 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 /**
570 * List of content providers who have clients waiting for them. The
571 * application is currently being launched and the provider will be
572 * removed from this list once it is published.
573 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700574 final ArrayList<ContentProviderRecord> mLaunchingProviders
575 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576
577 /**
578 * Global set of specific Uri permissions that have been granted.
579 */
580 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
581 = new SparseArray<HashMap<Uri, UriPermission>>();
582
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800583 CoreSettingsObserver mCoreSettingsObserver;
584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 /**
586 * Thread-local storage used to carry caller permissions over through
587 * indirect content-provider access.
588 * @see #ActivityManagerService.openContentUri()
589 */
590 private class Identity {
591 public int pid;
592 public int uid;
593
594 Identity(int _pid, int _uid) {
595 pid = _pid;
596 uid = _uid;
597 }
598 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
601
602 /**
603 * All information we have collected about the runtime performance of
604 * any user id that can impact battery performance.
605 */
606 final BatteryStatsService mBatteryStatsService;
607
608 /**
609 * information about component usage
610 */
611 final UsageStatsService mUsageStatsService;
612
613 /**
614 * Current configuration information. HistoryRecord objects are given
615 * a reference to this object to indicate which configuration they are
616 * currently running in, so this object must be kept immutable.
617 */
618 Configuration mConfiguration = new Configuration();
619
620 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800621 * Current sequencing integer of the configuration, for skipping old
622 * configurations.
623 */
624 int mConfigurationSeq = 0;
625
626 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700627 * Hardware-reported OpenGLES version.
628 */
629 final int GL_ES_VERSION;
630
631 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 * List of initialization arguments to pass to all processes when binding applications to them.
633 * For example, references to the commonly used services.
634 */
635 HashMap<String, IBinder> mAppBindArgs;
636
637 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700638 * Temporary to avoid allocations. Protected by main lock.
639 */
640 final StringBuilder mStringBuilder = new StringBuilder(256);
641
642 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 * Used to control how we initialize the service.
644 */
645 boolean mStartRunning = false;
646 ComponentName mTopComponent;
647 String mTopAction;
648 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700649 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 boolean mSystemReady = false;
651 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700652 boolean mWaitingUpdate = false;
653 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700654 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700655 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656
657 Context mContext;
658
659 int mFactoryTest;
660
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700661 boolean mCheckedForSetup;
662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700664 * The time at which we will allow normal application switches again,
665 * after a call to {@link #stopAppSwitches()}.
666 */
667 long mAppSwitchesAllowedTime;
668
669 /**
670 * This is set to true after the first switch after mAppSwitchesAllowedTime
671 * is set; any switches after that will clear the time.
672 */
673 boolean mDidAppSwitch;
674
675 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700676 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700677 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700678 long mLastPowerCheckRealtime;
679
680 /**
681 * Last time (in uptime) at which we checked for power usage.
682 */
683 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700684
685 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 * Set while we are wanting to sleep, to prevent any
687 * activities from being started/resumed.
688 */
689 boolean mSleeping = false;
690
691 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700692 * State of external calls telling us if the device is asleep.
693 */
694 boolean mWentToSleep = false;
695
696 /**
697 * State of external call telling us if the lock screen is shown.
698 */
699 boolean mLockScreenShown = false;
700
701 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700702 * Set if we are shutting down the system, similar to sleeping.
703 */
704 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705
706 /**
707 * Task identifier that activities are currently being started
708 * in. Incremented each time a new task is created.
709 * todo: Replace this with a TokenSpace class that generates non-repeating
710 * integers that won't wrap.
711 */
712 int mCurTask = 1;
713
714 /**
715 * Current sequence id for oom_adj computation traversal.
716 */
717 int mAdjSeq = 0;
718
719 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700720 * Current sequence id for process LRU updating.
721 */
722 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723
724 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700725 * Keep track of the non-hidden/empty process we last found, to help
726 * determine how to distribute hidden/empty processes next time.
727 */
728 int mNumNonHiddenProcs = 0;
729
730 /**
731 * Keep track of the number of hidden procs, to balance oom adj
732 * distribution between those and empty procs.
733 */
734 int mNumHiddenProcs = 0;
735
736 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700737 * Keep track of the number of service processes we last found, to
738 * determine on the next iteration which should be B services.
739 */
740 int mNumServiceProcs = 0;
741 int mNewNumServiceProcs = 0;
742
743 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 * System monitoring: number of processes that died since the last
745 * N procs were started.
746 */
747 int[] mProcDeaths = new int[20];
748
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700749 /**
750 * This is set if we had to do a delayed dexopt of an app before launching
751 * it, to increasing the ANR timeouts in that case.
752 */
753 boolean mDidDexOpt;
754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 String mDebugApp = null;
756 boolean mWaitForDebugger = false;
757 boolean mDebugTransient = false;
758 String mOrigDebugApp = null;
759 boolean mOrigWaitForDebugger = false;
760 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700761 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700762 String mProfileApp = null;
763 ProcessRecord mProfileProc = null;
764 String mProfileFile;
765 ParcelFileDescriptor mProfileFd;
766 int mProfileType = 0;
767 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800768 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700770 static class ProcessChangeItem {
771 static final int CHANGE_ACTIVITIES = 1<<0;
772 static final int CHANGE_IMPORTANCE= 1<<1;
773 int changes;
774 int uid;
775 int pid;
776 int importance;
777 boolean foregroundActivities;
778 }
779
Jeff Sharkeya4620792011-05-20 15:29:23 -0700780 final RemoteCallbackList<IProcessObserver> mProcessObservers
781 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700782 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
783
784 final ArrayList<ProcessChangeItem> mPendingProcessChanges
785 = new ArrayList<ProcessChangeItem>();
786 final ArrayList<ProcessChangeItem> mAvailProcessChanges
787 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 /**
790 * Callback of last caller to {@link #requestPss}.
791 */
792 Runnable mRequestPssCallback;
793
794 /**
795 * Remaining processes for which we are waiting results from the last
796 * call to {@link #requestPss}.
797 */
798 final ArrayList<ProcessRecord> mRequestPssList
799 = new ArrayList<ProcessRecord>();
800
801 /**
802 * Runtime statistics collection thread. This object's lock is used to
803 * protect all related state.
804 */
805 final Thread mProcessStatsThread;
806
807 /**
808 * Used to collect process stats when showing not responding dialog.
809 * Protected by mProcessStatsThread.
810 */
811 final ProcessStats mProcessStats = new ProcessStats(
812 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700813 final AtomicLong mLastCpuTime = new AtomicLong(0);
814 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 long mLastWriteTime = 0;
817
818 /**
819 * Set to true after the system has finished booting.
820 */
821 boolean mBooted = false;
822
Dianne Hackborn7d608422011-08-07 16:24:18 -0700823 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700824 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825
826 WindowManagerService mWindowManager;
827
828 static ActivityManagerService mSelf;
829 static ActivityThread mSystemThread;
830
Amith Yamasani258848d2012-08-10 17:06:33 -0700831 private int mCurrentUserId;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700832 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 private final class AppDeathRecipient implements IBinder.DeathRecipient {
835 final ProcessRecord mApp;
836 final int mPid;
837 final IApplicationThread mAppThread;
838
839 AppDeathRecipient(ProcessRecord app, int pid,
840 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800841 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 TAG, "New death recipient " + this
843 + " for thread " + thread.asBinder());
844 mApp = app;
845 mPid = pid;
846 mAppThread = thread;
847 }
848
849 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800850 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 TAG, "Death received in " + this
852 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 synchronized(ActivityManagerService.this) {
854 appDiedLocked(mApp, mPid, mAppThread);
855 }
856 }
857 }
858
859 static final int SHOW_ERROR_MSG = 1;
860 static final int SHOW_NOT_RESPONDING_MSG = 2;
861 static final int SHOW_FACTORY_ERROR_MSG = 3;
862 static final int UPDATE_CONFIGURATION_MSG = 4;
863 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
864 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 static final int SERVICE_TIMEOUT_MSG = 12;
866 static final int UPDATE_TIME_ZONE = 13;
867 static final int SHOW_UID_ERROR_MSG = 14;
868 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700870 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700871 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800872 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700873 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
874 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700875 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700876 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700877 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700878 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700879 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700880 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700881 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700882 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700883 static final int REPORT_USER_SWITCH_MSG = 34;
884 static final int CONTINUE_USER_SWITCH_MSG = 35;
885 static final int USER_SWITCH_TIMEOUT_MSG = 36;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800887 static final int FIRST_ACTIVITY_STACK_MSG = 100;
888 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
889 static final int FIRST_COMPAT_MODE_MSG = 300;
890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700892 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700893 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894
895 final Handler mHandler = new Handler() {
896 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800897 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 //}
899
900 public void handleMessage(Message msg) {
901 switch (msg.what) {
902 case SHOW_ERROR_MSG: {
903 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 synchronized (ActivityManagerService.this) {
905 ProcessRecord proc = (ProcessRecord)data.get("app");
906 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800907 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 return;
909 }
910 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700911 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800912 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 d.show();
914 proc.crashDialog = d;
915 } else {
916 // The device is asleep, so just pretend that the user
917 // saw a crash dialog and hit "force quit".
918 res.set(0);
919 }
920 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700921
922 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 } break;
924 case SHOW_NOT_RESPONDING_MSG: {
925 synchronized (ActivityManagerService.this) {
926 HashMap data = (HashMap) msg.obj;
927 ProcessRecord proc = (ProcessRecord)data.get("app");
928 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800929 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 return;
931 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800932
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700933 Intent intent = new Intent("android.intent.action.ANR");
934 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800935 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
936 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700937 }
938 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800939 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700940 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800941
Justin Kohbc52ca22012-03-29 15:11:44 -0700942 if (mShowDialogs) {
943 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700944 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700945 d.show();
946 proc.anrDialog = d;
947 } else {
948 // Just kill the app if there is no dialog to be shown.
949 killAppAtUsersRequest(proc, null);
950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700952
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700953 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700955 case SHOW_STRICT_MODE_VIOLATION_MSG: {
956 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
957 synchronized (ActivityManagerService.this) {
958 ProcessRecord proc = (ProcessRecord) data.get("app");
959 if (proc == null) {
960 Slog.e(TAG, "App not found when showing strict mode dialog.");
961 break;
962 }
963 if (proc.crashDialog != null) {
964 Slog.e(TAG, "App already has strict mode dialog: " + proc);
965 return;
966 }
967 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700968 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700969 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
970 d.show();
971 proc.crashDialog = d;
972 } else {
973 // The device is asleep, so just pretend that the user
974 // saw a crash dialog and hit "force quit".
975 res.set(0);
976 }
977 }
978 ensureBootCompleted();
979 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 case SHOW_FACTORY_ERROR_MSG: {
981 Dialog d = new FactoryErrorDialog(
982 mContext, msg.getData().getCharSequence("msg"));
983 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700984 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 } break;
986 case UPDATE_CONFIGURATION_MSG: {
987 final ContentResolver resolver = mContext.getContentResolver();
988 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
989 } break;
990 case GC_BACKGROUND_PROCESSES_MSG: {
991 synchronized (ActivityManagerService.this) {
992 performAppGcsIfAppropriateLocked();
993 }
994 } break;
995 case WAIT_FOR_DEBUGGER_MSG: {
996 synchronized (ActivityManagerService.this) {
997 ProcessRecord app = (ProcessRecord)msg.obj;
998 if (msg.arg1 != 0) {
999 if (!app.waitedForDebugger) {
1000 Dialog d = new AppWaitingForDebuggerDialog(
1001 ActivityManagerService.this,
1002 mContext, app);
1003 app.waitDialog = d;
1004 app.waitedForDebugger = true;
1005 d.show();
1006 }
1007 } else {
1008 if (app.waitDialog != null) {
1009 app.waitDialog.dismiss();
1010 app.waitDialog = null;
1011 }
1012 }
1013 }
1014 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001016 if (mDidDexOpt) {
1017 mDidDexOpt = false;
1018 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1019 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001020 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001021 return;
1022 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001023 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 } break;
1025 case UPDATE_TIME_ZONE: {
1026 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001027 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1028 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 if (r.thread != null) {
1030 try {
1031 r.thread.updateTimeZone();
1032 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001033 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
1035 }
1036 }
1037 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001038 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001039 case CLEAR_DNS_CACHE: {
1040 synchronized (ActivityManagerService.this) {
1041 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1042 ProcessRecord r = mLruProcesses.get(i);
1043 if (r.thread != null) {
1044 try {
1045 r.thread.clearDnsCache();
1046 } catch (RemoteException ex) {
1047 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1048 }
1049 }
1050 }
1051 }
1052 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001053 case UPDATE_HTTP_PROXY: {
1054 ProxyProperties proxy = (ProxyProperties)msg.obj;
1055 String host = "";
1056 String port = "";
1057 String exclList = "";
1058 if (proxy != null) {
1059 host = proxy.getHost();
1060 port = Integer.toString(proxy.getPort());
1061 exclList = proxy.getExclusionList();
1062 }
1063 synchronized (ActivityManagerService.this) {
1064 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1065 ProcessRecord r = mLruProcesses.get(i);
1066 if (r.thread != null) {
1067 try {
1068 r.thread.setHttpProxy(host, port, exclList);
1069 } catch (RemoteException ex) {
1070 Slog.w(TAG, "Failed to update http proxy for: " +
1071 r.info.processName);
1072 }
1073 }
1074 }
1075 }
1076 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001078 String title = "System UIDs Inconsistent";
1079 String text = "UIDs on the system are inconsistent, you need to wipe your"
1080 + " data partition or your device will be unstable.";
1081 Log.e(TAG, title + ": " + text);
1082 if (mShowDialogs) {
1083 // XXX This is a temporary dialog, no need to localize.
1084 AlertDialog d = new BaseErrorDialog(mContext);
1085 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1086 d.setCancelable(false);
1087 d.setTitle(title);
1088 d.setMessage(text);
1089 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1090 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1091 mUidAlert = d;
1092 d.show();
1093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 } break;
1095 case IM_FEELING_LUCKY_MSG: {
1096 if (mUidAlert != null) {
1097 mUidAlert.dismiss();
1098 mUidAlert = null;
1099 }
1100 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001102 if (mDidDexOpt) {
1103 mDidDexOpt = false;
1104 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1105 nmsg.obj = msg.obj;
1106 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1107 return;
1108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 ProcessRecord app = (ProcessRecord)msg.obj;
1110 synchronized (ActivityManagerService.this) {
1111 processStartTimedOutLocked(app);
1112 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001113 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001114 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1115 synchronized (ActivityManagerService.this) {
1116 doPendingActivityLaunchesLocked(true);
1117 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001118 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001119 case KILL_APPLICATION_MSG: {
1120 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001121 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001122 boolean restart = (msg.arg2 == 1);
1123 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001124 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1125 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001126 }
1127 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001128 case FINALIZE_PENDING_INTENT_MSG: {
1129 ((PendingIntentRecord)msg.obj).completeFinalize();
1130 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001131 case POST_HEAVY_NOTIFICATION_MSG: {
1132 INotificationManager inm = NotificationManager.getService();
1133 if (inm == null) {
1134 return;
1135 }
1136
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001137 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001138 ProcessRecord process = root.app;
1139 if (process == null) {
1140 return;
1141 }
1142
1143 try {
1144 Context context = mContext.createPackageContext(process.info.packageName, 0);
1145 String text = mContext.getString(R.string.heavy_weight_notification,
1146 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1147 Notification notification = new Notification();
1148 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1149 notification.when = 0;
1150 notification.flags = Notification.FLAG_ONGOING_EVENT;
1151 notification.tickerText = text;
1152 notification.defaults = 0; // please be quiet
1153 notification.sound = null;
1154 notification.vibrate = null;
1155 notification.setLatestEventInfo(context, text,
1156 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001157 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1158 PendingIntent.FLAG_CANCEL_CURRENT, null,
1159 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001160
1161 try {
1162 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001163 inm.enqueueNotificationWithTag("android", null,
1164 R.string.heavy_weight_notification,
1165 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001166 } catch (RuntimeException e) {
1167 Slog.w(ActivityManagerService.TAG,
1168 "Error showing notification for heavy-weight app", e);
1169 } catch (RemoteException e) {
1170 }
1171 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001172 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001173 }
1174 } break;
1175 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1176 INotificationManager inm = NotificationManager.getService();
1177 if (inm == null) {
1178 return;
1179 }
1180 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001181 inm.cancelNotificationWithTag("android", null,
1182 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001183 } catch (RuntimeException e) {
1184 Slog.w(ActivityManagerService.TAG,
1185 "Error canceling notification for service", e);
1186 } catch (RemoteException e) {
1187 }
1188 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001189 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1190 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001191 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001192 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001193 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1194 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001195 }
1196 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001197 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1198 synchronized (ActivityManagerService.this) {
1199 ActivityRecord ar = (ActivityRecord)msg.obj;
1200 if (mCompatModeDialog != null) {
1201 if (mCompatModeDialog.mAppInfo.packageName.equals(
1202 ar.info.applicationInfo.packageName)) {
1203 return;
1204 }
1205 mCompatModeDialog.dismiss();
1206 mCompatModeDialog = null;
1207 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001208 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001209 if (mCompatModePackages.getPackageAskCompatModeLocked(
1210 ar.packageName)) {
1211 int mode = mCompatModePackages.computeCompatModeLocked(
1212 ar.info.applicationInfo);
1213 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1214 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1215 mCompatModeDialog = new CompatModeDialog(
1216 ActivityManagerService.this, mContext,
1217 ar.info.applicationInfo);
1218 mCompatModeDialog.show();
1219 }
1220 }
1221 }
1222 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001223 break;
1224 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001225 case DISPATCH_PROCESSES_CHANGED: {
1226 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001227 break;
1228 }
1229 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001230 final int pid = msg.arg1;
1231 final int uid = msg.arg2;
1232 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001233 break;
1234 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001235 case REPORT_MEM_USAGE: {
1236 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1237 if (!isDebuggable) {
1238 return;
1239 }
1240 synchronized (ActivityManagerService.this) {
1241 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001242 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1243 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001244 // avoid spamming.
1245 return;
1246 }
1247 mLastMemUsageReportTime = now;
1248 }
1249 Thread thread = new Thread() {
1250 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001251 StringBuilder dropBuilder = new StringBuilder(1024);
1252 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001253 StringWriter oomSw = new StringWriter();
1254 PrintWriter oomPw = new PrintWriter(oomSw);
1255 StringWriter catSw = new StringWriter();
1256 PrintWriter catPw = new PrintWriter(catSw);
1257 String[] emptyArgs = new String[] { };
1258 StringBuilder tag = new StringBuilder(128);
1259 StringBuilder stack = new StringBuilder(128);
1260 tag.append("Low on memory -- ");
1261 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1262 tag, stack);
1263 dropBuilder.append(stack);
1264 dropBuilder.append('\n');
1265 dropBuilder.append('\n');
1266 String oomString = oomSw.toString();
1267 dropBuilder.append(oomString);
1268 dropBuilder.append('\n');
1269 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001270 try {
1271 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1272 "procrank", });
1273 final InputStreamReader converter = new InputStreamReader(
1274 proc.getInputStream());
1275 BufferedReader in = new BufferedReader(converter);
1276 String line;
1277 while (true) {
1278 line = in.readLine();
1279 if (line == null) {
1280 break;
1281 }
1282 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001283 logBuilder.append(line);
1284 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001285 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001286 dropBuilder.append(line);
1287 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001288 }
1289 converter.close();
1290 } catch (IOException e) {
1291 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001292 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001293 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001294 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001295 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001296 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1297 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001298 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001299 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001300 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001301 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001302 addErrorToDropBox("lowmem", null, "system_server", null,
1303 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001304 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001305 synchronized (ActivityManagerService.this) {
1306 long now = SystemClock.uptimeMillis();
1307 if (mLastMemUsageReportTime < now) {
1308 mLastMemUsageReportTime = now;
1309 }
1310 }
1311 }
1312 };
1313 thread.start();
1314 break;
1315 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001316 case REPORT_USER_SWITCH_MSG: {
1317 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1318 break;
1319 }
1320 case CONTINUE_USER_SWITCH_MSG: {
1321 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1322 break;
1323 }
1324 case USER_SWITCH_TIMEOUT_MSG: {
1325 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1326 break;
1327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
1329 }
1330 };
1331
1332 public static void setSystemProcess() {
1333 try {
1334 ActivityManagerService m = mSelf;
1335
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001336 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001338 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001339 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 if (MONITOR_CPU_USAGE) {
1341 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 ServiceManager.addService("permission", new PermissionController(m));
1344
1345 ApplicationInfo info =
1346 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001347 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001348 mSystemThread.installSystemApplicationInfo(info);
1349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 synchronized (mSelf) {
1351 ProcessRecord app = mSelf.newProcessRecordLocked(
1352 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001353 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001355 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001356 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001357 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 synchronized (mSelf.mPidsSelfLocked) {
1359 mSelf.mPidsSelfLocked.put(app.pid, app);
1360 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001361 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363 } catch (PackageManager.NameNotFoundException e) {
1364 throw new RuntimeException(
1365 "Unable to find android system package", e);
1366 }
1367 }
1368
1369 public void setWindowManager(WindowManagerService wm) {
1370 mWindowManager = wm;
1371 }
1372
1373 public static final Context main(int factoryTest) {
1374 AThread thr = new AThread();
1375 thr.start();
1376
1377 synchronized (thr) {
1378 while (thr.mService == null) {
1379 try {
1380 thr.wait();
1381 } catch (InterruptedException e) {
1382 }
1383 }
1384 }
1385
1386 ActivityManagerService m = thr.mService;
1387 mSelf = m;
1388 ActivityThread at = ActivityThread.systemMain();
1389 mSystemThread = at;
1390 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001391 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 m.mContext = context;
1393 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001394 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395
1396 m.mBatteryStatsService.publish(context);
1397 m.mUsageStatsService.publish(context);
1398
1399 synchronized (thr) {
1400 thr.mReady = true;
1401 thr.notifyAll();
1402 }
1403
1404 m.startRunning(null, null, null, null);
1405
1406 return context;
1407 }
1408
1409 public static ActivityManagerService self() {
1410 return mSelf;
1411 }
1412
1413 static class AThread extends Thread {
1414 ActivityManagerService mService;
1415 boolean mReady = false;
1416
1417 public AThread() {
1418 super("ActivityManager");
1419 }
1420
1421 public void run() {
1422 Looper.prepare();
1423
1424 android.os.Process.setThreadPriority(
1425 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001426 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
1428 ActivityManagerService m = new ActivityManagerService();
1429
1430 synchronized (this) {
1431 mService = m;
1432 notifyAll();
1433 }
1434
1435 synchronized (this) {
1436 while (!mReady) {
1437 try {
1438 wait();
1439 } catch (InterruptedException e) {
1440 }
1441 }
1442 }
1443
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001444 // For debug builds, log event loop stalls to dropbox for analysis.
1445 if (StrictMode.conditionallyEnableDebugLogging()) {
1446 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1447 }
1448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 Looper.loop();
1450 }
1451 }
1452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 static class MemBinder extends Binder {
1454 ActivityManagerService mActivityManagerService;
1455 MemBinder(ActivityManagerService activityManagerService) {
1456 mActivityManagerService = activityManagerService;
1457 }
1458
1459 @Override
1460 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001461 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1462 != PackageManager.PERMISSION_GRANTED) {
1463 pw.println("Permission Denial: can't dump meminfo from from pid="
1464 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1465 + " without permission " + android.Manifest.permission.DUMP);
1466 return;
1467 }
1468
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001469 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001470 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
1472 }
1473
Chet Haase9c1e23b2011-03-24 10:51:31 -07001474 static class GraphicsBinder extends Binder {
1475 ActivityManagerService mActivityManagerService;
1476 GraphicsBinder(ActivityManagerService activityManagerService) {
1477 mActivityManagerService = activityManagerService;
1478 }
1479
1480 @Override
1481 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001482 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1483 != PackageManager.PERMISSION_GRANTED) {
1484 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1485 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1486 + " without permission " + android.Manifest.permission.DUMP);
1487 return;
1488 }
1489
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001490 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001491 }
1492 }
1493
Jeff Brown6754ba22011-12-14 20:20:01 -08001494 static class DbBinder extends Binder {
1495 ActivityManagerService mActivityManagerService;
1496 DbBinder(ActivityManagerService activityManagerService) {
1497 mActivityManagerService = activityManagerService;
1498 }
1499
1500 @Override
1501 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1502 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1503 != PackageManager.PERMISSION_GRANTED) {
1504 pw.println("Permission Denial: can't dump dbinfo from from pid="
1505 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1506 + " without permission " + android.Manifest.permission.DUMP);
1507 return;
1508 }
1509
1510 mActivityManagerService.dumpDbInfo(fd, pw, args);
1511 }
1512 }
1513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 static class CpuBinder extends Binder {
1515 ActivityManagerService mActivityManagerService;
1516 CpuBinder(ActivityManagerService activityManagerService) {
1517 mActivityManagerService = activityManagerService;
1518 }
1519
1520 @Override
1521 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001522 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1523 != PackageManager.PERMISSION_GRANTED) {
1524 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1525 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1526 + " without permission " + android.Manifest.permission.DUMP);
1527 return;
1528 }
1529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001531 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1532 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1533 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535 }
1536 }
1537
1538 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001539 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001540
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001541 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1542 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1543 mBroadcastQueues[0] = mFgBroadcastQueue;
1544 mBroadcastQueues[1] = mBgBroadcastQueue;
1545
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001546 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001547 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 File dataDir = Environment.getDataDirectory();
1550 File systemDir = new File(dataDir, "system");
1551 systemDir.mkdirs();
1552 mBatteryStatsService = new BatteryStatsService(new File(
1553 systemDir, "batterystats.bin").toString());
1554 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001555 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001556 mOnBattery = DEBUG_POWER ? true
1557 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001558 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001560 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001561 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001562 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001564 // User 0 is the first and only user that runs at boot.
1565 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001566 mUserLru.add(Integer.valueOf(0));
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001567
Jack Palevichb90d28c2009-07-22 15:35:24 -07001568 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1569 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1570
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001571 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001572 mConfiguration.setLocale(Locale.getDefault());
1573
Dianne Hackborn813075a62011-11-14 17:45:19 -08001574 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 mProcessStats.init();
1576
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001577 mCompatModePackages = new CompatModePackages(this, systemDir);
1578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 // Add ourself to the Watchdog monitors.
1580 Watchdog.getInstance().addMonitor(this);
1581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 mProcessStatsThread = new Thread("ProcessStats") {
1583 public void run() {
1584 while (true) {
1585 try {
1586 try {
1587 synchronized(this) {
1588 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001589 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001591 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 // + ", write delay=" + nextWriteDelay);
1593 if (nextWriteDelay < nextCpuDelay) {
1594 nextCpuDelay = nextWriteDelay;
1595 }
1596 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001597 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 this.wait(nextCpuDelay);
1599 }
1600 }
1601 } catch (InterruptedException e) {
1602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 updateCpuStatsNow();
1604 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607 }
1608 }
1609 };
1610 mProcessStatsThread.start();
1611 }
1612
1613 @Override
1614 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1615 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001616 if (code == SYSPROPS_TRANSACTION) {
1617 // We need to tell all apps about the system property change.
1618 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1619 synchronized(this) {
1620 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1621 final int NA = apps.size();
1622 for (int ia=0; ia<NA; ia++) {
1623 ProcessRecord app = apps.valueAt(ia);
1624 if (app.thread != null) {
1625 procs.add(app.thread.asBinder());
1626 }
1627 }
1628 }
1629 }
1630
1631 int N = procs.size();
1632 for (int i=0; i<N; i++) {
1633 Parcel data2 = Parcel.obtain();
1634 try {
1635 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1636 } catch (RemoteException e) {
1637 }
1638 data2.recycle();
1639 }
1640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 try {
1642 return super.onTransact(code, data, reply, flags);
1643 } catch (RuntimeException e) {
1644 // The activity manager only throws security exceptions, so let's
1645 // log all others.
1646 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001647 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 throw e;
1650 }
1651 }
1652
1653 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001654 final long now = SystemClock.uptimeMillis();
1655 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1656 return;
1657 }
1658 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1659 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 mProcessStatsThread.notify();
1661 }
1662 }
1663 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 void updateCpuStatsNow() {
1666 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001667 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 final long now = SystemClock.uptimeMillis();
1669 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001672 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1673 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 haveNewCpuStats = true;
1675 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001676 //Slog.i(TAG, mProcessStats.printCurrentState());
1677 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 // + mProcessStats.getTotalCpuPercent() + "%");
1679
Joe Onorato8a9b2202010-02-26 18:56:32 -08001680 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 if ("true".equals(SystemProperties.get("events.cpu"))) {
1682 int user = mProcessStats.getLastUserTime();
1683 int system = mProcessStats.getLastSystemTime();
1684 int iowait = mProcessStats.getLastIoWaitTime();
1685 int irq = mProcessStats.getLastIrqTime();
1686 int softIrq = mProcessStats.getLastSoftIrqTime();
1687 int idle = mProcessStats.getLastIdleTime();
1688
1689 int total = user + system + iowait + irq + softIrq + idle;
1690 if (total == 0) total = 1;
1691
Doug Zongker2bec3d42009-12-04 12:52:44 -08001692 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 ((user+system+iowait+irq+softIrq) * 100) / total,
1694 (user * 100) / total,
1695 (system * 100) / total,
1696 (iowait * 100) / total,
1697 (irq * 100) / total,
1698 (softIrq * 100) / total);
1699 }
1700 }
1701
Amith Yamasanie43530a2009-08-21 13:11:37 -07001702 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001703 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001704 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 synchronized(mPidsSelfLocked) {
1706 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001707 if (mOnBattery) {
1708 int perc = bstats.startAddingCpuLocked();
1709 int totalUTime = 0;
1710 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001711 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001713 ProcessStats.Stats st = mProcessStats.getStats(i);
1714 if (!st.working) {
1715 continue;
1716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001718 int otherUTime = (st.rel_utime*perc)/100;
1719 int otherSTime = (st.rel_stime*perc)/100;
1720 totalUTime += otherUTime;
1721 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (pr != null) {
1723 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001724 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1725 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001726 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001727 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001728 } else {
1729 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001730 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001731 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001732 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1733 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001734 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
1737 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001738 bstats.finishAddingCpuLocked(perc, totalUTime,
1739 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741 }
1742 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1745 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001746 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748 }
1749 }
1750 }
1751
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001752 @Override
1753 public void batteryNeedsCpuUpdate() {
1754 updateCpuStatsNow();
1755 }
1756
1757 @Override
1758 public void batteryPowerChanged(boolean onBattery) {
1759 // When plugging in, update the CPU stats first before changing
1760 // the plug state.
1761 updateCpuStatsNow();
1762 synchronized (this) {
1763 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001764 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001765 }
1766 }
1767 }
1768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 /**
1770 * Initialize the application bind args. These are passed to each
1771 * process when the bindApplication() IPC is sent to the process. They're
1772 * lazily setup to make sure the services are running when they're asked for.
1773 */
1774 private HashMap<String, IBinder> getCommonServicesLocked() {
1775 if (mAppBindArgs == null) {
1776 mAppBindArgs = new HashMap<String, IBinder>();
1777
1778 // Setup the application init args
1779 mAppBindArgs.put("package", ServiceManager.getService("package"));
1780 mAppBindArgs.put("window", ServiceManager.getService("window"));
1781 mAppBindArgs.put(Context.ALARM_SERVICE,
1782 ServiceManager.getService(Context.ALARM_SERVICE));
1783 }
1784 return mAppBindArgs;
1785 }
1786
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (mFocusedActivity != r) {
1789 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001790 if (r != null) {
1791 mWindowManager.setFocusedApp(r.appToken, true);
1792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
1794 }
1795
Dianne Hackborn906497c2010-05-10 15:57:38 -07001796 private final void updateLruProcessInternalLocked(ProcessRecord app,
1797 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001799 int lrui = mLruProcesses.indexOf(app);
1800 if (lrui >= 0) mLruProcesses.remove(lrui);
1801
1802 int i = mLruProcesses.size()-1;
1803 int skipTop = 0;
1804
Dianne Hackborn906497c2010-05-10 15:57:38 -07001805 app.lruSeq = mLruSeq;
1806
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001807 // compute the new weight for this process.
1808 if (updateActivityTime) {
1809 app.lastActivityTime = SystemClock.uptimeMillis();
1810 }
1811 if (app.activities.size() > 0) {
1812 // If this process has activities, we more strongly want to keep
1813 // it around.
1814 app.lruWeight = app.lastActivityTime;
1815 } else if (app.pubProviders.size() > 0) {
1816 // If this process contains content providers, we want to keep
1817 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001818 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001819 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001820 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001821 } else {
1822 // If this process doesn't have activities, we less strongly
1823 // want to keep it around, and generally want to avoid getting
1824 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001825 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001826 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001827 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001828 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001829
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001830 while (i >= 0) {
1831 ProcessRecord p = mLruProcesses.get(i);
1832 // If this app shouldn't be in front of the first N background
1833 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001834 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001835 skipTop--;
1836 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001837 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001838 mLruProcesses.add(i+1, app);
1839 break;
1840 }
1841 i--;
1842 }
1843 if (i < 0) {
1844 mLruProcesses.add(0, app);
1845 }
1846
Dianne Hackborn906497c2010-05-10 15:57:38 -07001847 // If the app is currently using a content provider or service,
1848 // bump those processes as well.
1849 if (app.connections.size() > 0) {
1850 for (ConnectionRecord cr : app.connections) {
1851 if (cr.binding != null && cr.binding.service != null
1852 && cr.binding.service.app != null
1853 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001854 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001855 updateActivityTime, i+1);
1856 }
1857 }
1858 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001859 for (int j=app.conProviders.size()-1; j>=0; j--) {
1860 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1861 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001862 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001863 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001864 }
1865 }
1866
Joe Onorato8a9b2202010-02-26 18:56:32 -08001867 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 if (oomAdj) {
1869 updateOomAdjLocked();
1870 }
1871 }
1872
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001873 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001874 boolean oomAdj, boolean updateActivityTime) {
1875 mLruSeq++;
1876 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1877 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001878
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001879 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001881 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001882 // The system gets to run in any process. If there are multiple
1883 // processes with the same uid, just pick the first (this
1884 // should never happen).
1885 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1886 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001887 if (procs == null) return null;
1888 final int N = procs.size();
1889 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001890 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893 ProcessRecord proc = mProcessNames.get(processName, uid);
1894 return proc;
1895 }
1896
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001897 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001898 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001899 try {
1900 if (pm.performDexOpt(packageName)) {
1901 mDidDexOpt = true;
1902 }
1903 } catch (RemoteException e) {
1904 }
1905 }
1906
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001907 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 int transit = mWindowManager.getPendingAppTransition();
1909 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1910 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1911 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1912 }
1913
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001914 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001916 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1917 boolean isolated) {
1918 ProcessRecord app;
1919 if (!isolated) {
1920 app = getProcessRecordLocked(processName, info.uid);
1921 } else {
1922 // If this is an isolated process, it can't re-use an existing process.
1923 app = null;
1924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 // We don't have to do anything more if:
1926 // (1) There is an existing application record; and
1927 // (2) The caller doesn't think it is dead, OR there is no thread
1928 // object attached to it so we know it couldn't have crashed; and
1929 // (3) There is a pid assigned to it, so it is either starting or
1930 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001931 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 + " app=" + app + " knownToBeDead=" + knownToBeDead
1933 + " thread=" + (app != null ? app.thread : null)
1934 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001935 if (app != null && app.pid > 0) {
1936 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001937 // We already have the app running, or are waiting for it to
1938 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001939 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001940 // If this is a new package in the process, add the package to the list
1941 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001942 return app;
1943 } else {
1944 // An application record is attached to a previous process,
1945 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001946 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001947 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 String hostingNameStr = hostingName != null
1952 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001953
1954 if (!isolated) {
1955 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1956 // If we are in the background, then check to see if this process
1957 // is bad. If so, we will just silently fail.
1958 if (mBadProcesses.get(info.processName, info.uid) != null) {
1959 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1960 + "/" + info.processName);
1961 return null;
1962 }
1963 } else {
1964 // When the user is explicitly starting a process, then clear its
1965 // crash count so that we won't make it bad until they see at
1966 // least one crash dialog again, and make the process good again
1967 // if it had been bad.
1968 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001969 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001970 mProcessCrashTimes.remove(info.processName, info.uid);
1971 if (mBadProcesses.get(info.processName, info.uid) != null) {
1972 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1973 info.processName);
1974 mBadProcesses.remove(info.processName, info.uid);
1975 if (app != null) {
1976 app.bad = false;
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 }
1980 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001983 app = newProcessRecordLocked(null, info, processName, isolated);
1984 if (app == null) {
1985 Slog.w(TAG, "Failed making new process record for "
1986 + processName + "/" + info.uid + " isolated=" + isolated);
1987 return null;
1988 }
1989 mProcessNames.put(processName, app.uid, app);
1990 if (isolated) {
1991 mIsolatedProcesses.put(app.uid, app);
1992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 } else {
1994 // If this is a new package in the process, add the package to the list
1995 app.addPackage(info.packageName);
1996 }
1997
1998 // If the system is not ready yet, then hold off on starting this
1999 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002000 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002001 && !isAllowedWhileBooting(info)
2002 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if (!mProcessesOnHold.contains(app)) {
2004 mProcessesOnHold.add(app);
2005 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002006 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 return app;
2008 }
2009
2010 startProcessLocked(app, hostingType, hostingNameStr);
2011 return (app.pid != 0) ? app : null;
2012 }
2013
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002014 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2015 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2016 }
2017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 private final void startProcessLocked(ProcessRecord app,
2019 String hostingType, String hostingNameStr) {
2020 if (app.pid > 0 && app.pid != MY_PID) {
2021 synchronized (mPidsSelfLocked) {
2022 mPidsSelfLocked.remove(app.pid);
2023 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2024 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002025 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002028 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2029 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 mProcessesOnHold.remove(app);
2031
2032 updateCpuStats();
2033
2034 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2035 mProcDeaths[0] = 0;
2036
2037 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002038 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002041 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002042 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002043 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002044 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002045 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002046 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002047
2048 if (Environment.isExternalStorageEmulated()) {
2049 if (pm.checkPermission(
2050 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2051 app.info.packageName) == PERMISSION_GRANTED) {
2052 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2053 } else {
2054 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2055 }
2056 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002057 } catch (PackageManager.NameNotFoundException e) {
2058 Slog.w(TAG, "Unable to retrieve gids", e);
2059 }
Kenny Roote091f222012-09-11 15:01:26 -07002060
2061 /*
2062 * Add shared application GID so applications can share some
2063 * resources like shared libraries
2064 */
2065 if (permGids == null) {
2066 gids = new int[1];
2067 } else {
2068 gids = new int[permGids.length + 1];
2069 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2070 }
2071 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2074 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2075 && mTopComponent != null
2076 && app.processName.equals(mTopComponent.getPackageName())) {
2077 uid = 0;
2078 }
2079 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2080 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2081 uid = 0;
2082 }
2083 }
2084 int debugFlags = 0;
2085 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2086 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002087 // Also turn on CheckJNI for debuggable apps. It's quite
2088 // awkward to turn on otherwise.
2089 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002091 // Run the app in safe mode if its manifest requests so or the
2092 // system is booted in safe mode.
2093 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2094 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002095 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2098 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2099 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002100 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2101 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 if ("1".equals(SystemProperties.get("debug.assert"))) {
2104 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2105 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002106
2107 // Start the process. It will either succeed and return a result containing
2108 // the PID of the new process, or else throw a RuntimeException.
2109 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002110 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002111 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2114 synchronized (bs) {
2115 if (bs.isOnBattery()) {
2116 app.batteryStats.incStartsLocked();
2117 }
2118 }
2119
Jeff Brown3f9dd282011-07-08 20:02:19 -07002120 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 app.processName, hostingType,
2122 hostingNameStr != null ? hostingNameStr : "");
2123
2124 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002125 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
2127
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002128 StringBuilder buf = mStringBuilder;
2129 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 buf.append("Start proc ");
2131 buf.append(app.processName);
2132 buf.append(" for ");
2133 buf.append(hostingType);
2134 if (hostingNameStr != null) {
2135 buf.append(" ");
2136 buf.append(hostingNameStr);
2137 }
2138 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002139 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 buf.append(" uid=");
2141 buf.append(uid);
2142 buf.append(" gids={");
2143 if (gids != null) {
2144 for (int gi=0; gi<gids.length; gi++) {
2145 if (gi != 0) buf.append(", ");
2146 buf.append(gids[gi]);
2147
2148 }
2149 }
2150 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002151 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002152 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002153 app.usingWrapper = startResult.usingWrapper;
2154 app.removed = false;
2155 synchronized (mPidsSelfLocked) {
2156 this.mPidsSelfLocked.put(startResult.pid, app);
2157 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2158 msg.obj = app;
2159 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2160 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
2162 } catch (RuntimeException e) {
2163 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002164 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002165 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 }
2167 }
2168
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002169 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 if (resumed) {
2171 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2172 } else {
2173 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2174 }
2175 }
2176
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002177 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002178 if (mHeadless) {
2179 // Added because none of the other calls to ensureBootCompleted seem to fire
2180 // when running headless.
2181 ensureBootCompleted();
2182 return false;
2183 }
2184
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002185 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2186 && mTopAction == null) {
2187 // We are running in factory test mode, but unable to find
2188 // the factory test app, so just sit around displaying the
2189 // error message and don't try to start anything.
2190 return false;
2191 }
2192 Intent intent = new Intent(
2193 mTopAction,
2194 mTopData != null ? Uri.parse(mTopData) : null);
2195 intent.setComponent(mTopComponent);
2196 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2197 intent.addCategory(Intent.CATEGORY_HOME);
2198 }
2199 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002200 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002201 if (aInfo != null) {
2202 intent.setComponent(new ComponentName(
2203 aInfo.applicationInfo.packageName, aInfo.name));
2204 // Don't do this if the home app is currently being
2205 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002206 aInfo = new ActivityInfo(aInfo);
2207 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002208 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2209 aInfo.applicationInfo.uid);
2210 if (app == null || app.instrumentationClass == null) {
2211 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002212 mMainStack.startActivityLocked(null, intent, null, aInfo,
2213 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002214 }
2215 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002216
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002217 return true;
2218 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002219
Amith Yamasani259d5e52012-08-31 15:11:01 -07002220 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2221 ActivityInfo ai = null;
2222 ComponentName comp = intent.getComponent();
2223 try {
2224 if (comp != null) {
2225 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2226 } else {
2227 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2228 intent,
2229 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2230 flags, userId);
2231
2232 if (info != null) {
2233 ai = info.activityInfo;
2234 }
2235 }
2236 } catch (RemoteException e) {
2237 // ignore
2238 }
2239
2240 return ai;
2241 }
2242
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002243 /**
2244 * Starts the "new version setup screen" if appropriate.
2245 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002246 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002247 // Only do this once per boot.
2248 if (mCheckedForSetup) {
2249 return;
2250 }
2251
2252 // We will show this screen if the current one is a different
2253 // version than the last one shown, and we are not running in
2254 // low-level factory test mode.
2255 final ContentResolver resolver = mContext.getContentResolver();
2256 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2257 Settings.Secure.getInt(resolver,
2258 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2259 mCheckedForSetup = true;
2260
2261 // See if we should be showing the platform update setup UI.
2262 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2263 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2264 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2265
2266 // We don't allow third party apps to replace this.
2267 ResolveInfo ri = null;
2268 for (int i=0; ris != null && i<ris.size(); i++) {
2269 if ((ris.get(i).activityInfo.applicationInfo.flags
2270 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2271 ri = ris.get(i);
2272 break;
2273 }
2274 }
2275
2276 if (ri != null) {
2277 String vers = ri.activityInfo.metaData != null
2278 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2279 : null;
2280 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2281 vers = ri.activityInfo.applicationInfo.metaData.getString(
2282 Intent.METADATA_SETUP_VERSION);
2283 }
2284 String lastVers = Settings.Secure.getString(
2285 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2286 if (vers != null && !vers.equals(lastVers)) {
2287 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2288 intent.setComponent(new ComponentName(
2289 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002290 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2291 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002292 }
2293 }
2294 }
2295 }
2296
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002297 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002298 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002299 }
2300
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002301 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002302 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002303 throw new SecurityException("Isolated process not allowed to call " + caller);
2304 }
2305 }
2306
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002307 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002308 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002309 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002310 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2311 }
2312 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002313
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002314 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2316 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002317 synchronized (this) {
2318 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2319 }
2320 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002321
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002322 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002323 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002324 synchronized (this) {
2325 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2326 }
2327 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002328
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002329 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002330 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2331 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002332 synchronized (this) {
2333 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002334 }
2335 }
2336
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002337 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002338 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002339 synchronized (this) {
2340 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2341 }
2342 }
2343
2344 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002345 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2346 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002347 synchronized (this) {
2348 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2349 }
2350 }
2351
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002352 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002353 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002354 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002357 private void dispatchProcessesChanged() {
2358 int N;
2359 synchronized (this) {
2360 N = mPendingProcessChanges.size();
2361 if (mActiveProcessChanges.length < N) {
2362 mActiveProcessChanges = new ProcessChangeItem[N];
2363 }
2364 mPendingProcessChanges.toArray(mActiveProcessChanges);
2365 mAvailProcessChanges.addAll(mPendingProcessChanges);
2366 mPendingProcessChanges.clear();
2367 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2368 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002369 int i = mProcessObservers.beginBroadcast();
2370 while (i > 0) {
2371 i--;
2372 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2373 if (observer != null) {
2374 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002375 for (int j=0; j<N; j++) {
2376 ProcessChangeItem item = mActiveProcessChanges[j];
2377 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2378 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2379 + item.pid + " uid=" + item.uid + ": "
2380 + item.foregroundActivities);
2381 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2382 item.foregroundActivities);
2383 }
2384 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2385 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2386 + item.pid + " uid=" + item.uid + ": " + item.importance);
2387 observer.onImportanceChanged(item.pid, item.uid,
2388 item.importance);
2389 }
2390 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002391 } catch (RemoteException e) {
2392 }
2393 }
2394 }
2395 mProcessObservers.finishBroadcast();
2396 }
2397
2398 private void dispatchProcessDied(int pid, int uid) {
2399 int i = mProcessObservers.beginBroadcast();
2400 while (i > 0) {
2401 i--;
2402 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2403 if (observer != null) {
2404 try {
2405 observer.onProcessDied(pid, uid);
2406 } catch (RemoteException e) {
2407 }
2408 }
2409 }
2410 mProcessObservers.finishBroadcast();
2411 }
2412
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002413 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002414 final int N = mPendingActivityLaunches.size();
2415 if (N <= 0) {
2416 return;
2417 }
2418 for (int i=0; i<N; i++) {
2419 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002420 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002421 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002422 }
2423 mPendingActivityLaunches.clear();
2424 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002425
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002426 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002427 Intent intent, String resolvedType, IBinder resultTo,
2428 String resultWho, int requestCode, int startFlags,
2429 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002430 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002431 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002432 }
2433
2434 public final int startActivityAsUser(IApplicationThread caller,
2435 Intent intent, String resolvedType, IBinder resultTo,
2436 String resultWho, int requestCode, int startFlags,
2437 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002438 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornd8883992012-09-07 15:58:52 -07002439 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2440 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002441 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002442 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2443 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002444 }
2445
2446 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002447 Intent intent, String resolvedType, IBinder resultTo,
2448 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002449 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002450 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002451 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2452 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002453 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002454 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002455 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002456 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002457 return res;
2458 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002459
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002460 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002461 Intent intent, String resolvedType, IBinder resultTo,
2462 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002463 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002464 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002465 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2466 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002467 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002468 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002469 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002470 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002471 }
2472
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002473 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002474 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002475 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002476 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002477 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002478 // Refuse possible leaked file descriptors
2479 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2480 throw new IllegalArgumentException("File descriptors passed in Intent");
2481 }
2482
2483 IIntentSender sender = intent.getTarget();
2484 if (!(sender instanceof PendingIntentRecord)) {
2485 throw new IllegalArgumentException("Bad PendingIntent object");
2486 }
2487
2488 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002489
2490 synchronized (this) {
2491 // If this is coming from the currently resumed activity, it is
2492 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002493 if (mMainStack.mResumedActivity != null
2494 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002495 Binder.getCallingUid()) {
2496 mAppSwitchesAllowedTime = 0;
2497 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002498 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002499 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2500 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002502 }
2503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002505 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 // Refuse possible leaked file descriptors
2507 if (intent != null && intent.hasFileDescriptors() == true) {
2508 throw new IllegalArgumentException("File descriptors passed in Intent");
2509 }
2510
2511 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002512 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2513 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002514 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 return false;
2516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 if (r.app == null || r.app.thread == null) {
2518 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002519 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 return false;
2521 }
2522 intent = new Intent(intent);
2523 // The caller is not allowed to change the data.
2524 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2525 // And we are resetting to find the next component...
2526 intent.setComponent(null);
2527
2528 ActivityInfo aInfo = null;
2529 try {
2530 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002531 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002533 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002534 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535
2536 // Look for the original activity in the list...
2537 final int N = resolves != null ? resolves.size() : 0;
2538 for (int i=0; i<N; i++) {
2539 ResolveInfo rInfo = resolves.get(i);
2540 if (rInfo.activityInfo.packageName.equals(r.packageName)
2541 && rInfo.activityInfo.name.equals(r.info.name)) {
2542 // We found the current one... the next matching is
2543 // after it.
2544 i++;
2545 if (i<N) {
2546 aInfo = resolves.get(i).activityInfo;
2547 }
2548 break;
2549 }
2550 }
2551 } catch (RemoteException e) {
2552 }
2553
2554 if (aInfo == null) {
2555 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002556 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 return false;
2558 }
2559
2560 intent.setComponent(new ComponentName(
2561 aInfo.applicationInfo.packageName, aInfo.name));
2562 intent.setFlags(intent.getFlags()&~(
2563 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2564 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2565 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2566 Intent.FLAG_ACTIVITY_NEW_TASK));
2567
2568 // Okay now we need to start the new activity, replacing the
2569 // currently running activity. This is a little tricky because
2570 // we want to start the new one as if the current one is finished,
2571 // but not finish the current one first so that there is no flicker.
2572 // And thus...
2573 final boolean wasFinishing = r.finishing;
2574 r.finishing = true;
2575
2576 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002577 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 final String resultWho = r.resultWho;
2579 final int requestCode = r.requestCode;
2580 r.resultTo = null;
2581 if (resultTo != null) {
2582 resultTo.removeResultsLocked(r, resultWho, requestCode);
2583 }
2584
2585 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002586 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002587 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2588 resultWho, requestCode, -1, r.launchedFromUid, 0,
2589 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 Binder.restoreCallingIdentity(origId);
2591
2592 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002593 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 return false;
2595 }
2596 return true;
2597 }
2598 }
2599
Dianne Hackborn41203752012-08-31 14:05:51 -07002600 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002602 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2603
2604 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2605 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606
Amith Yamasani742a6712011-05-04 14:49:28 -07002607 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002608 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002609 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002610 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002611 }
2612
2613 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002614 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002615 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002616 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002617 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002618 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002619 }
2620
Dianne Hackborn41203752012-08-31 14:05:51 -07002621 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002622 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002623 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002624
Dianne Hackborn41203752012-08-31 14:05:51 -07002625 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2626 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002627 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002628 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002629 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 }
2631
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002632 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002634 // Quick case: check if the top-most recent task is the same.
2635 if (N > 0 && mRecentTasks.get(0) == task) {
2636 return;
2637 }
2638 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 for (int i=0; i<N; i++) {
2640 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002641 if (task.userId == tr.userId
2642 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2643 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 mRecentTasks.remove(i);
2645 i--;
2646 N--;
2647 if (task.intent == null) {
2648 // If the new recent task we are adding is not fully
2649 // specified, then replace it with the existing recent task.
2650 task = tr;
2651 }
2652 }
2653 }
2654 if (N >= MAX_RECENT_TASKS) {
2655 mRecentTasks.remove(N-1);
2656 }
2657 mRecentTasks.add(0, task);
2658 }
2659
2660 public void setRequestedOrientation(IBinder token,
2661 int requestedOrientation) {
2662 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002663 ActivityRecord r = mMainStack.isInStackLocked(token);
2664 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 return;
2666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002668 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002670 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002671 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 if (config != null) {
2673 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002674 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002675 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677 }
2678 Binder.restoreCallingIdentity(origId);
2679 }
2680 }
2681
2682 public int getRequestedOrientation(IBinder token) {
2683 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002684 ActivityRecord r = mMainStack.isInStackLocked(token);
2685 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2687 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002688 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 }
2690 }
2691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 /**
2693 * This is the internal entry point for handling Activity.finish().
2694 *
2695 * @param token The Binder token referencing the Activity we want to finish.
2696 * @param resultCode Result code, if any, from this Activity.
2697 * @param resultData Result data (Intent), if any, from this Activity.
2698 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002699 * @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 -08002700 */
2701 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2702 // Refuse possible leaked file descriptors
2703 if (resultData != null && resultData.hasFileDescriptors() == true) {
2704 throw new IllegalArgumentException("File descriptors passed in Intent");
2705 }
2706
2707 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002708 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002710 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 if (next != null) {
2712 // ask watcher if this is allowed
2713 boolean resumeOK = true;
2714 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002715 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002717 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 }
2719
2720 if (!resumeOK) {
2721 return false;
2722 }
2723 }
2724 }
2725 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002726 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002727 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 Binder.restoreCallingIdentity(origId);
2729 return res;
2730 }
2731 }
2732
Dianne Hackborn860755f2010-06-03 18:47:52 -07002733 public final void finishHeavyWeightApp() {
2734 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2735 != PackageManager.PERMISSION_GRANTED) {
2736 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2737 + Binder.getCallingPid()
2738 + ", uid=" + Binder.getCallingUid()
2739 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2740 Slog.w(TAG, msg);
2741 throw new SecurityException(msg);
2742 }
2743
2744 synchronized(this) {
2745 if (mHeavyWeightProcess == null) {
2746 return;
2747 }
2748
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002749 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002750 mHeavyWeightProcess.activities);
2751 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002752 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002753 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002754 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002755 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002756 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002757 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002758 }
2759 }
2760 }
2761
Dianne Hackborn41203752012-08-31 14:05:51 -07002762 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2763 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002764 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002765 }
2766 }
2767
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002768 public void crashApplication(int uid, int initialPid, String packageName,
2769 String message) {
2770 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2771 != PackageManager.PERMISSION_GRANTED) {
2772 String msg = "Permission Denial: crashApplication() from pid="
2773 + Binder.getCallingPid()
2774 + ", uid=" + Binder.getCallingUid()
2775 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2776 Slog.w(TAG, msg);
2777 throw new SecurityException(msg);
2778 }
2779
2780 synchronized(this) {
2781 ProcessRecord proc = null;
2782
2783 // Figure out which process to kill. We don't trust that initialPid
2784 // still has any relation to current pids, so must scan through the
2785 // list.
2786 synchronized (mPidsSelfLocked) {
2787 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2788 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002789 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002790 continue;
2791 }
2792 if (p.pid == initialPid) {
2793 proc = p;
2794 break;
2795 }
2796 for (String str : p.pkgList) {
2797 if (str.equals(packageName)) {
2798 proc = p;
2799 }
2800 }
2801 }
2802 }
2803
2804 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002805 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002806 + " initialPid=" + initialPid
2807 + " packageName=" + packageName);
2808 return;
2809 }
2810
2811 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002812 if (proc.pid == Process.myPid()) {
2813 Log.w(TAG, "crashApplication: trying to crash self!");
2814 return;
2815 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002816 long ident = Binder.clearCallingIdentity();
2817 try {
2818 proc.thread.scheduleCrash(message);
2819 } catch (RemoteException e) {
2820 }
2821 Binder.restoreCallingIdentity(ident);
2822 }
2823 }
2824 }
2825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 public final void finishSubActivity(IBinder token, String resultWho,
2827 int requestCode) {
2828 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002830 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 Binder.restoreCallingIdentity(origId);
2832 }
2833 }
2834
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002835 public boolean finishActivityAffinity(IBinder token) {
2836 synchronized(this) {
2837 final long origId = Binder.clearCallingIdentity();
2838 boolean res = mMainStack.finishActivityAffinityLocked(token);
2839 Binder.restoreCallingIdentity(origId);
2840 return res;
2841 }
2842 }
2843
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002844 public boolean willActivityBeVisible(IBinder token) {
2845 synchronized(this) {
2846 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2848 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002849 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002850 return true;
2851 }
2852 if (r.fullscreen && !r.finishing) {
2853 return false;
2854 }
2855 }
2856 return true;
2857 }
2858 }
2859
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002860 public void overridePendingTransition(IBinder token, String packageName,
2861 int enterAnim, int exitAnim) {
2862 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002863 ActivityRecord self = mMainStack.isInStackLocked(token);
2864 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002865 return;
2866 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002867
2868 final long origId = Binder.clearCallingIdentity();
2869
2870 if (self.state == ActivityState.RESUMED
2871 || self.state == ActivityState.PAUSING) {
2872 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002873 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002874 }
2875
2876 Binder.restoreCallingIdentity(origId);
2877 }
2878 }
2879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 * Main function for removing an existing process from the activity manager
2882 * as a result of that process going away. Clears out all connections
2883 * to the process.
2884 */
2885 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002886 boolean restarting, boolean allowRestart) {
2887 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002889 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 }
2891
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002892 if (mProfileProc == app) {
2893 clearProfilerLocked();
2894 }
2895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002897 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2898 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2899 mMainStack.mPausingActivity = null;
2900 }
2901 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2902 mMainStack.mLastPausedActivity = null;
2903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904
2905 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002906 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907
2908 boolean atTop = true;
2909 boolean hasVisibleActivities = false;
2910
2911 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002912 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002913 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 TAG, "Removing app " + app + " from history with " + i + " entries");
2915 while (i > 0) {
2916 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002917 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002918 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2920 if (r.app == app) {
2921 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002922 if (ActivityStack.DEBUG_ADD_REMOVE) {
2923 RuntimeException here = new RuntimeException("here");
2924 here.fillInStackTrace();
2925 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2926 + ": haveState=" + r.haveState
2927 + " stateNotNeeded=" + r.stateNotNeeded
2928 + " finishing=" + r.finishing
2929 + " state=" + r.state, here);
2930 }
2931 if (!r.finishing) {
2932 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002933 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2934 System.identityHashCode(r),
2935 r.task.taskId, r.shortComponentName,
2936 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002937 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002938 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939
2940 } else {
2941 // We have the current state for this activity, so
2942 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002943 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 TAG, "Keeping entry, setting app to null");
2945 if (r.visible) {
2946 hasVisibleActivities = true;
2947 }
2948 r.app = null;
2949 r.nowVisible = false;
2950 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002951 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2952 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 r.icicle = null;
2954 }
2955 }
2956
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002957 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 }
2959 atTop = false;
2960 }
2961
2962 app.activities.clear();
2963
2964 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002965 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 + " running instrumentation " + app.instrumentationClass);
2967 Bundle info = new Bundle();
2968 info.putString("shortMsg", "Process crashed.");
2969 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2970 }
2971
2972 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002973 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 // If there was nothing to resume, and we are not already
2975 // restarting this process, but there is a visible activity that
2976 // is hosted by the process... then make sure all visible
2977 // activities are running, taking care of restarting this
2978 // process.
2979 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002980 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 }
2982 }
2983 }
2984 }
2985
2986 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2987 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002989 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2990 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2992 return i;
2993 }
2994 }
2995 return -1;
2996 }
2997
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002998 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 IApplicationThread thread) {
3000 if (thread == null) {
3001 return null;
3002 }
3003
3004 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003005 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 }
3007
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003008 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 IApplicationThread thread) {
3010
3011 mProcDeaths[0]++;
3012
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003013 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3014 synchronized (stats) {
3015 stats.noteProcessDiedLocked(app.info.uid, pid);
3016 }
3017
Magnus Edlund7bb25812010-02-24 15:45:06 +01003018 // Clean up already done if the process has been re-started.
3019 if (app.pid == pid && app.thread != null &&
3020 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003021 if (!app.killedBackground) {
3022 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3023 + ") has died.");
3024 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003025 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003026 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 TAG, "Dying app: " + app + ", pid: " + pid
3028 + ", thread: " + thread.asBinder());
3029 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003030 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031
3032 if (doLowMem) {
3033 // If there are no longer any background processes running,
3034 // and the app that died was not running instrumentation,
3035 // then tell everyone we are now low on memory.
3036 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003037 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3038 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003039 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 haveBg = true;
3041 break;
3042 }
3043 }
3044
3045 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003046 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003047 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003048 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3049 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003050 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003051 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3052 // The low memory report is overriding any current
3053 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003054 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003055 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003056 rec.lastRequestedGc = 0;
3057 } else {
3058 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003060 rec.reportLowMemory = true;
3061 rec.lastLowMemory = now;
3062 mProcessesToGc.remove(rec);
3063 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 }
3065 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003066 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003067 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 }
3069 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003070 } else if (app.pid != pid) {
3071 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003072 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003073 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003074 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003075 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003076 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 + thread.asBinder());
3078 }
3079 }
3080
Dan Egnor42471dd2010-01-07 17:25:22 -08003081 /**
3082 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003083 * @param clearTraces causes the dump file to be erased prior to the new
3084 * traces being written, if true; when false, the new traces will be
3085 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003086 * @param firstPids of dalvik VM processes to dump stack traces for first
3087 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003088 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003089 * @return file containing stack traces, or null if no dump file is configured
3090 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003091 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003092 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003093 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3094 if (tracesPath == null || tracesPath.length() == 0) {
3095 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003097
3098 File tracesFile = new File(tracesPath);
3099 try {
3100 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003101 if (!tracesDir.exists()) {
3102 tracesFile.mkdirs();
3103 if (!SELinux.restorecon(tracesDir)) {
3104 return null;
3105 }
3106 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003107 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3108
Christopher Tate6ee412d2010-05-28 12:01:56 -07003109 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003110 tracesFile.createNewFile();
3111 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3112 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003113 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003114 return null;
3115 }
3116
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003117 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003118 return tracesFile;
3119 }
3120
3121 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003122 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003123 // Use a FileObserver to detect when traces finish writing.
3124 // The order of traces is considered important to maintain for legibility.
3125 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3126 public synchronized void onEvent(int event, String path) { notify(); }
3127 };
3128
3129 try {
3130 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003131
3132 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003133 if (firstPids != null) {
3134 try {
3135 int num = firstPids.size();
3136 for (int i = 0; i < num; i++) {
3137 synchronized (observer) {
3138 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3139 observer.wait(200); // Wait for write-close, give up after 200msec
3140 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003141 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003142 } catch (InterruptedException e) {
3143 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003144 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003145 }
3146
3147 // Next measure CPU usage.
3148 if (processStats != null) {
3149 processStats.init();
3150 System.gc();
3151 processStats.update();
3152 try {
3153 synchronized (processStats) {
3154 processStats.wait(500); // measure over 1/2 second.
3155 }
3156 } catch (InterruptedException e) {
3157 }
3158 processStats.update();
3159
3160 // We'll take the stack crawls of just the top apps using CPU.
3161 final int N = processStats.countWorkingStats();
3162 int numProcs = 0;
3163 for (int i=0; i<N && numProcs<5; i++) {
3164 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3165 if (lastPids.indexOfKey(stats.pid) >= 0) {
3166 numProcs++;
3167 try {
3168 synchronized (observer) {
3169 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3170 observer.wait(200); // Wait for write-close, give up after 200msec
3171 }
3172 } catch (InterruptedException e) {
3173 Log.wtf(TAG, e);
3174 }
3175
3176 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003177 }
3178 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003179
Dan Egnor42471dd2010-01-07 17:25:22 -08003180 } finally {
3181 observer.stopWatching();
3182 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003183
3184 if (nativeProcs != null) {
3185 int[] pids = Process.getPidsForCommands(nativeProcs);
3186 if (pids != null) {
3187 for (int pid : pids) {
3188 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3189 }
3190 }
3191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 }
3193
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003194 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003195 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003196 return;
3197 }
3198 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3199 if (tracesPath == null || tracesPath.length() == 0) {
3200 return;
3201 }
3202
3203 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3204 StrictMode.allowThreadDiskWrites();
3205 try {
3206 final File tracesFile = new File(tracesPath);
3207 final File tracesDir = tracesFile.getParentFile();
3208 final File tracesTmp = new File(tracesDir, "__tmp__");
3209 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003210 if (!tracesDir.exists()) {
3211 tracesFile.mkdirs();
3212 if (!SELinux.restorecon(tracesDir.getPath())) {
3213 return;
3214 }
3215 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003216 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3217
3218 if (tracesFile.exists()) {
3219 tracesTmp.delete();
3220 tracesFile.renameTo(tracesTmp);
3221 }
3222 StringBuilder sb = new StringBuilder();
3223 Time tobj = new Time();
3224 tobj.set(System.currentTimeMillis());
3225 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3226 sb.append(": ");
3227 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3228 sb.append(" since ");
3229 sb.append(msg);
3230 FileOutputStream fos = new FileOutputStream(tracesFile);
3231 fos.write(sb.toString().getBytes());
3232 if (app == null) {
3233 fos.write("\n*** No application process!".getBytes());
3234 }
3235 fos.close();
3236 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3237 } catch (IOException e) {
3238 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3239 return;
3240 }
3241
3242 if (app != null) {
3243 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3244 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003245 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003246 }
3247
3248 File lastTracesFile = null;
3249 File curTracesFile = null;
3250 for (int i=9; i>=0; i--) {
3251 String name = String.format("slow%02d.txt", i);
3252 curTracesFile = new File(tracesDir, name);
3253 if (curTracesFile.exists()) {
3254 if (lastTracesFile != null) {
3255 curTracesFile.renameTo(lastTracesFile);
3256 } else {
3257 curTracesFile.delete();
3258 }
3259 }
3260 lastTracesFile = curTracesFile;
3261 }
3262 tracesFile.renameTo(curTracesFile);
3263 if (tracesTmp.exists()) {
3264 tracesTmp.renameTo(tracesFile);
3265 }
3266 } finally {
3267 StrictMode.setThreadPolicy(oldPolicy);
3268 }
3269 }
3270
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003271 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3272 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003273 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3274 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3275
Dianne Hackborn287952c2010-09-22 22:34:31 -07003276 if (mController != null) {
3277 try {
3278 // 0 == continue, -1 = kill process immediately
3279 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3280 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3281 } catch (RemoteException e) {
3282 mController = null;
3283 }
3284 }
3285
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003286 long anrTime = SystemClock.uptimeMillis();
3287 if (MONITOR_CPU_USAGE) {
3288 updateCpuStatsNow();
3289 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003290
3291 synchronized (this) {
3292 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3293 if (mShuttingDown) {
3294 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3295 return;
3296 } else if (app.notResponding) {
3297 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3298 return;
3299 } else if (app.crashing) {
3300 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3301 return;
3302 }
3303
3304 // In case we come through here for the same app before completing
3305 // this one, mark as anring now so we will bail out.
3306 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003307
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003308 // Log the ANR to the event log.
3309 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3310 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003311
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003312 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003313 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003314
3315 int parentPid = app.pid;
3316 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003317 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003318
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003319 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003320
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003321 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3322 ProcessRecord r = mLruProcesses.get(i);
3323 if (r != null && r.thread != null) {
3324 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003325 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3326 if (r.persistent) {
3327 firstPids.add(pid);
3328 } else {
3329 lastPids.put(pid, Boolean.TRUE);
3330 }
3331 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 }
3334 }
3335
Dan Egnor42471dd2010-01-07 17:25:22 -08003336 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003337 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003338 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003339 info.append("ANR in ").append(app.processName);
3340 if (activity != null && activity.shortComponentName != null) {
3341 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003342 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003343 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003345 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003347 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003348 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350
Dianne Hackborn287952c2010-09-22 22:34:31 -07003351 final ProcessStats processStats = new ProcessStats(true);
3352
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003353 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003354
Dan Egnor42471dd2010-01-07 17:25:22 -08003355 String cpuInfo = null;
3356 if (MONITOR_CPU_USAGE) {
3357 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003358 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003359 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003360 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003361 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003362 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
3364
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003365 info.append(processStats.printCurrentState(anrTime));
3366
Joe Onorato8a9b2202010-02-26 18:56:32 -08003367 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003368 if (tracesFile == null) {
3369 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3370 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3371 }
3372
Jeff Sharkeya353d262011-10-28 11:12:06 -07003373 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3374 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003375
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003376 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003378 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3379 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003381 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3382 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
3384 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003385 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 }
3387 }
3388
Dan Egnor42471dd2010-01-07 17:25:22 -08003389 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3390 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3391 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003392
3393 synchronized (this) {
3394 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003395 Slog.w(TAG, "Killing " + app + ": background ANR");
3396 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3397 app.processName, app.setAdj, "background ANR");
3398 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003399 return;
3400 }
3401
3402 // Set the app's notResponding state, and look up the errorReportReceiver
3403 makeAppNotRespondingLocked(app,
3404 activity != null ? activity.shortComponentName : null,
3405 annotation != null ? "ANR " + annotation : "ANR",
3406 info.toString());
3407
3408 // Bring up the infamous App Not Responding dialog
3409 Message msg = Message.obtain();
3410 HashMap map = new HashMap();
3411 msg.what = SHOW_NOT_RESPONDING_MSG;
3412 msg.obj = map;
3413 map.put("app", app);
3414 if (activity != null) {
3415 map.put("activity", activity);
3416 }
3417
3418 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 }
3421
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003422 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3423 if (!mLaunchWarningShown) {
3424 mLaunchWarningShown = true;
3425 mHandler.post(new Runnable() {
3426 @Override
3427 public void run() {
3428 synchronized (ActivityManagerService.this) {
3429 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3430 d.show();
3431 mHandler.postDelayed(new Runnable() {
3432 @Override
3433 public void run() {
3434 synchronized (ActivityManagerService.this) {
3435 d.dismiss();
3436 mLaunchWarningShown = false;
3437 }
3438 }
3439 }, 4000);
3440 }
3441 }
3442 });
3443 }
3444 }
3445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003447 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003448 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 int uid = Binder.getCallingUid();
3450 int pid = Binder.getCallingPid();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003451 userId = handleIncomingUserLocked(pid, uid,
3452 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 long callingId = Binder.clearCallingIdentity();
3454 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003455 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 int pkgUid = -1;
3457 synchronized(this) {
3458 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003459 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 } catch (RemoteException e) {
3461 }
3462 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003463 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 return false;
3465 }
3466 if (uid == pkgUid || checkComponentPermission(
3467 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003468 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003470 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 } else {
3472 throw new SecurityException(pid+" does not have permission:"+
3473 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3474 "for process:"+packageName);
3475 }
3476 }
3477
3478 try {
3479 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003480 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3482 Uri.fromParts("package", packageName, null));
3483 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003484 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003485 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 } catch (RemoteException e) {
3487 }
3488 } finally {
3489 Binder.restoreCallingIdentity(callingId);
3490 }
3491 return true;
3492 }
3493
Dianne Hackborn1676c852012-09-10 14:52:30 -07003494 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003495 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3496 != PackageManager.PERMISSION_GRANTED &&
3497 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3498 != PackageManager.PERMISSION_GRANTED) {
3499 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 + Binder.getCallingPid()
3501 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003502 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003503 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 throw new SecurityException(msg);
3505 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003506
3507 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3508 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 long callingId = Binder.clearCallingIdentity();
3510 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003511 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003513 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003515 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 } catch (RemoteException e) {
3517 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003518 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003519 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 return;
3521 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003522 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003523 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3524 }
3525 } finally {
3526 Binder.restoreCallingIdentity(callingId);
3527 }
3528 }
3529
3530 public void killAllBackgroundProcesses() {
3531 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3532 != PackageManager.PERMISSION_GRANTED) {
3533 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3534 + Binder.getCallingPid()
3535 + ", uid=" + Binder.getCallingUid()
3536 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3537 Slog.w(TAG, msg);
3538 throw new SecurityException(msg);
3539 }
3540
3541 long callingId = Binder.clearCallingIdentity();
3542 try {
3543 synchronized(this) {
3544 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3545 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3546 final int NA = apps.size();
3547 for (int ia=0; ia<NA; ia++) {
3548 ProcessRecord app = apps.valueAt(ia);
3549 if (app.persistent) {
3550 // we don't kill persistent processes
3551 continue;
3552 }
3553 if (app.removed) {
3554 procs.add(app);
3555 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3556 app.removed = true;
3557 procs.add(app);
3558 }
3559 }
3560 }
3561
3562 int N = procs.size();
3563 for (int i=0; i<N; i++) {
3564 removeProcessLocked(procs.get(i), false, true, "kill all background");
3565 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003566 }
3567 } finally {
3568 Binder.restoreCallingIdentity(callingId);
3569 }
3570 }
3571
Dianne Hackborn1676c852012-09-10 14:52:30 -07003572 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003573 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3574 != PackageManager.PERMISSION_GRANTED) {
3575 String msg = "Permission Denial: forceStopPackage() from pid="
3576 + Binder.getCallingPid()
3577 + ", uid=" + Binder.getCallingUid()
3578 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003579 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003580 throw new SecurityException(msg);
3581 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003582 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3583 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003584 long callingId = Binder.clearCallingIdentity();
3585 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003586 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003587 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003588 int[] users = userId == UserHandle.USER_ALL
3589 ? getUsersLocked() : new int[] { userId };
3590 for (int user : users) {
3591 int pkgUid = -1;
3592 try {
3593 pkgUid = pm.getPackageUid(packageName, user);
3594 } catch (RemoteException e) {
3595 }
3596 if (pkgUid == -1) {
3597 Slog.w(TAG, "Invalid packageName: " + packageName);
3598 continue;
3599 }
3600 try {
3601 pm.setPackageStoppedState(packageName, true, user);
3602 } catch (RemoteException e) {
3603 } catch (IllegalArgumentException e) {
3604 Slog.w(TAG, "Failed trying to unstop package "
3605 + packageName + ": " + e);
3606 }
3607 if (isUserRunningLocked(user)) {
3608 forceStopPackageLocked(packageName, pkgUid);
3609 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 }
3612 } finally {
3613 Binder.restoreCallingIdentity(callingId);
3614 }
3615 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003616
3617 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003618 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003619 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003620 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003621 if (pkg == null) {
3622 return;
3623 }
3624 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003625 if (appid < 0) {
3626 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003627 return;
3628 }
3629 int callerUid = Binder.getCallingUid();
3630 // Only the system server can kill an application
3631 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003632 // Post an aysnc message to kill the application
3633 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003634 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003635 msg.arg2 = 0;
3636 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003637 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003638 } else {
3639 throw new SecurityException(callerUid + " cannot kill pkg: " +
3640 pkg);
3641 }
3642 }
3643
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003644 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003645 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003646
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003647 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003648 final int uid = Binder.getCallingUid();
3649 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003650 try {
3651 synchronized (this) {
3652 // Only allow this from foreground processes, so that background
3653 // applications can't abuse it to prevent system UI from being shown.
3654 if (uid >= Process.FIRST_APPLICATION_UID) {
3655 ProcessRecord proc;
3656 synchronized (mPidsSelfLocked) {
3657 proc = mPidsSelfLocked.get(pid);
3658 }
3659 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3660 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3661 + " from background process " + proc);
3662 return;
3663 }
3664 }
3665 closeSystemDialogsLocked(reason);
3666 }
3667 } finally {
3668 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003669 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003670 }
3671
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003672 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003673 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003674 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003675 if (reason != null) {
3676 intent.putExtra("reason", reason);
3677 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003678 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003679
Dianne Hackborne302a162012-05-15 14:58:32 -07003680 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3681 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003682 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003683 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003684 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003685 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003686 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003687
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003688 broadcastIntentLocked(null, null, intent, null,
3689 null, 0, null, null, null, false, false, -1,
3690 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003691 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003692
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003693 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003694 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003695 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003696 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3697 for (int i=pids.length-1; i>=0; i--) {
3698 infos[i] = new Debug.MemoryInfo();
3699 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003700 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003701 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003702 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003703
Dianne Hackbornb437e092011-08-05 17:50:29 -07003704 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003705 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003706 long[] pss = new long[pids.length];
3707 for (int i=pids.length-1; i>=0; i--) {
3708 pss[i] = Debug.getPss(pids[i]);
3709 }
3710 return pss;
3711 }
3712
Christopher Tate5e1ab332009-09-01 20:32:49 -07003713 public void killApplicationProcess(String processName, int uid) {
3714 if (processName == null) {
3715 return;
3716 }
3717
3718 int callerUid = Binder.getCallingUid();
3719 // Only the system server can kill an application
3720 if (callerUid == Process.SYSTEM_UID) {
3721 synchronized (this) {
3722 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003723 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003724 try {
3725 app.thread.scheduleSuicide();
3726 } catch (RemoteException e) {
3727 // If the other end already died, then our work here is done.
3728 }
3729 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003730 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003731 + processName + " / " + uid);
3732 }
3733 }
3734 } else {
3735 throw new SecurityException(callerUid + " cannot kill app process: " +
3736 processName);
3737 }
3738 }
3739
Dianne Hackborn03abb812010-01-04 18:43:19 -08003740 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003741 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3742 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3744 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003745 if (!mProcessesReady) {
3746 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 intent.putExtra(Intent.EXTRA_UID, uid);
3749 broadcastIntentLocked(null, null, intent,
3750 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003751 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003752 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003754
3755 private void forceStopUserLocked(int userId) {
3756 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3757 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3758 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3759 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3760 broadcastIntentLocked(null, null, intent,
3761 null, null, 0, null, null, null,
3762 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003763 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003764 }
3765
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003766 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003767 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3768 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003769 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770
Dianne Hackborn03abb812010-01-04 18:43:19 -08003771 // Remove all processes this package may have touched: all with the
3772 // same UID (except for the system or root user), and all whose name
3773 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003774 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003775 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3776 final int NA = apps.size();
3777 for (int ia=0; ia<NA; ia++) {
3778 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003779 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003780 // we don't kill persistent processes
3781 continue;
3782 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003783 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003784 if (doit) {
3785 procs.add(app);
3786 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003787 continue;
3788 }
3789
3790 // Skip process if it doesn't meet our oom adj requirement.
3791 if (app.setAdj < minOomAdj) {
3792 continue;
3793 }
3794
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003795 // If no package is specified, we call all processes under the
3796 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003797 if (packageName == null) {
3798 if (app.userId != userId) {
3799 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003800 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003801 // Package has been specified, we want to hit all processes
3802 // that match it. We need to qualify this by the processes
3803 // that are running under the specified app and user ID.
3804 } else {
3805 if (UserHandle.getAppId(app.uid) != appId) {
3806 continue;
3807 }
3808 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3809 continue;
3810 }
3811 if (!app.pkgList.contains(packageName)) {
3812 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003813 }
3814 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003815
3816 // Process has passed all conditions, kill it!
3817 if (!doit) {
3818 return true;
3819 }
3820 app.removed = true;
3821 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003822 }
3823 }
3824
3825 int N = procs.size();
3826 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003827 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003828 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003829 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003830 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003831
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003832 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003833 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003834 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003835 int i;
3836 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003838 if (userId == UserHandle.USER_ALL && name == null) {
3839 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3840 }
3841
3842 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003844 appId = UserHandle.getAppId(
3845 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 } catch (RemoteException e) {
3847 }
3848 }
3849
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003850 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003851 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003852 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3853 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003854 } else {
3855 Slog.i(TAG, "Force stopping user " + userId);
3856 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003857
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003858 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3859 while (badApps.hasNext()) {
3860 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003861 for (i=ba.size()-1; i>=0; i--) {
3862 boolean remove = false;
3863 final int entUid = ba.keyAt(i);
3864 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003865 if (userId == UserHandle.USER_ALL) {
3866 if (UserHandle.getAppId(entUid) == appId) {
3867 remove = true;
3868 }
3869 } else {
3870 if (entUid == UserHandle.getUid(userId, appId)) {
3871 remove = true;
3872 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003873 }
3874 } else if (UserHandle.getUserId(entUid) == userId) {
3875 remove = true;
3876 }
3877 if (remove) {
3878 ba.removeAt(i);
3879 }
3880 }
3881 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003882 badApps.remove();
3883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 }
3885 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003886
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003887 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3888 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003889 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003891 TaskRecord lastTask = null;
3892 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003893 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003894 final boolean samePackage = r.packageName.equals(name)
3895 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003896 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003897 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003898 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003899 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003900 if (r.finishing) {
3901 // If this activity is just finishing, then it is not
3902 // interesting as far as something to stop.
3903 continue;
3904 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003905 return true;
3906 }
3907 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003908 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003909 if (samePackage) {
3910 if (r.app != null) {
3911 r.app.removed = true;
3912 }
3913 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003915 lastTask = r.task;
3916 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003917 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003918 i--;
3919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 }
3921 }
3922
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003923 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3924 if (!doit) {
3925 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003927 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003929
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003930 if (name == null) {
3931 // Remove all sticky broadcasts from this user.
3932 mStickyBroadcasts.remove(userId);
3933 }
3934
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003935 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003936 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3937 userId, providers)) {
3938 if (!doit) {
3939 return true;
3940 }
3941 didSomething = true;
3942 }
3943 N = providers.size();
3944 for (i=0; i<N; i++) {
3945 removeDyingProviderLocked(null, providers.get(i), true);
3946 }
3947
3948 if (mIntentSenderRecords.size() > 0) {
3949 Iterator<WeakReference<PendingIntentRecord>> it
3950 = mIntentSenderRecords.values().iterator();
3951 while (it.hasNext()) {
3952 WeakReference<PendingIntentRecord> wpir = it.next();
3953 if (wpir == null) {
3954 it.remove();
3955 continue;
3956 }
3957 PendingIntentRecord pir = wpir.get();
3958 if (pir == null) {
3959 it.remove();
3960 continue;
3961 }
3962 if (name == null) {
3963 // Stopping user, remove all objects for the user.
3964 if (pir.key.userId != userId) {
3965 // Not the same user, skip it.
3966 continue;
3967 }
3968 } else {
3969 if (UserHandle.getAppId(pir.uid) != appId) {
3970 // Different app id, skip it.
3971 continue;
3972 }
3973 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3974 // Different user, skip it.
3975 continue;
3976 }
3977 if (!pir.key.packageName.equals(name)) {
3978 // Different package, skip it.
3979 continue;
3980 }
3981 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003982 if (!doit) {
3983 return true;
3984 }
3985 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003986 it.remove();
3987 pir.canceled = true;
3988 if (pir.key.activity != null) {
3989 pir.key.activity.pendingResults.remove(pir.ref);
3990 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003991 }
3992 }
3993
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003994 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003995 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003996 AttributeCache ac = AttributeCache.instance();
3997 if (ac != null) {
3998 ac.removePackage(name);
3999 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004000 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004001 if (mBooted) {
4002 mMainStack.resumeTopActivityLocked(null);
4003 mMainStack.scheduleIdleLocked();
4004 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004005 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004006
4007 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 }
4009
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004010 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004011 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004013 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004014 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004015 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 + "/" + uid + ")");
4017
4018 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004019 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004020 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004021 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4022 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004023 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 boolean needRestart = false;
4026 if (app.pid > 0 && app.pid != MY_PID) {
4027 int pid = app.pid;
4028 synchronized (mPidsSelfLocked) {
4029 mPidsSelfLocked.remove(pid);
4030 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4031 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004032 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004033 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004034 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004035 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004037 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004039 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 } else {
4041 needRestart = true;
4042 }
4043 }
4044 } else {
4045 mRemovedProcesses.add(app);
4046 }
4047
4048 return needRestart;
4049 }
4050
4051 private final void processStartTimedOutLocked(ProcessRecord app) {
4052 final int pid = app.pid;
4053 boolean gone = false;
4054 synchronized (mPidsSelfLocked) {
4055 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4056 if (knownApp != null && knownApp.thread == null) {
4057 mPidsSelfLocked.remove(pid);
4058 gone = true;
4059 }
4060 }
4061
4062 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004063 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004064 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004065 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004066 mProcessNames.remove(app.processName, app.uid);
4067 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004068 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004069 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4070 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004071 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004072 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004073 // Take care of any launching providers waiting for this process.
4074 checkAppInLaunchingProvidersLocked(app, true);
4075 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004076 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004077 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4078 app.processName, app.setAdj, "start timeout");
4079 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004080 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004081 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004082 try {
4083 IBackupManager bm = IBackupManager.Stub.asInterface(
4084 ServiceManager.getService(Context.BACKUP_SERVICE));
4085 bm.agentDisconnected(app.info.packageName);
4086 } catch (RemoteException e) {
4087 // Can't happen; the backup manager is local
4088 }
4089 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004090 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004091 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004092 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004095 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 }
4097 }
4098
4099 private final boolean attachApplicationLocked(IApplicationThread thread,
4100 int pid) {
4101
4102 // Find the application record that is being attached... either via
4103 // the pid if we are running in multiple processes, or just pull the
4104 // next app record if we are emulating process with anonymous threads.
4105 ProcessRecord app;
4106 if (pid != MY_PID && pid >= 0) {
4107 synchronized (mPidsSelfLocked) {
4108 app = mPidsSelfLocked.get(pid);
4109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 } else {
4111 app = null;
4112 }
4113
4114 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004115 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004117 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004119 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 } else {
4121 try {
4122 thread.scheduleExit();
4123 } catch (Exception e) {
4124 // Ignore exceptions.
4125 }
4126 }
4127 return false;
4128 }
4129
4130 // If this application record is still attached to a previous
4131 // process, clean it up now.
4132 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004133 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
4135
4136 // Tell the process all about itself.
4137
Joe Onorato8a9b2202010-02-26 18:56:32 -08004138 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 TAG, "Binding process pid " + pid + " to record " + app);
4140
4141 String processName = app.processName;
4142 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004143 AppDeathRecipient adr = new AppDeathRecipient(
4144 app, pid, thread);
4145 thread.asBinder().linkToDeath(adr, 0);
4146 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 } catch (RemoteException e) {
4148 app.resetPackageList();
4149 startProcessLocked(app, "link fail", processName);
4150 return false;
4151 }
4152
Doug Zongker2bec3d42009-12-04 12:52:44 -08004153 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154
4155 app.thread = thread;
4156 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004157 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4158 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 app.forcingToForeground = null;
4160 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004161 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 app.debugging = false;
4163
4164 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4165
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004166 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004167 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004169 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004170 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004171 }
4172
Joe Onorato8a9b2202010-02-26 18:56:32 -08004173 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 TAG, "New app record " + app
4175 + " thread=" + thread.asBinder() + " pid=" + pid);
4176 try {
4177 int testMode = IApplicationThread.DEBUG_OFF;
4178 if (mDebugApp != null && mDebugApp.equals(processName)) {
4179 testMode = mWaitForDebugger
4180 ? IApplicationThread.DEBUG_WAIT
4181 : IApplicationThread.DEBUG_ON;
4182 app.debugging = true;
4183 if (mDebugTransient) {
4184 mDebugApp = mOrigDebugApp;
4185 mWaitForDebugger = mOrigWaitForDebugger;
4186 }
4187 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004188 String profileFile = app.instrumentationProfileFile;
4189 ParcelFileDescriptor profileFd = null;
4190 boolean profileAutoStop = false;
4191 if (mProfileApp != null && mProfileApp.equals(processName)) {
4192 mProfileProc = app;
4193 profileFile = mProfileFile;
4194 profileFd = mProfileFd;
4195 profileAutoStop = mAutoStopProfiler;
4196 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004197 boolean enableOpenGlTrace = false;
4198 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4199 enableOpenGlTrace = true;
4200 mOpenGlTraceApp = null;
4201 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004202
Christopher Tate181fafa2009-05-14 11:12:14 -07004203 // If the app is being launched for restore or full backup, set it up specially
4204 boolean isRestrictedBackupMode = false;
4205 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4206 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004207 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004208 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4209 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004210
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004211 ensurePackageDexOpt(app.instrumentationInfo != null
4212 ? app.instrumentationInfo.packageName
4213 : app.info.packageName);
4214 if (app.instrumentationClass != null) {
4215 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004216 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004217 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004218 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004219 ApplicationInfo appInfo = app.instrumentationInfo != null
4220 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004221 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004222 if (profileFd != null) {
4223 profileFd = profileFd.dup();
4224 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004225 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004226 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004227 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4228 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004229 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004230 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004231 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004232 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 } catch (Exception e) {
4234 // todo: Yikes! What should we do? For now we will try to
4235 // start another process, but that could easily get us in
4236 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004237 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238
4239 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004240 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 startProcessLocked(app, "bind fail", processName);
4242 return false;
4243 }
4244
4245 // Remove this record from the list of starting applications.
4246 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004247 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4248 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 mProcessesOnHold.remove(app);
4250
4251 boolean badApp = false;
4252 boolean didSomething = false;
4253
4254 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004255 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004256 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004257 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 && processName.equals(hr.processName)) {
4259 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004260 if (mHeadless) {
4261 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4262 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263 didSomething = true;
4264 }
4265 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004266 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 + hr.intent.getComponent().flattenToShortString(), e);
4268 badApp = true;
4269 }
4270 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004271 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 }
4273 }
4274
4275 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004276 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004278 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 badApp = true;
4281 }
4282 }
4283
Christopher Tatef46723b2012-01-26 14:19:24 -08004284 // Check if a next-broadcast receiver is in this process...
4285 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004287 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004289 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292 }
4293
Christopher Tate181fafa2009-05-14 11:12:14 -07004294 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004295 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004296 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004297 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004298 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004299 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4300 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4301 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004302 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004303 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004304 e.printStackTrace();
4305 }
4306 }
4307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 if (badApp) {
4309 // todo: Also need to kill application to deal with all
4310 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004311 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 return false;
4313 }
4314
4315 if (!didSomething) {
4316 updateOomAdjLocked();
4317 }
4318
4319 return true;
4320 }
4321
4322 public final void attachApplication(IApplicationThread thread) {
4323 synchronized (this) {
4324 int callingPid = Binder.getCallingPid();
4325 final long origId = Binder.clearCallingIdentity();
4326 attachApplicationLocked(thread, callingPid);
4327 Binder.restoreCallingIdentity(origId);
4328 }
4329 }
4330
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004331 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004333 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4334 if (stopProfiling) {
4335 synchronized (this) {
4336 if (mProfileProc == r.app) {
4337 if (mProfileFd != null) {
4338 try {
4339 mProfileFd.close();
4340 } catch (IOException e) {
4341 }
4342 clearProfilerLocked();
4343 }
4344 }
4345 }
4346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 Binder.restoreCallingIdentity(origId);
4348 }
4349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004351 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004352 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004354
4355 synchronized (this) {
4356 updateEventDispatchingLocked();
4357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 }
4359
Dianne Hackborn661cd522011-08-22 00:26:20 -07004360 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004361 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004362 mWindowManager.showBootMessage(msg, always);
4363 }
4364
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004365 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004366 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004367 final long token = Binder.clearCallingIdentity();
4368 try {
4369 synchronized (this) {
4370 if (mLockScreenShown) {
4371 mLockScreenShown = false;
4372 comeOutOfSleepIfNeededLocked();
4373 }
4374 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004375 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004376 } finally {
4377 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004378 }
4379 }
4380
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004381 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004382 IntentFilter pkgFilter = new IntentFilter();
4383 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4384 pkgFilter.addDataScheme("package");
4385 mContext.registerReceiver(new BroadcastReceiver() {
4386 @Override
4387 public void onReceive(Context context, Intent intent) {
4388 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4389 if (pkgs != null) {
4390 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004391 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004392 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4393 setResultCode(Activity.RESULT_OK);
4394 return;
4395 }
4396 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004397 }
4398 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004399 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004400 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004401
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004402 synchronized (this) {
4403 // Ensure that any processes we had put on hold are now started
4404 // up.
4405 final int NP = mProcessesOnHold.size();
4406 if (NP > 0) {
4407 ArrayList<ProcessRecord> procs =
4408 new ArrayList<ProcessRecord>(mProcessesOnHold);
4409 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004410 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4411 + procs.get(ip));
4412 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004413 }
4414 }
4415
4416 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004417 // Start looking for apps that are abusing wake locks.
4418 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004419 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004420 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004421 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004422 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004423 for (int i=0; i<mStartedUsers.size(); i++) {
4424 UserStartedState uss = mStartedUsers.valueAt(i);
4425 if (uss.mState == UserStartedState.STATE_BOOTING) {
4426 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004427 final int userId = mStartedUsers.keyAt(i);
4428 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4429 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4430 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004431 null, null, 0, null, null,
4432 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004433 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004434 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004435 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004436 }
4437 }
4438 }
4439
4440 final void ensureBootCompleted() {
4441 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004442 boolean enableScreen;
4443 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004444 booting = mBooting;
4445 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004446 enableScreen = !mBooted;
4447 mBooted = true;
4448 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004449
4450 if (booting) {
4451 finishBooting();
4452 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004453
4454 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004455 enableScreenAfterBoot();
4456 }
4457 }
4458
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004459 public final void activityPaused(IBinder token) {
4460 final long origId = Binder.clearCallingIdentity();
4461 mMainStack.activityPaused(token, false);
4462 Binder.restoreCallingIdentity(origId);
4463 }
4464
4465 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4466 CharSequence description) {
4467 if (localLOGV) Slog.v(
4468 TAG, "Activity stopped: token=" + token);
4469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 // Refuse possible leaked file descriptors
4471 if (icicle != null && icicle.hasFileDescriptors()) {
4472 throw new IllegalArgumentException("File descriptors passed in Bundle");
4473 }
4474
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004475 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476
4477 final long origId = Binder.clearCallingIdentity();
4478
4479 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004480 r = mMainStack.isInStackLocked(token);
4481 if (r != null) {
4482 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 }
4484 }
4485
4486 if (r != null) {
4487 sendPendingThumbnail(r, null, null, null, false);
4488 }
4489
4490 trimApplications();
4491
4492 Binder.restoreCallingIdentity(origId);
4493 }
4494
4495 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004496 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004497 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 }
4499
4500 public String getCallingPackage(IBinder token) {
4501 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004502 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004503 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
4505 }
4506
4507 public ComponentName getCallingActivity(IBinder token) {
4508 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004509 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 return r != null ? r.intent.getComponent() : null;
4511 }
4512 }
4513
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004514 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004515 ActivityRecord r = mMainStack.isInStackLocked(token);
4516 if (r == null) {
4517 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004519 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521
4522 public ComponentName getActivityClassForToken(IBinder token) {
4523 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004524 ActivityRecord r = mMainStack.isInStackLocked(token);
4525 if (r == null) {
4526 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004528 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 }
4530 }
4531
4532 public String getPackageForToken(IBinder token) {
4533 synchronized(this) {
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.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 }
4540 }
4541
4542 public IIntentSender getIntentSender(int type,
4543 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004544 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004545 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004546 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004548 if (intents != null) {
4549 if (intents.length < 1) {
4550 throw new IllegalArgumentException("Intents array length must be >= 1");
4551 }
4552 for (int i=0; i<intents.length; i++) {
4553 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004554 if (intent != null) {
4555 if (intent.hasFileDescriptors()) {
4556 throw new IllegalArgumentException("File descriptors passed in Intent");
4557 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004558 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004559 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4560 throw new IllegalArgumentException(
4561 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4562 }
4563 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004564 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004565 }
4566 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004567 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004568 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004569 }
4570 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004571 if (options != null) {
4572 if (options.hasFileDescriptors()) {
4573 throw new IllegalArgumentException("File descriptors passed in options");
4574 }
4575 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 synchronized(this) {
4578 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004579 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4580 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004582 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004583 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004584 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4585 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 String msg = "Permission Denial: getIntentSender() from pid="
4587 + Binder.getCallingPid()
4588 + ", uid=" + Binder.getCallingUid()
4589 + ", (need uid=" + uid + ")"
4590 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004591 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 throw new SecurityException(msg);
4593 }
4594 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004595
4596 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004597 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 } catch (RemoteException e) {
4600 throw new SecurityException(e);
4601 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004602 }
4603 }
4604
Dianne Hackborn41203752012-08-31 14:05:51 -07004605 IIntentSender getIntentSenderLocked(int type, String packageName,
4606 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004607 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4608 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004609 if (DEBUG_MU)
4610 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004611 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004612 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004613 activity = mMainStack.isInStackLocked(token);
4614 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004615 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004617 if (activity.finishing) {
4618 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004620 }
4621
4622 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4623 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4624 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4625 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4626 |PendingIntent.FLAG_UPDATE_CURRENT);
4627
4628 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4629 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004630 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004631 WeakReference<PendingIntentRecord> ref;
4632 ref = mIntentSenderRecords.get(key);
4633 PendingIntentRecord rec = ref != null ? ref.get() : null;
4634 if (rec != null) {
4635 if (!cancelCurrent) {
4636 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004637 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004638 rec.key.requestIntent.replaceExtras(intents != null ?
4639 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004640 }
4641 if (intents != null) {
4642 intents[intents.length-1] = rec.key.requestIntent;
4643 rec.key.allIntents = intents;
4644 rec.key.allResolvedTypes = resolvedTypes;
4645 } else {
4646 rec.key.allIntents = null;
4647 rec.key.allResolvedTypes = null;
4648 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004650 return rec;
4651 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004652 rec.canceled = true;
4653 mIntentSenderRecords.remove(key);
4654 }
4655 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 return rec;
4657 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004658 rec = new PendingIntentRecord(this, key, callingUid);
4659 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004660 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004661 if (activity.pendingResults == null) {
4662 activity.pendingResults
4663 = new HashSet<WeakReference<PendingIntentRecord>>();
4664 }
4665 activity.pendingResults.add(rec.ref);
4666 }
4667 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 }
4669
4670 public void cancelIntentSender(IIntentSender sender) {
4671 if (!(sender instanceof PendingIntentRecord)) {
4672 return;
4673 }
4674 synchronized(this) {
4675 PendingIntentRecord rec = (PendingIntentRecord)sender;
4676 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004677 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004678 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4679 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 String msg = "Permission Denial: cancelIntentSender() from pid="
4681 + Binder.getCallingPid()
4682 + ", uid=" + Binder.getCallingUid()
4683 + " is not allowed to cancel packges "
4684 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004685 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 throw new SecurityException(msg);
4687 }
4688 } catch (RemoteException e) {
4689 throw new SecurityException(e);
4690 }
4691 cancelIntentSenderLocked(rec, true);
4692 }
4693 }
4694
4695 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4696 rec.canceled = true;
4697 mIntentSenderRecords.remove(rec.key);
4698 if (cleanActivity && rec.key.activity != null) {
4699 rec.key.activity.pendingResults.remove(rec.ref);
4700 }
4701 }
4702
4703 public String getPackageForIntentSender(IIntentSender pendingResult) {
4704 if (!(pendingResult instanceof PendingIntentRecord)) {
4705 return null;
4706 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004707 try {
4708 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4709 return res.key.packageName;
4710 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 }
4712 return null;
4713 }
4714
Christopher Tatec4a07d12012-04-06 14:19:13 -07004715 public int getUidForIntentSender(IIntentSender sender) {
4716 if (sender instanceof PendingIntentRecord) {
4717 try {
4718 PendingIntentRecord res = (PendingIntentRecord)sender;
4719 return res.uid;
4720 } catch (ClassCastException e) {
4721 }
4722 }
4723 return -1;
4724 }
4725
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004726 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4727 if (!(pendingResult instanceof PendingIntentRecord)) {
4728 return false;
4729 }
4730 try {
4731 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4732 if (res.key.allIntents == null) {
4733 return false;
4734 }
4735 for (int i=0; i<res.key.allIntents.length; i++) {
4736 Intent intent = res.key.allIntents[i];
4737 if (intent.getPackage() != null && intent.getComponent() != null) {
4738 return false;
4739 }
4740 }
4741 return true;
4742 } catch (ClassCastException e) {
4743 }
4744 return false;
4745 }
4746
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004747 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4748 if (!(pendingResult instanceof PendingIntentRecord)) {
4749 return false;
4750 }
4751 try {
4752 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4753 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4754 return true;
4755 }
4756 return false;
4757 } catch (ClassCastException e) {
4758 }
4759 return false;
4760 }
4761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 public void setProcessLimit(int max) {
4763 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4764 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004765 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004766 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004767 mProcessLimitOverride = max;
4768 }
4769 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 }
4771
4772 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004773 synchronized (this) {
4774 return mProcessLimitOverride;
4775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777
4778 void foregroundTokenDied(ForegroundToken token) {
4779 synchronized (ActivityManagerService.this) {
4780 synchronized (mPidsSelfLocked) {
4781 ForegroundToken cur
4782 = mForegroundProcesses.get(token.pid);
4783 if (cur != token) {
4784 return;
4785 }
4786 mForegroundProcesses.remove(token.pid);
4787 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4788 if (pr == null) {
4789 return;
4790 }
4791 pr.forcingToForeground = null;
4792 pr.foregroundServices = false;
4793 }
4794 updateOomAdjLocked();
4795 }
4796 }
4797
4798 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4799 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4800 "setProcessForeground()");
4801 synchronized(this) {
4802 boolean changed = false;
4803
4804 synchronized (mPidsSelfLocked) {
4805 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004806 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004807 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 return;
4809 }
4810 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4811 if (oldToken != null) {
4812 oldToken.token.unlinkToDeath(oldToken, 0);
4813 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004814 if (pr != null) {
4815 pr.forcingToForeground = null;
4816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 changed = true;
4818 }
4819 if (isForeground && token != null) {
4820 ForegroundToken newToken = new ForegroundToken() {
4821 public void binderDied() {
4822 foregroundTokenDied(this);
4823 }
4824 };
4825 newToken.pid = pid;
4826 newToken.token = token;
4827 try {
4828 token.linkToDeath(newToken, 0);
4829 mForegroundProcesses.put(pid, newToken);
4830 pr.forcingToForeground = token;
4831 changed = true;
4832 } catch (RemoteException e) {
4833 // If the process died while doing this, we will later
4834 // do the cleanup with the process death link.
4835 }
4836 }
4837 }
4838
4839 if (changed) {
4840 updateOomAdjLocked();
4841 }
4842 }
4843 }
4844
4845 // =========================================================
4846 // PERMISSIONS
4847 // =========================================================
4848
4849 static class PermissionController extends IPermissionController.Stub {
4850 ActivityManagerService mActivityManagerService;
4851 PermissionController(ActivityManagerService activityManagerService) {
4852 mActivityManagerService = activityManagerService;
4853 }
4854
4855 public boolean checkPermission(String permission, int pid, int uid) {
4856 return mActivityManagerService.checkPermission(permission, pid,
4857 uid) == PackageManager.PERMISSION_GRANTED;
4858 }
4859 }
4860
4861 /**
4862 * This can be called with or without the global lock held.
4863 */
4864 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004865 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004866 // We might be performing an operation on behalf of an indirect binder
4867 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4868 // client identity accordingly before proceeding.
4869 Identity tlsIdentity = sCallerIdentity.get();
4870 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004871 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4873 uid = tlsIdentity.uid;
4874 pid = tlsIdentity.pid;
4875 }
4876
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004877 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 return PackageManager.PERMISSION_GRANTED;
4879 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004880
4881 return ActivityManager.checkComponentPermission(permission, uid,
4882 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 }
4884
4885 /**
4886 * As the only public entry point for permissions checking, this method
4887 * can enforce the semantic that requesting a check on a null global
4888 * permission is automatically denied. (Internally a null permission
4889 * string is used when calling {@link #checkComponentPermission} in cases
4890 * when only uid-based security is needed.)
4891 *
4892 * This can be called with or without the global lock held.
4893 */
4894 public int checkPermission(String permission, int pid, int uid) {
4895 if (permission == null) {
4896 return PackageManager.PERMISSION_DENIED;
4897 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004898 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 }
4900
4901 /**
4902 * Binder IPC calls go through the public entry point.
4903 * This can be called with or without the global lock held.
4904 */
4905 int checkCallingPermission(String permission) {
4906 return checkPermission(permission,
4907 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004908 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004909 }
4910
4911 /**
4912 * This can be called with or without the global lock held.
4913 */
4914 void enforceCallingPermission(String permission, String func) {
4915 if (checkCallingPermission(permission)
4916 == PackageManager.PERMISSION_GRANTED) {
4917 return;
4918 }
4919
4920 String msg = "Permission Denial: " + func + " from pid="
4921 + Binder.getCallingPid()
4922 + ", uid=" + Binder.getCallingUid()
4923 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004924 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 throw new SecurityException(msg);
4926 }
4927
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004928 /**
4929 * Determine if UID is holding permissions required to access {@link Uri} in
4930 * the given {@link ProviderInfo}. Final permission checking is always done
4931 * in {@link ContentProvider}.
4932 */
4933 private final boolean checkHoldingPermissionsLocked(
4934 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004935 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4936 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004937
4938 if (pi.applicationInfo.uid == uid) {
4939 return true;
4940 } else if (!pi.exported) {
4941 return false;
4942 }
4943
4944 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4945 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004947 // check if target holds top-level <provider> permissions
4948 if (!readMet && pi.readPermission != null
4949 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4950 readMet = true;
4951 }
4952 if (!writeMet && pi.writePermission != null
4953 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4954 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004956
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004957 // track if unprotected read/write is allowed; any denied
4958 // <path-permission> below removes this ability
4959 boolean allowDefaultRead = pi.readPermission == null;
4960 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004961
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004962 // check if target holds any <path-permission> that match uri
4963 final PathPermission[] pps = pi.pathPermissions;
4964 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004965 final String path = uri.getPath();
4966 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004967 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004968 i--;
4969 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004970 if (pp.match(path)) {
4971 if (!readMet) {
4972 final String pprperm = pp.getReadPermission();
4973 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4974 + pprperm + " for " + pp.getPath()
4975 + ": match=" + pp.match(path)
4976 + " check=" + pm.checkUidPermission(pprperm, uid));
4977 if (pprperm != null) {
4978 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4979 readMet = true;
4980 } else {
4981 allowDefaultRead = false;
4982 }
4983 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004984 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004985 if (!writeMet) {
4986 final String ppwperm = pp.getWritePermission();
4987 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4988 + ppwperm + " for " + pp.getPath()
4989 + ": match=" + pp.match(path)
4990 + " check=" + pm.checkUidPermission(ppwperm, uid));
4991 if (ppwperm != null) {
4992 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4993 writeMet = true;
4994 } else {
4995 allowDefaultWrite = false;
4996 }
4997 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004998 }
4999 }
5000 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005001 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005002
5003 // grant unprotected <provider> read/write, if not blocked by
5004 // <path-permission> above
5005 if (allowDefaultRead) readMet = true;
5006 if (allowDefaultWrite) writeMet = true;
5007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005008 } catch (RemoteException e) {
5009 return false;
5010 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005011
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005012 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005013 }
5014
5015 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5016 int modeFlags) {
5017 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005018 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 return true;
5020 }
5021 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5022 if (perms == null) return false;
5023 UriPermission perm = perms.get(uri);
5024 if (perm == null) return false;
5025 return (modeFlags&perm.modeFlags) == modeFlags;
5026 }
5027
5028 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005029 enforceNotIsolatedCaller("checkUriPermission");
5030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 // Another redirected-binder-call permissions check as in
5032 // {@link checkComponentPermission}.
5033 Identity tlsIdentity = sCallerIdentity.get();
5034 if (tlsIdentity != null) {
5035 uid = tlsIdentity.uid;
5036 pid = tlsIdentity.pid;
5037 }
5038
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005039 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005040 // Our own process gets to do everything.
5041 if (pid == MY_PID) {
5042 return PackageManager.PERMISSION_GRANTED;
5043 }
5044 synchronized(this) {
5045 return checkUriPermissionLocked(uri, uid, modeFlags)
5046 ? PackageManager.PERMISSION_GRANTED
5047 : PackageManager.PERMISSION_DENIED;
5048 }
5049 }
5050
Dianne Hackborn39792d22010-08-19 18:01:52 -07005051 /**
5052 * Check if the targetPkg can be granted permission to access uri by
5053 * the callingUid using the given modeFlags. Throws a security exception
5054 * if callingUid is not allowed to do this. Returns the uid of the target
5055 * if the URI permission grant should be performed; returns -1 if it is not
5056 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005057 * If you already know the uid of the target, you can supply it in
5058 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005059 */
5060 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005061 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5063 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5064 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005065 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 }
5067
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005068 if (targetPkg != null) {
5069 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5070 "Checking grant " + targetPkg + " permission to " + uri);
5071 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005072
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005073 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074
5075 // If this is not a content: uri, we can't do anything with it.
5076 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005077 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005078 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005079 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 }
5081
5082 String name = uri.getAuthority();
5083 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005084 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005085 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 if (cpr != null) {
5087 pi = cpr.info;
5088 } else {
5089 try {
5090 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005091 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 } catch (RemoteException ex) {
5093 }
5094 }
5095 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005096 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005097 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 }
5099
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005100 int targetUid = lastTargetUid;
5101 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005102 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005103 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005104 if (targetUid < 0) {
5105 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5106 "Can't grant URI permission no uid for: " + targetPkg);
5107 return -1;
5108 }
5109 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005110 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 }
5113
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005114 if (targetUid >= 0) {
5115 // First... does the target actually need this permission?
5116 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5117 // No need to grant the target this permission.
5118 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5119 "Target " + targetPkg + " already has full permission to " + uri);
5120 return -1;
5121 }
5122 } else {
5123 // First... there is no target package, so can anyone access it?
5124 boolean allowed = pi.exported;
5125 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5126 if (pi.readPermission != null) {
5127 allowed = false;
5128 }
5129 }
5130 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5131 if (pi.writePermission != null) {
5132 allowed = false;
5133 }
5134 }
5135 if (allowed) {
5136 return -1;
5137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 }
5139
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005140 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 if (!pi.grantUriPermissions) {
5142 throw new SecurityException("Provider " + pi.packageName
5143 + "/" + pi.name
5144 + " does not allow granting of Uri permissions (uri "
5145 + uri + ")");
5146 }
5147 if (pi.uriPermissionPatterns != null) {
5148 final int N = pi.uriPermissionPatterns.length;
5149 boolean allowed = false;
5150 for (int i=0; i<N; i++) {
5151 if (pi.uriPermissionPatterns[i] != null
5152 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5153 allowed = true;
5154 break;
5155 }
5156 }
5157 if (!allowed) {
5158 throw new SecurityException("Provider " + pi.packageName
5159 + "/" + pi.name
5160 + " does not allow granting of permission to path of Uri "
5161 + uri);
5162 }
5163 }
5164
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005165 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005167 if (callingUid != Process.myUid()) {
5168 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5169 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5170 throw new SecurityException("Uid " + callingUid
5171 + " does not have permission to uri " + uri);
5172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 }
5174 }
5175
Dianne Hackborn39792d22010-08-19 18:01:52 -07005176 return targetUid;
5177 }
5178
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005179 public int checkGrantUriPermission(int callingUid, String targetPkg,
5180 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005181 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005182 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005183 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005184 }
5185 }
5186
Dianne Hackborn39792d22010-08-19 18:01:52 -07005187 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5188 Uri uri, int modeFlags, UriPermissionOwner owner) {
5189 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5190 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5191 if (modeFlags == 0) {
5192 return;
5193 }
5194
5195 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 // to the uri, and the target doesn't. Let's now give this to
5197 // the target.
5198
Joe Onorato8a9b2202010-02-26 18:56:32 -08005199 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005200 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 HashMap<Uri, UriPermission> targetUris
5203 = mGrantedUriPermissions.get(targetUid);
5204 if (targetUris == null) {
5205 targetUris = new HashMap<Uri, UriPermission>();
5206 mGrantedUriPermissions.put(targetUid, targetUris);
5207 }
5208
5209 UriPermission perm = targetUris.get(uri);
5210 if (perm == null) {
5211 perm = new UriPermission(targetUid, uri);
5212 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005215 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005216 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005218 } else {
5219 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5220 perm.readOwners.add(owner);
5221 owner.addReadPermission(perm);
5222 }
5223 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5224 perm.writeOwners.add(owner);
5225 owner.addWritePermission(perm);
5226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 }
5228 }
5229
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005230 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5231 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005232 if (targetPkg == null) {
5233 throw new NullPointerException("targetPkg");
5234 }
5235
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005236 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005237 if (targetUid < 0) {
5238 return;
5239 }
5240
5241 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5242 }
5243
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005244 static class NeededUriGrants extends ArrayList<Uri> {
5245 final String targetPkg;
5246 final int targetUid;
5247 final int flags;
5248
5249 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5250 targetPkg = _targetPkg;
5251 targetUid = _targetUid;
5252 flags = _flags;
5253 }
5254 }
5255
Dianne Hackborn39792d22010-08-19 18:01:52 -07005256 /**
5257 * Like checkGrantUriPermissionLocked, but takes an Intent.
5258 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005259 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5260 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005261 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005262 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5263 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005264 + " from " + intent + "; flags=0x"
5265 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5266
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005267 if (targetPkg == null) {
5268 throw new NullPointerException("targetPkg");
5269 }
5270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005272 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 }
5274 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005275 ClipData clip = intent.getClipData();
5276 if (data == null && clip == null) {
5277 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005278 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005279 if (data != null) {
5280 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5281 mode, needed != null ? needed.targetUid : -1);
5282 if (target > 0) {
5283 if (needed == null) {
5284 needed = new NeededUriGrants(targetPkg, target, mode);
5285 }
5286 needed.add(data);
5287 }
5288 }
5289 if (clip != null) {
5290 for (int i=0; i<clip.getItemCount(); i++) {
5291 Uri uri = clip.getItemAt(i).getUri();
5292 if (uri != null) {
5293 int target = -1;
5294 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5295 mode, needed != null ? needed.targetUid : -1);
5296 if (target > 0) {
5297 if (needed == null) {
5298 needed = new NeededUriGrants(targetPkg, target, mode);
5299 }
5300 needed.add(uri);
5301 }
5302 } else {
5303 Intent clipIntent = clip.getItemAt(i).getIntent();
5304 if (clipIntent != null) {
5305 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5306 callingUid, targetPkg, clipIntent, mode, needed);
5307 if (newNeeded != null) {
5308 needed = newNeeded;
5309 }
5310 }
5311 }
5312 }
5313 }
5314
5315 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005316 }
5317
5318 /**
5319 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5320 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005321 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5322 UriPermissionOwner owner) {
5323 if (needed != null) {
5324 for (int i=0; i<needed.size(); i++) {
5325 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5326 needed.get(i), needed.flags, owner);
5327 }
5328 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005329 }
5330
5331 void grantUriPermissionFromIntentLocked(int callingUid,
5332 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005333 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005334 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005335 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 return;
5337 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005338
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005339 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340 }
5341
5342 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5343 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005344 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 synchronized(this) {
5346 final ProcessRecord r = getRecordForAppLocked(caller);
5347 if (r == null) {
5348 throw new SecurityException("Unable to find app for caller "
5349 + caller
5350 + " when granting permission to uri " + uri);
5351 }
5352 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005353 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 }
5355 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005356 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 }
5358
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005359 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 null);
5361 }
5362 }
5363
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005364 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005365 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5366 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5367 HashMap<Uri, UriPermission> perms
5368 = mGrantedUriPermissions.get(perm.uid);
5369 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005370 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005371 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 perms.remove(perm.uri);
5373 if (perms.size() == 0) {
5374 mGrantedUriPermissions.remove(perm.uid);
5375 }
5376 }
5377 }
5378 }
5379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5381 int modeFlags) {
5382 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5383 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5384 if (modeFlags == 0) {
5385 return;
5386 }
5387
Joe Onorato8a9b2202010-02-26 18:56:32 -08005388 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005389 "Revoking all granted permissions to " + uri);
5390
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005391 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392
5393 final String authority = uri.getAuthority();
5394 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005395 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005396 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 if (cpr != null) {
5398 pi = cpr.info;
5399 } else {
5400 try {
5401 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005402 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 } catch (RemoteException ex) {
5404 }
5405 }
5406 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005407 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 return;
5409 }
5410
5411 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005412 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 // Right now, if you are not the original owner of the permission,
5414 // you are not allowed to revoke it.
5415 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5416 throw new SecurityException("Uid " + callingUid
5417 + " does not have permission to uri " + uri);
5418 //}
5419 }
5420
5421 // Go through all of the permissions and remove any that match.
5422 final List<String> SEGMENTS = uri.getPathSegments();
5423 if (SEGMENTS != null) {
5424 final int NS = SEGMENTS.size();
5425 int N = mGrantedUriPermissions.size();
5426 for (int i=0; i<N; i++) {
5427 HashMap<Uri, UriPermission> perms
5428 = mGrantedUriPermissions.valueAt(i);
5429 Iterator<UriPermission> it = perms.values().iterator();
5430 toploop:
5431 while (it.hasNext()) {
5432 UriPermission perm = it.next();
5433 Uri targetUri = perm.uri;
5434 if (!authority.equals(targetUri.getAuthority())) {
5435 continue;
5436 }
5437 List<String> targetSegments = targetUri.getPathSegments();
5438 if (targetSegments == null) {
5439 continue;
5440 }
5441 if (targetSegments.size() < NS) {
5442 continue;
5443 }
5444 for (int j=0; j<NS; j++) {
5445 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5446 continue toploop;
5447 }
5448 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005449 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005450 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 perm.clearModes(modeFlags);
5452 if (perm.modeFlags == 0) {
5453 it.remove();
5454 }
5455 }
5456 if (perms.size() == 0) {
5457 mGrantedUriPermissions.remove(
5458 mGrantedUriPermissions.keyAt(i));
5459 N--;
5460 i--;
5461 }
5462 }
5463 }
5464 }
5465
5466 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5467 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005468 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 synchronized(this) {
5470 final ProcessRecord r = getRecordForAppLocked(caller);
5471 if (r == null) {
5472 throw new SecurityException("Unable to find app for caller "
5473 + caller
5474 + " when revoking permission to uri " + uri);
5475 }
5476 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005477 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 return;
5479 }
5480
5481 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5482 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5483 if (modeFlags == 0) {
5484 return;
5485 }
5486
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005487 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488
5489 final String authority = uri.getAuthority();
5490 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005491 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 if (cpr != null) {
5493 pi = cpr.info;
5494 } else {
5495 try {
5496 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005497 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 } catch (RemoteException ex) {
5499 }
5500 }
5501 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005502 Slog.w(TAG, "No content provider found for permission revoke: "
5503 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 return;
5505 }
5506
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005507 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 }
5509 }
5510
Dianne Hackborn7e269642010-08-25 19:50:20 -07005511 @Override
5512 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005513 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005514 synchronized(this) {
5515 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5516 return owner.getExternalTokenLocked();
5517 }
5518 }
5519
5520 @Override
5521 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5522 Uri uri, int modeFlags) {
5523 synchronized(this) {
5524 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5525 if (owner == null) {
5526 throw new IllegalArgumentException("Unknown owner: " + token);
5527 }
5528 if (fromUid != Binder.getCallingUid()) {
5529 if (Binder.getCallingUid() != Process.myUid()) {
5530 // Only system code can grant URI permissions on behalf
5531 // of other users.
5532 throw new SecurityException("nice try");
5533 }
5534 }
5535 if (targetPkg == null) {
5536 throw new IllegalArgumentException("null target");
5537 }
5538 if (uri == null) {
5539 throw new IllegalArgumentException("null uri");
5540 }
5541
5542 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5543 }
5544 }
5545
5546 @Override
5547 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5548 synchronized(this) {
5549 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5550 if (owner == null) {
5551 throw new IllegalArgumentException("Unknown owner: " + token);
5552 }
5553
5554 if (uri == null) {
5555 owner.removeUriPermissionsLocked(mode);
5556 } else {
5557 owner.removeUriPermissionLocked(uri, mode);
5558 }
5559 }
5560 }
5561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5563 synchronized (this) {
5564 ProcessRecord app =
5565 who != null ? getRecordForAppLocked(who) : null;
5566 if (app == null) return;
5567
5568 Message msg = Message.obtain();
5569 msg.what = WAIT_FOR_DEBUGGER_MSG;
5570 msg.obj = app;
5571 msg.arg1 = waiting ? 1 : 0;
5572 mHandler.sendMessage(msg);
5573 }
5574 }
5575
5576 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005577 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5578 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005580 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005581 outInfo.threshold = homeAppMem;
5582 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5583 outInfo.hiddenAppThreshold = hiddenAppMem;
5584 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005585 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005586 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5587 ProcessList.VISIBLE_APP_ADJ);
5588 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5589 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 }
5591
5592 // =========================================================
5593 // TASK MANAGEMENT
5594 // =========================================================
5595
5596 public List getTasks(int maxNum, int flags,
5597 IThumbnailReceiver receiver) {
5598 ArrayList list = new ArrayList();
5599
5600 PendingThumbnailsRecord pending = null;
5601 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005602 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603
5604 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005605 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5607 + ", receiver=" + receiver);
5608
5609 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5610 != PackageManager.PERMISSION_GRANTED) {
5611 if (receiver != null) {
5612 // If the caller wants to wait for pending thumbnails,
5613 // it ain't gonna get them.
5614 try {
5615 receiver.finished();
5616 } catch (RemoteException ex) {
5617 }
5618 }
5619 String msg = "Permission Denial: getTasks() from pid="
5620 + Binder.getCallingPid()
5621 + ", uid=" + Binder.getCallingUid()
5622 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005623 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 throw new SecurityException(msg);
5625 }
5626
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005627 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005628 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005629 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005630 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 TaskRecord curTask = null;
5632 int numActivities = 0;
5633 int numRunning = 0;
5634 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005635 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005637 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638
5639 // Initialize state for next task if needed.
5640 if (top == null ||
5641 (top.state == ActivityState.INITIALIZING
5642 && top.task == r.task)) {
5643 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 curTask = r.task;
5645 numActivities = numRunning = 0;
5646 }
5647
5648 // Add 'r' into the current task.
5649 numActivities++;
5650 if (r.app != null && r.app.thread != null) {
5651 numRunning++;
5652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653
Joe Onorato8a9b2202010-02-26 18:56:32 -08005654 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 TAG, r.intent.getComponent().flattenToShortString()
5656 + ": task=" + r.task);
5657
5658 // If the next one is a different task, generate a new
5659 // TaskInfo entry for what we have.
5660 if (next == null || next.task != curTask) {
5661 ActivityManager.RunningTaskInfo ci
5662 = new ActivityManager.RunningTaskInfo();
5663 ci.id = curTask.taskId;
5664 ci.baseActivity = r.intent.getComponent();
5665 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005666 if (top.thumbHolder != null) {
5667 ci.description = top.thumbHolder.lastDescription;
5668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 ci.numActivities = numActivities;
5670 ci.numRunning = numRunning;
5671 //System.out.println(
5672 // "#" + maxNum + ": " + " descr=" + ci.description);
5673 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005674 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 TAG, "State=" + top.state + "Idle=" + top.idle
5676 + " app=" + top.app
5677 + " thr=" + (top.app != null ? top.app.thread : null));
5678 if (top.state == ActivityState.RESUMED
5679 || top.state == ActivityState.PAUSING) {
5680 if (top.idle && top.app != null
5681 && top.app.thread != null) {
5682 topRecord = top;
5683 topThumbnail = top.app.thread;
5684 } else {
5685 top.thumbnailNeeded = true;
5686 }
5687 }
5688 if (pending == null) {
5689 pending = new PendingThumbnailsRecord(receiver);
5690 }
5691 pending.pendingRecords.add(top);
5692 }
5693 list.add(ci);
5694 maxNum--;
5695 top = null;
5696 }
5697 }
5698
5699 if (pending != null) {
5700 mPendingThumbnails.add(pending);
5701 }
5702 }
5703
Joe Onorato8a9b2202010-02-26 18:56:32 -08005704 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705
5706 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005707 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005709 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005711 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005712 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 }
5714 }
5715
5716 if (pending == null && receiver != null) {
5717 // In this case all thumbnails were available and the client
5718 // is being asked to be told when the remaining ones come in...
5719 // which is unusually, since the top-most currently running
5720 // activity should never have a canned thumbnail! Oh well.
5721 try {
5722 receiver.finished();
5723 } catch (RemoteException ex) {
5724 }
5725 }
5726
5727 return list;
5728 }
5729
5730 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005731 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005732 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005733 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005734 // Check if the caller is holding permissions for cross-user requests.
5735 if (checkComponentPermission(
5736 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5737 Binder.getCallingPid(), callingUid, -1, true)
5738 != PackageManager.PERMISSION_GRANTED) {
5739 String msg = "Permission Denial: "
5740 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005741 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005742 + "; this requires "
5743 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5744 Slog.w(TAG, msg);
5745 throw new SecurityException(msg);
5746 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005747 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005748 userId = mCurrentUserId;
5749 }
5750 }
5751 }
5752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 synchronized (this) {
5754 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5755 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005756 final boolean detailed = checkCallingPermission(
5757 android.Manifest.permission.GET_DETAILED_TASKS)
5758 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005760 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 final int N = mRecentTasks.size();
5763 ArrayList<ActivityManager.RecentTaskInfo> res
5764 = new ArrayList<ActivityManager.RecentTaskInfo>(
5765 maxNum < N ? maxNum : N);
5766 for (int i=0; i<N && maxNum > 0; i++) {
5767 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005768 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005769 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005770 // Return the entry if desired by the caller. We always return
5771 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005772 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005773 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5774 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005775
Dianne Hackborn905577f2011-09-07 18:31:28 -07005776 if (i == 0
5777 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 || (tr.intent == null)
5779 || ((tr.intent.getFlags()
5780 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5781 ActivityManager.RecentTaskInfo rti
5782 = new ActivityManager.RecentTaskInfo();
5783 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005784 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 rti.baseIntent = new Intent(
5786 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005787 if (!detailed) {
5788 rti.baseIntent.replaceExtras((Bundle)null);
5789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005791 rti.description = tr.lastDescription;
5792
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005793 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5794 // Check whether this activity is currently available.
5795 try {
5796 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005797 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005798 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005799 continue;
5800 }
5801 } else if (rti.baseIntent != null) {
5802 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005803 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005804 continue;
5805 }
5806 }
5807 } catch (RemoteException e) {
5808 // Will never happen.
5809 }
5810 }
5811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 res.add(rti);
5813 maxNum--;
5814 }
5815 }
5816 return res;
5817 }
5818 }
5819
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005820 private TaskRecord taskForIdLocked(int id) {
5821 final int N = mRecentTasks.size();
5822 for (int i=0; i<N; i++) {
5823 TaskRecord tr = mRecentTasks.get(i);
5824 if (tr.taskId == id) {
5825 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005826 }
5827 }
5828 return null;
5829 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005830
5831 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5832 synchronized (this) {
5833 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5834 "getTaskThumbnails()");
5835 TaskRecord tr = taskForIdLocked(id);
5836 if (tr != null) {
5837 return mMainStack.getTaskThumbnailsLocked(tr);
5838 }
5839 }
5840 return null;
5841 }
5842
5843 public boolean removeSubTask(int taskId, int subTaskIndex) {
5844 synchronized (this) {
5845 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5846 "removeSubTask()");
5847 long ident = Binder.clearCallingIdentity();
5848 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005849 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5850 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005851 } finally {
5852 Binder.restoreCallingIdentity(ident);
5853 }
5854 }
5855 }
5856
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005857 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5858 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005859 Intent baseIntent = new Intent(
5860 tr.intent != null ? tr.intent : tr.affinityIntent);
5861 ComponentName component = baseIntent.getComponent();
5862 if (component == null) {
5863 Slog.w(TAG, "Now component for base intent of task: " + tr);
5864 return;
5865 }
5866
5867 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005868 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005869
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005870 if (killProcesses) {
5871 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005872 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005873 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005874 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5875 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5876 for (int i=0; i<uids.size(); i++) {
5877 ProcessRecord proc = uids.valueAt(i);
5878 if (proc.userId != tr.userId) {
5879 continue;
5880 }
5881 if (!proc.pkgList.contains(pkg)) {
5882 continue;
5883 }
5884 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005885 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005886 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005887
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005888 // Kill the running processes.
5889 for (int i=0; i<procs.size(); i++) {
5890 ProcessRecord pr = procs.get(i);
5891 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5892 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5893 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5894 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005895 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005896 Process.killProcessQuiet(pr.pid);
5897 } else {
5898 pr.waitingToKill = "remove task";
5899 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005900 }
5901 }
5902 }
5903
5904 public boolean removeTask(int taskId, int flags) {
5905 synchronized (this) {
5906 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5907 "removeTask()");
5908 long ident = Binder.clearCallingIdentity();
5909 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005910 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5911 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005912 if (r != null) {
5913 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005914 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005915 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005916 } else {
5917 TaskRecord tr = null;
5918 int i=0;
5919 while (i < mRecentTasks.size()) {
5920 TaskRecord t = mRecentTasks.get(i);
5921 if (t.taskId == taskId) {
5922 tr = t;
5923 break;
5924 }
5925 i++;
5926 }
5927 if (tr != null) {
5928 if (tr.numActivities <= 0) {
5929 // Caller is just removing a recent task that is
5930 // not actively running. That is easy!
5931 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005932 cleanUpRemovedTaskLocked(tr, flags);
5933 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005934 } else {
5935 Slog.w(TAG, "removeTask: task " + taskId
5936 + " does not have activities to remove, "
5937 + " but numActivities=" + tr.numActivities
5938 + ": " + tr);
5939 }
5940 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005941 }
5942 } finally {
5943 Binder.restoreCallingIdentity(ident);
5944 }
5945 }
5946 return false;
5947 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5950 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005951 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 TaskRecord jt = startTask;
5953
5954 // First look backwards
5955 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005956 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 if (r.task != jt) {
5958 jt = r.task;
5959 if (affinity.equals(jt.affinity)) {
5960 return j;
5961 }
5962 }
5963 }
5964
5965 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005966 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 jt = startTask;
5968 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005969 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 if (r.task != jt) {
5971 if (affinity.equals(jt.affinity)) {
5972 return j;
5973 }
5974 jt = r.task;
5975 }
5976 }
5977
5978 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005979 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 return N-1;
5981 }
5982
5983 return -1;
5984 }
5985
5986 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005987 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005989 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005990 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5991 "moveTaskToFront()");
5992
5993 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005994 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5995 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005996 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005997 return;
5998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 final long origId = Binder.clearCallingIdentity();
6000 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006001 TaskRecord tr = taskForIdLocked(task);
6002 if (tr != null) {
6003 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6004 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006006 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6007 // Caller wants the home activity moved with it. To accomplish this,
6008 // we'll just move the home task to the top first.
6009 mMainStack.moveHomeToFrontLocked();
6010 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006011 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006012 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006014 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6015 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006017 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6018 mMainStack.mUserLeaving = true;
6019 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006020 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6021 // Caller wants the home activity moved with it. To accomplish this,
6022 // we'll just move the home task to the top first.
6023 mMainStack.moveHomeToFrontLocked();
6024 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006025 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 return;
6027 }
6028 }
6029 } finally {
6030 Binder.restoreCallingIdentity(origId);
6031 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006032 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 }
6034 }
6035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 public void moveTaskToBack(int task) {
6037 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6038 "moveTaskToBack()");
6039
6040 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006041 if (mMainStack.mResumedActivity != null
6042 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006043 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6044 Binder.getCallingUid(), "Task to back")) {
6045 return;
6046 }
6047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006049 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 Binder.restoreCallingIdentity(origId);
6051 }
6052 }
6053
6054 /**
6055 * Moves an activity, and all of the other activities within the same task, to the bottom
6056 * of the history stack. The activity's order within the task is unchanged.
6057 *
6058 * @param token A reference to the activity we wish to move
6059 * @param nonRoot If false then this only works if the activity is the root
6060 * of a task; if true it will work for any activity in a task.
6061 * @return Returns true if the move completed, false if not.
6062 */
6063 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006064 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 synchronized(this) {
6066 final long origId = Binder.clearCallingIdentity();
6067 int taskId = getTaskForActivityLocked(token, !nonRoot);
6068 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006069 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 }
6071 Binder.restoreCallingIdentity(origId);
6072 }
6073 return false;
6074 }
6075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 public void moveTaskBackwards(int task) {
6077 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6078 "moveTaskBackwards()");
6079
6080 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006081 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6082 Binder.getCallingUid(), "Task backwards")) {
6083 return;
6084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 final long origId = Binder.clearCallingIdentity();
6086 moveTaskBackwardsLocked(task);
6087 Binder.restoreCallingIdentity(origId);
6088 }
6089 }
6090
6091 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006092 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 }
6094
6095 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6096 synchronized(this) {
6097 return getTaskForActivityLocked(token, onlyRoot);
6098 }
6099 }
6100
6101 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006102 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 TaskRecord lastTask = null;
6104 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006105 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006106 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 if (!onlyRoot || lastTask != r.task) {
6108 return r.task.taskId;
6109 }
6110 return -1;
6111 }
6112 lastTask = r.task;
6113 }
6114
6115 return -1;
6116 }
6117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 // =========================================================
6119 // THUMBNAILS
6120 // =========================================================
6121
6122 public void reportThumbnail(IBinder token,
6123 Bitmap thumbnail, CharSequence description) {
6124 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6125 final long origId = Binder.clearCallingIdentity();
6126 sendPendingThumbnail(null, token, thumbnail, description, true);
6127 Binder.restoreCallingIdentity(origId);
6128 }
6129
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006130 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 Bitmap thumbnail, CharSequence description, boolean always) {
6132 TaskRecord task = null;
6133 ArrayList receivers = null;
6134
6135 //System.out.println("Send pending thumbnail: " + r);
6136
6137 synchronized(this) {
6138 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006139 r = mMainStack.isInStackLocked(token);
6140 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 return;
6142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006144 if (thumbnail == null && r.thumbHolder != null) {
6145 thumbnail = r.thumbHolder.lastThumbnail;
6146 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 }
6148 if (thumbnail == null && !always) {
6149 // If there is no thumbnail, and this entry is not actually
6150 // going away, then abort for now and pick up the next
6151 // thumbnail we get.
6152 return;
6153 }
6154 task = r.task;
6155
6156 int N = mPendingThumbnails.size();
6157 int i=0;
6158 while (i<N) {
6159 PendingThumbnailsRecord pr =
6160 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6161 //System.out.println("Looking in " + pr.pendingRecords);
6162 if (pr.pendingRecords.remove(r)) {
6163 if (receivers == null) {
6164 receivers = new ArrayList();
6165 }
6166 receivers.add(pr);
6167 if (pr.pendingRecords.size() == 0) {
6168 pr.finished = true;
6169 mPendingThumbnails.remove(i);
6170 N--;
6171 continue;
6172 }
6173 }
6174 i++;
6175 }
6176 }
6177
6178 if (receivers != null) {
6179 final int N = receivers.size();
6180 for (int i=0; i<N; i++) {
6181 try {
6182 PendingThumbnailsRecord pr =
6183 (PendingThumbnailsRecord)receivers.get(i);
6184 pr.receiver.newThumbnail(
6185 task != null ? task.taskId : -1, thumbnail, description);
6186 if (pr.finished) {
6187 pr.receiver.finished();
6188 }
6189 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006190 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 }
6192 }
6193 }
6194 }
6195
6196 // =========================================================
6197 // CONTENT PROVIDERS
6198 // =========================================================
6199
Jeff Brown10e89712011-07-08 18:52:57 -07006200 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6201 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006203 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006204 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006205 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 } catch (RemoteException ex) {
6207 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006208 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006209 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6210 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006212 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 for (int i=0; i<N; i++) {
6214 ProviderInfo cpi =
6215 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006216 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6217 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006218 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006219 // This is a singleton provider, but a user besides the
6220 // default user is asking to initialize a process it runs
6221 // in... well, no, it doesn't actually run in this process,
6222 // it runs in the process of the default user. Get rid of it.
6223 providers.remove(i);
6224 N--;
6225 continue;
6226 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006227
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006228 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006229 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006231 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006232 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006234 if (DEBUG_MU)
6235 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 app.pubProviders.put(cpi.name, cpr);
6237 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006238 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 }
6240 }
6241 return providers;
6242 }
6243
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006244 /**
6245 * Check if {@link ProcessRecord} has a possible chance at accessing the
6246 * given {@link ProviderInfo}. Final permission checking is always done
6247 * in {@link ContentProvider}.
6248 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006250 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006252 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006254 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006255 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 return null;
6257 }
6258 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006259 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 == PackageManager.PERMISSION_GRANTED) {
6261 return null;
6262 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006263
6264 PathPermission[] pps = cpi.pathPermissions;
6265 if (pps != null) {
6266 int i = pps.length;
6267 while (i > 0) {
6268 i--;
6269 PathPermission pp = pps[i];
6270 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006271 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006272 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006273 return null;
6274 }
6275 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006276 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006277 == PackageManager.PERMISSION_GRANTED) {
6278 return null;
6279 }
6280 }
6281 }
6282
Dianne Hackbornb424b632010-08-18 15:59:05 -07006283 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6284 if (perms != null) {
6285 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6286 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6287 return null;
6288 }
6289 }
6290 }
6291
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006292 String msg;
6293 if (!cpi.exported) {
6294 msg = "Permission Denial: opening provider " + cpi.name
6295 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6296 + ", uid=" + callingUid + ") that is not exported from uid "
6297 + cpi.applicationInfo.uid;
6298 } else {
6299 msg = "Permission Denial: opening provider " + cpi.name
6300 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6301 + ", uid=" + callingUid + ") requires "
6302 + cpi.readPermission + " or " + cpi.writePermission;
6303 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006304 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 return msg;
6306 }
6307
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006308 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6309 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006310 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006311 for (int i=0; i<r.conProviders.size(); i++) {
6312 ContentProviderConnection conn = r.conProviders.get(i);
6313 if (conn.provider == cpr) {
6314 if (DEBUG_PROVIDER) Slog.v(TAG,
6315 "Adding provider requested by "
6316 + r.processName + " from process "
6317 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6318 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6319 if (stable) {
6320 conn.stableCount++;
6321 conn.numStableIncs++;
6322 } else {
6323 conn.unstableCount++;
6324 conn.numUnstableIncs++;
6325 }
6326 return conn;
6327 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006328 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006329 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6330 if (stable) {
6331 conn.stableCount = 1;
6332 conn.numStableIncs = 1;
6333 } else {
6334 conn.unstableCount = 1;
6335 conn.numUnstableIncs = 1;
6336 }
6337 cpr.connections.add(conn);
6338 r.conProviders.add(conn);
6339 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006340 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006341 cpr.addExternalProcessHandleLocked(externalProcessToken);
6342 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006343 }
6344
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006345 boolean decProviderCountLocked(ContentProviderConnection conn,
6346 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6347 if (conn != null) {
6348 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006349 if (DEBUG_PROVIDER) Slog.v(TAG,
6350 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006351 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006352 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006353 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6354 if (stable) {
6355 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006356 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006357 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006358 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006359 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6360 cpr.connections.remove(conn);
6361 conn.client.conProviders.remove(conn);
6362 return true;
6363 }
6364 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006365 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006366 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006367 return false;
6368 }
6369
Amith Yamasani742a6712011-05-04 14:49:28 -07006370 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006371 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006373 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 ProviderInfo cpi = null;
6375
6376 synchronized(this) {
6377 ProcessRecord r = null;
6378 if (caller != null) {
6379 r = getRecordForAppLocked(caller);
6380 if (r == null) {
6381 throw new SecurityException(
6382 "Unable to find app for caller " + caller
6383 + " (pid=" + Binder.getCallingPid()
6384 + ") when getting content provider " + name);
6385 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006386 if (r.userId != userId) {
6387 throw new SecurityException("Calling requested user " + userId
6388 + " but app is user " + r.userId);
6389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 }
6391
6392 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006393 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006394 boolean providerRunning = cpr != null;
6395 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006397 String msg;
6398 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6399 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
6401
6402 if (r != null && cpr.canRunHere(r)) {
6403 // This provider has been published or is in the process
6404 // of being published... but it is also allowed to run
6405 // in the caller's process, so don't make a connection
6406 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006407 ContentProviderHolder holder = cpr.newHolder(null);
6408 // don't give caller the provider object, it needs
6409 // to make its own.
6410 holder.provider = null;
6411 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 }
6413
6414 final long origId = Binder.clearCallingIdentity();
6415
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006416 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006418 conn = incProviderCountLocked(r, cpr, token, stable);
6419 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006420 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006421 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006422 // make sure to count it as being accessed and thus
6423 // back up on the LRU list. This is good because
6424 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006425 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006426 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006427 }
6428
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006429 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006430 if (false) {
6431 if (cpr.name.flattenToShortString().equals(
6432 "com.android.providers.calendar/.CalendarProvider2")) {
6433 Slog.v(TAG, "****************** KILLING "
6434 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006435 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006436 }
6437 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006438 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006439 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6440 // NOTE: there is still a race here where a signal could be
6441 // pending on the process even though we managed to update its
6442 // adj level. Not sure what to do about this, but at least
6443 // the race is now smaller.
6444 if (!success) {
6445 // Uh oh... it looks like the provider's process
6446 // has been killed on us. We need to wait for a new
6447 // process to be started, and make sure its death
6448 // doesn't kill our process.
6449 Slog.i(TAG,
6450 "Existing provider " + cpr.name.flattenToShortString()
6451 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006452 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006453 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006454 if (!lastRef) {
6455 // This wasn't the last ref our process had on
6456 // the provider... we have now been killed, bail.
6457 return null;
6458 }
6459 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006460 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
6463
6464 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006467 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006468 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006470 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006471 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006472 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 } catch (RemoteException ex) {
6474 }
6475 if (cpi == null) {
6476 return null;
6477 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006478 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6479 cpi.name, cpi.flags);
6480 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006481 userId = 0;
6482 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006483 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006484
Dianne Hackbornb424b632010-08-18 15:59:05 -07006485 String msg;
6486 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6487 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 }
6489
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006490 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006491 && !cpi.processName.equals("system")) {
6492 // If this content provider does not run in the system
6493 // process, and the system is not yet ready to run other
6494 // processes, then fail fast instead of hanging.
6495 throw new IllegalArgumentException(
6496 "Attempt to launch content provider before system ready");
6497 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006498
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006499 // Make sure that the user who owns this provider is started. If not,
6500 // we don't want to allow it to run.
6501 if (mStartedUsers.get(userId) == null) {
6502 Slog.w(TAG, "Unable to launch app "
6503 + cpi.applicationInfo.packageName + "/"
6504 + cpi.applicationInfo.uid + " for provider "
6505 + name + ": user " + userId + " is stopped");
6506 return null;
6507 }
6508
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006509 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006510 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 final boolean firstClass = cpr == null;
6512 if (firstClass) {
6513 try {
6514 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006515 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 getApplicationInfo(
6517 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006518 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006520 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 + cpi.name);
6522 return null;
6523 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006524 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006525 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 } catch (RemoteException ex) {
6527 // pm is in same process, this will never happen.
6528 }
6529 }
6530
6531 if (r != null && cpr.canRunHere(r)) {
6532 // If this is a multiprocess provider, then just return its
6533 // info and allow the caller to instantiate it. Only do
6534 // this if the provider is the same user as the caller's
6535 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006536 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 }
6538
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006539 if (DEBUG_PROVIDER) {
6540 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006541 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006542 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 }
6544
6545 // This is single process, and our app is now connecting to it.
6546 // See if we are already in the process of launching this
6547 // provider.
6548 final int N = mLaunchingProviders.size();
6549 int i;
6550 for (i=0; i<N; i++) {
6551 if (mLaunchingProviders.get(i) == cpr) {
6552 break;
6553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 }
6555
6556 // If the provider is not already being launched, then get it
6557 // started.
6558 if (i >= N) {
6559 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006560
6561 try {
6562 // Content provider is now in use, its package can't be stopped.
6563 try {
6564 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006565 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006566 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006567 } catch (IllegalArgumentException e) {
6568 Slog.w(TAG, "Failed trying to unstop package "
6569 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006570 }
6571
6572 ProcessRecord proc = startProcessLocked(cpi.processName,
6573 cpr.appInfo, false, 0, "content provider",
6574 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006575 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006576 if (proc == null) {
6577 Slog.w(TAG, "Unable to launch app "
6578 + cpi.applicationInfo.packageName + "/"
6579 + cpi.applicationInfo.uid + " for provider "
6580 + name + ": process is bad");
6581 return null;
6582 }
6583 cpr.launchingApp = proc;
6584 mLaunchingProviders.add(cpr);
6585 } finally {
6586 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 }
6589
6590 // Make sure the provider is published (the same provider class
6591 // may be published under multiple names).
6592 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006593 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006595
Amith Yamasani742a6712011-05-04 14:49:28 -07006596 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006597 conn = incProviderCountLocked(r, cpr, token, stable);
6598 if (conn != null) {
6599 conn.waiting = true;
6600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 }
6602 }
6603
6604 // Wait for the provider to be published...
6605 synchronized (cpr) {
6606 while (cpr.provider == null) {
6607 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006608 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 + cpi.applicationInfo.packageName + "/"
6610 + cpi.applicationInfo.uid + " for provider "
6611 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006612 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 cpi.applicationInfo.packageName,
6614 cpi.applicationInfo.uid, name);
6615 return null;
6616 }
6617 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006618 if (DEBUG_MU) {
6619 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6620 + cpr.launchingApp);
6621 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006622 if (conn != null) {
6623 conn.waiting = true;
6624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 cpr.wait();
6626 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006627 } finally {
6628 if (conn != null) {
6629 conn.waiting = false;
6630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 }
6632 }
6633 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006634 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 }
6636
6637 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006638 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006639 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 if (caller == null) {
6641 String msg = "null IApplicationThread when getting content provider "
6642 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006643 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 throw new SecurityException(msg);
6645 }
6646
Dianne Hackborn41203752012-08-31 14:05:51 -07006647 return getContentProviderImpl(caller, name, null, stable,
6648 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 }
6650
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006651 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6652 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6653 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006654 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006655 }
6656
Dianne Hackborn41203752012-08-31 14:05:51 -07006657 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6658 IBinder token, int userId) {
6659 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 }
6661
6662 /**
6663 * Drop a content provider from a ProcessRecord's bookkeeping
6664 * @param cpr
6665 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006666 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006667 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006669 ContentProviderConnection conn;
6670 try {
6671 conn = (ContentProviderConnection)connection;
6672 } catch (ClassCastException e) {
6673 String msg ="removeContentProvider: " + connection
6674 + " not a ContentProviderConnection";
6675 Slog.w(TAG, msg);
6676 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006678 if (conn == null) {
6679 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006681 if (decProviderCountLocked(conn, null, null, stable)) {
6682 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 }
6685 }
6686
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006687 public void removeContentProviderExternal(String name, IBinder token) {
6688 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6689 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006690 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006691 }
6692
Dianne Hackborn41203752012-08-31 14:05:51 -07006693 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006695 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 if(cpr == null) {
6697 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006698 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 return;
6700 }
6701
6702 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006703 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006704 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006705 if (localCpr.hasExternalProcessHandles()) {
6706 if (localCpr.removeExternalProcessHandleLocked(token)) {
6707 updateOomAdjLocked();
6708 } else {
6709 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6710 + " with no external reference for token: "
6711 + token + ".");
6712 }
6713 } else {
6714 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6715 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 }
6718 }
6719
6720 public final void publishContentProviders(IApplicationThread caller,
6721 List<ContentProviderHolder> providers) {
6722 if (providers == null) {
6723 return;
6724 }
6725
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006726 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006727 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006729 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006730 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 if (r == null) {
6732 throw new SecurityException(
6733 "Unable to find app for caller " + caller
6734 + " (pid=" + Binder.getCallingPid()
6735 + ") when publishing content providers");
6736 }
6737
6738 final long origId = Binder.clearCallingIdentity();
6739
6740 final int N = providers.size();
6741 for (int i=0; i<N; i++) {
6742 ContentProviderHolder src = providers.get(i);
6743 if (src == null || src.info == null || src.provider == null) {
6744 continue;
6745 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006746 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006747 if (DEBUG_MU)
6748 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006750 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006751 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 String names[] = dst.info.authority.split(";");
6753 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006754 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
6756
6757 int NL = mLaunchingProviders.size();
6758 int j;
6759 for (j=0; j<NL; j++) {
6760 if (mLaunchingProviders.get(j) == dst) {
6761 mLaunchingProviders.remove(j);
6762 j--;
6763 NL--;
6764 }
6765 }
6766 synchronized (dst) {
6767 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006768 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 dst.notifyAll();
6770 }
6771 updateOomAdjLocked(r);
6772 }
6773 }
6774
6775 Binder.restoreCallingIdentity(origId);
6776 }
6777 }
6778
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006779 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6780 ContentProviderConnection conn;
6781 try {
6782 conn = (ContentProviderConnection)connection;
6783 } catch (ClassCastException e) {
6784 String msg ="refContentProvider: " + connection
6785 + " not a ContentProviderConnection";
6786 Slog.w(TAG, msg);
6787 throw new IllegalArgumentException(msg);
6788 }
6789 if (conn == null) {
6790 throw new NullPointerException("connection is null");
6791 }
6792
6793 synchronized (this) {
6794 if (stable > 0) {
6795 conn.numStableIncs += stable;
6796 }
6797 stable = conn.stableCount + stable;
6798 if (stable < 0) {
6799 throw new IllegalStateException("stableCount < 0: " + stable);
6800 }
6801
6802 if (unstable > 0) {
6803 conn.numUnstableIncs += unstable;
6804 }
6805 unstable = conn.unstableCount + unstable;
6806 if (unstable < 0) {
6807 throw new IllegalStateException("unstableCount < 0: " + unstable);
6808 }
6809
6810 if ((stable+unstable) <= 0) {
6811 throw new IllegalStateException("ref counts can't go to zero here: stable="
6812 + stable + " unstable=" + unstable);
6813 }
6814 conn.stableCount = stable;
6815 conn.unstableCount = unstable;
6816 return !conn.dead;
6817 }
6818 }
6819
6820 public void unstableProviderDied(IBinder connection) {
6821 ContentProviderConnection conn;
6822 try {
6823 conn = (ContentProviderConnection)connection;
6824 } catch (ClassCastException e) {
6825 String msg ="refContentProvider: " + connection
6826 + " not a ContentProviderConnection";
6827 Slog.w(TAG, msg);
6828 throw new IllegalArgumentException(msg);
6829 }
6830 if (conn == null) {
6831 throw new NullPointerException("connection is null");
6832 }
6833
6834 // Safely retrieve the content provider associated with the connection.
6835 IContentProvider provider;
6836 synchronized (this) {
6837 provider = conn.provider.provider;
6838 }
6839
6840 if (provider == null) {
6841 // Um, yeah, we're way ahead of you.
6842 return;
6843 }
6844
6845 // Make sure the caller is being honest with us.
6846 if (provider.asBinder().pingBinder()) {
6847 // Er, no, still looks good to us.
6848 synchronized (this) {
6849 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6850 + " says " + conn + " died, but we don't agree");
6851 return;
6852 }
6853 }
6854
6855 // Well look at that! It's dead!
6856 synchronized (this) {
6857 if (conn.provider.provider != provider) {
6858 // But something changed... good enough.
6859 return;
6860 }
6861
6862 ProcessRecord proc = conn.provider.proc;
6863 if (proc == null || proc.thread == null) {
6864 // Seems like the process is already cleaned up.
6865 return;
6866 }
6867
6868 // As far as we're concerned, this is just like receiving a
6869 // death notification... just a bit prematurely.
6870 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6871 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006872 final long ident = Binder.clearCallingIdentity();
6873 try {
6874 appDiedLocked(proc, proc.pid, proc.thread);
6875 } finally {
6876 Binder.restoreCallingIdentity(ident);
6877 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006878 }
6879 }
6880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006882 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006883 synchronized (mSelf) {
6884 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6885 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006886 if (providers != null) {
6887 for (int i=providers.size()-1; i>=0; i--) {
6888 ProviderInfo pi = (ProviderInfo)providers.get(i);
6889 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6890 Slog.w(TAG, "Not installing system proc provider " + pi.name
6891 + ": not system .apk");
6892 providers.remove(i);
6893 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006894 }
6895 }
6896 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006897 if (providers != null) {
6898 mSystemThread.installSystemProviders(providers);
6899 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006900
6901 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006902
6903 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006904 }
6905
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006906 /**
6907 * Allows app to retrieve the MIME type of a URI without having permission
6908 * to access its content provider.
6909 *
6910 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6911 *
6912 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6913 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6914 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006915 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006916 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006917 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
6918 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006919 final String name = uri.getAuthority();
6920 final long ident = Binder.clearCallingIdentity();
6921 ContentProviderHolder holder = null;
6922
6923 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006924 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006925 if (holder != null) {
6926 return holder.provider.getType(uri);
6927 }
6928 } catch (RemoteException e) {
6929 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6930 return null;
6931 } finally {
6932 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006933 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006934 }
6935 Binder.restoreCallingIdentity(ident);
6936 }
6937
6938 return null;
6939 }
6940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 // =========================================================
6942 // GLOBAL MANAGEMENT
6943 // =========================================================
6944
6945 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006946 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 String proc = customProcess != null ? customProcess : info.processName;
6948 BatteryStatsImpl.Uid.Proc ps = null;
6949 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006950 int uid = info.uid;
6951 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006952 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006953 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6954 uid = 0;
6955 while (true) {
6956 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6957 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6958 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6959 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006960 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006961 mNextIsolatedProcessUid++;
6962 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6963 // No process for this uid, use it.
6964 break;
6965 }
6966 stepsLeft--;
6967 if (stepsLeft <= 0) {
6968 return null;
6969 }
6970 }
6971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006972 synchronized (stats) {
6973 ps = stats.getProcessStatsLocked(info.uid, proc);
6974 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006975 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006976 }
6977
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006978 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6979 ProcessRecord app;
6980 if (!isolated) {
6981 app = getProcessRecordLocked(info.processName, info.uid);
6982 } else {
6983 app = null;
6984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006985
6986 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006987 app = newProcessRecordLocked(null, info, null, isolated);
6988 mProcessNames.put(info.processName, app.uid, app);
6989 if (isolated) {
6990 mIsolatedProcesses.put(app.uid, app);
6991 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006992 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 }
6994
Dianne Hackborne7f97212011-02-24 14:40:20 -08006995 // This package really, really can not be stopped.
6996 try {
6997 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006998 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006999 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007000 } catch (IllegalArgumentException e) {
7001 Slog.w(TAG, "Failed trying to unstop package "
7002 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007003 }
7004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7006 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7007 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007008 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 }
7010 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7011 mPersistentStartingProcesses.add(app);
7012 startProcessLocked(app, "added application", app.processName);
7013 }
7014
7015 return app;
7016 }
7017
7018 public void unhandledBack() {
7019 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7020 "unhandledBack()");
7021
7022 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007023 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007024 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 TAG, "Performing unhandledBack(): stack size = " + count);
7026 if (count > 1) {
7027 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007028 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007029 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 Binder.restoreCallingIdentity(origId);
7031 }
7032 }
7033 }
7034
7035 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007036 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007037 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007039 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 ParcelFileDescriptor pfd = null;
7041 if (cph != null) {
7042 // We record the binder invoker's uid in thread-local storage before
7043 // going to the content provider to open the file. Later, in the code
7044 // that handles all permissions checks, we look for this uid and use
7045 // that rather than the Activity Manager's own uid. The effect is that
7046 // we do the check against the caller's permissions even though it looks
7047 // to the content provider like the Activity Manager itself is making
7048 // the request.
7049 sCallerIdentity.set(new Identity(
7050 Binder.getCallingPid(), Binder.getCallingUid()));
7051 try {
7052 pfd = cph.provider.openFile(uri, "r");
7053 } catch (FileNotFoundException e) {
7054 // do nothing; pfd will be returned null
7055 } finally {
7056 // Ensure that whatever happens, we clean up the identity state
7057 sCallerIdentity.remove();
7058 }
7059
7060 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007061 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007063 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 }
7065 return pfd;
7066 }
7067
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007068 // Actually is sleeping or shutting down or whatever else in the future
7069 // is an inactive state.
7070 public boolean isSleeping() {
7071 return mSleeping || mShuttingDown;
7072 }
7073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007075 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7076 != PackageManager.PERMISSION_GRANTED) {
7077 throw new SecurityException("Requires permission "
7078 + android.Manifest.permission.DEVICE_POWER);
7079 }
7080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007082 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007083 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007085 if (!mSleeping) {
7086 mSleeping = true;
7087 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007088
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007089 // Initialize the wake times of all processes.
7090 checkExcessivePowerUsageLocked(false);
7091 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7092 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7093 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 }
7096 }
7097
Dianne Hackborn55280a92009-05-07 15:53:46 -07007098 public boolean shutdown(int timeout) {
7099 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7100 != PackageManager.PERMISSION_GRANTED) {
7101 throw new SecurityException("Requires permission "
7102 + android.Manifest.permission.SHUTDOWN);
7103 }
7104
7105 boolean timedout = false;
7106
7107 synchronized(this) {
7108 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007109 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007111 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007112 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007113 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007114 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007115 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007116 long delay = endTime - System.currentTimeMillis();
7117 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007118 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007119 timedout = true;
7120 break;
7121 }
7122 try {
7123 this.wait();
7124 } catch (InterruptedException e) {
7125 }
7126 }
7127 }
7128 }
7129
7130 mUsageStatsService.shutdown();
7131 mBatteryStatsService.shutdown();
7132
7133 return timedout;
7134 }
7135
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007136 public final void activitySlept(IBinder token) {
7137 if (localLOGV) Slog.v(
7138 TAG, "Activity slept: token=" + token);
7139
7140 ActivityRecord r = null;
7141
7142 final long origId = Binder.clearCallingIdentity();
7143
7144 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007145 r = mMainStack.isInStackLocked(token);
7146 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007147 mMainStack.activitySleptLocked(r);
7148 }
7149 }
7150
7151 Binder.restoreCallingIdentity(origId);
7152 }
7153
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007154 private void comeOutOfSleepIfNeededLocked() {
7155 if (!mWentToSleep && !mLockScreenShown) {
7156 if (mSleeping) {
7157 mSleeping = false;
7158 mMainStack.awakeFromSleepingLocked();
7159 mMainStack.resumeTopActivityLocked(null);
7160 }
7161 }
7162 }
7163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007165 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7166 != PackageManager.PERMISSION_GRANTED) {
7167 throw new SecurityException("Requires permission "
7168 + android.Manifest.permission.DEVICE_POWER);
7169 }
7170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007172 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007173 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007174 comeOutOfSleepIfNeededLocked();
7175 }
7176 }
7177
Jeff Brownc042ee22012-05-08 13:03:42 -07007178 private void updateEventDispatchingLocked() {
7179 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7180 }
7181
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007182 public void setLockScreenShown(boolean shown) {
7183 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7184 != PackageManager.PERMISSION_GRANTED) {
7185 throw new SecurityException("Requires permission "
7186 + android.Manifest.permission.DEVICE_POWER);
7187 }
7188
7189 synchronized(this) {
7190 mLockScreenShown = shown;
7191 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007192 }
7193 }
7194
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007195 public void stopAppSwitches() {
7196 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7197 != PackageManager.PERMISSION_GRANTED) {
7198 throw new SecurityException("Requires permission "
7199 + android.Manifest.permission.STOP_APP_SWITCHES);
7200 }
7201
7202 synchronized(this) {
7203 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7204 + APP_SWITCH_DELAY_TIME;
7205 mDidAppSwitch = false;
7206 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7207 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7208 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7209 }
7210 }
7211
7212 public void resumeAppSwitches() {
7213 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7214 != PackageManager.PERMISSION_GRANTED) {
7215 throw new SecurityException("Requires permission "
7216 + android.Manifest.permission.STOP_APP_SWITCHES);
7217 }
7218
7219 synchronized(this) {
7220 // Note that we don't execute any pending app switches... we will
7221 // let those wait until either the timeout, or the next start
7222 // activity request.
7223 mAppSwitchesAllowedTime = 0;
7224 }
7225 }
7226
7227 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7228 String name) {
7229 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7230 return true;
7231 }
7232
7233 final int perm = checkComponentPermission(
7234 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007235 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007236 if (perm == PackageManager.PERMISSION_GRANTED) {
7237 return true;
7238 }
7239
Joe Onorato8a9b2202010-02-26 18:56:32 -08007240 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007241 return false;
7242 }
7243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 public void setDebugApp(String packageName, boolean waitForDebugger,
7245 boolean persistent) {
7246 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7247 "setDebugApp()");
7248
7249 // Note that this is not really thread safe if there are multiple
7250 // callers into it at the same time, but that's not a situation we
7251 // care about.
7252 if (persistent) {
7253 final ContentResolver resolver = mContext.getContentResolver();
7254 Settings.System.putString(
7255 resolver, Settings.System.DEBUG_APP,
7256 packageName);
7257 Settings.System.putInt(
7258 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7259 waitForDebugger ? 1 : 0);
7260 }
7261
7262 synchronized (this) {
7263 if (!persistent) {
7264 mOrigDebugApp = mDebugApp;
7265 mOrigWaitForDebugger = mWaitForDebugger;
7266 }
7267 mDebugApp = packageName;
7268 mWaitForDebugger = waitForDebugger;
7269 mDebugTransient = !persistent;
7270 if (packageName != null) {
7271 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007272 forceStopPackageLocked(packageName, -1, false, false, true, true,
7273 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 Binder.restoreCallingIdentity(origId);
7275 }
7276 }
7277 }
7278
Siva Velusamy92a8b222012-03-09 16:24:04 -08007279 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7280 synchronized (this) {
7281 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7282 if (!isDebuggable) {
7283 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7284 throw new SecurityException("Process not debuggable: " + app.packageName);
7285 }
7286 }
7287
7288 mOpenGlTraceApp = processName;
7289 }
7290 }
7291
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007292 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7293 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7294 synchronized (this) {
7295 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7296 if (!isDebuggable) {
7297 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7298 throw new SecurityException("Process not debuggable: " + app.packageName);
7299 }
7300 }
7301 mProfileApp = processName;
7302 mProfileFile = profileFile;
7303 if (mProfileFd != null) {
7304 try {
7305 mProfileFd.close();
7306 } catch (IOException e) {
7307 }
7308 mProfileFd = null;
7309 }
7310 mProfileFd = profileFd;
7311 mProfileType = 0;
7312 mAutoStopProfiler = autoStopProfiler;
7313 }
7314 }
7315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 public void setAlwaysFinish(boolean enabled) {
7317 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7318 "setAlwaysFinish()");
7319
7320 Settings.System.putInt(
7321 mContext.getContentResolver(),
7322 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7323
7324 synchronized (this) {
7325 mAlwaysFinishActivities = enabled;
7326 }
7327 }
7328
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007329 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007331 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007333 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 }
7335 }
7336
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007337 public boolean isUserAMonkey() {
7338 // For now the fact that there is a controller implies
7339 // we have a monkey.
7340 synchronized (this) {
7341 return mController != null;
7342 }
7343 }
7344
Jeff Sharkeya4620792011-05-20 15:29:23 -07007345 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007346 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7347 "registerProcessObserver()");
7348 synchronized (this) {
7349 mProcessObservers.register(observer);
7350 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007351 }
7352
7353 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007354 synchronized (this) {
7355 mProcessObservers.unregister(observer);
7356 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007357 }
7358
Daniel Sandler69a48172010-06-23 16:29:36 -04007359 public void setImmersive(IBinder token, boolean immersive) {
7360 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007361 ActivityRecord r = mMainStack.isInStackLocked(token);
7362 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007363 throw new IllegalArgumentException();
7364 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007365 r.immersive = immersive;
7366 }
7367 }
7368
7369 public boolean isImmersive(IBinder token) {
7370 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007371 ActivityRecord r = mMainStack.isInStackLocked(token);
7372 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007373 throw new IllegalArgumentException();
7374 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007375 return r.immersive;
7376 }
7377 }
7378
7379 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007380 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007381 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007382 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007383 return (r != null) ? r.immersive : false;
7384 }
7385 }
7386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 public final void enterSafeMode() {
7388 synchronized(this) {
7389 // It only makes sense to do this before the system is ready
7390 // and started launching other packages.
7391 if (!mSystemReady) {
7392 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007393 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007394 } catch (RemoteException e) {
7395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 }
7397 }
7398 }
7399
Jeff Brownb09abc12011-01-13 21:08:27 -08007400 public final void showSafeModeOverlay() {
7401 View v = LayoutInflater.from(mContext).inflate(
7402 com.android.internal.R.layout.safe_mode, null);
7403 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7404 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7405 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7406 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007407 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007408 lp.format = v.getBackground().getOpacity();
7409 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7410 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7411 ((WindowManager)mContext.getSystemService(
7412 Context.WINDOW_SERVICE)).addView(v, lp);
7413 }
7414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 public void noteWakeupAlarm(IIntentSender sender) {
7416 if (!(sender instanceof PendingIntentRecord)) {
7417 return;
7418 }
7419 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7420 synchronized (stats) {
7421 if (mBatteryStatsService.isOnBattery()) {
7422 mBatteryStatsService.enforceCallingPermission();
7423 PendingIntentRecord rec = (PendingIntentRecord)sender;
7424 int MY_UID = Binder.getCallingUid();
7425 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7426 BatteryStatsImpl.Uid.Pkg pkg =
7427 stats.getPackageStatsLocked(uid, rec.key.packageName);
7428 pkg.incWakeupsLocked();
7429 }
7430 }
7431 }
7432
Dianne Hackborn64825172011-03-02 21:32:58 -08007433 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007435 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007436 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007437 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007438 // XXX Note: don't acquire main activity lock here, because the window
7439 // manager calls in with its locks held.
7440
7441 boolean killed = false;
7442 synchronized (mPidsSelfLocked) {
7443 int[] types = new int[pids.length];
7444 int worstType = 0;
7445 for (int i=0; i<pids.length; i++) {
7446 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7447 if (proc != null) {
7448 int type = proc.setAdj;
7449 types[i] = type;
7450 if (type > worstType) {
7451 worstType = type;
7452 }
7453 }
7454 }
7455
Dianne Hackborn64825172011-03-02 21:32:58 -08007456 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007458 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7459 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007460 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007462
7463 // If this is not a secure call, don't let it kill processes that
7464 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007465 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7466 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007467 }
7468
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007469 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 for (int i=0; i<pids.length; i++) {
7471 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7472 if (proc == null) {
7473 continue;
7474 }
7475 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007476 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007477 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007478 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7479 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007481 proc.killedBackground = true;
7482 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 }
7484 }
7485 }
7486 return killed;
7487 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007488
7489 @Override
7490 public boolean killProcessesBelowForeground(String reason) {
7491 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7492 throw new SecurityException("killProcessesBelowForeground() only available to system");
7493 }
7494
7495 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7496 }
7497
7498 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7499 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7500 throw new SecurityException("killProcessesBelowAdj() only available to system");
7501 }
7502
7503 boolean killed = false;
7504 synchronized (mPidsSelfLocked) {
7505 final int size = mPidsSelfLocked.size();
7506 for (int i = 0; i < size; i++) {
7507 final int pid = mPidsSelfLocked.keyAt(i);
7508 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7509 if (proc == null) continue;
7510
7511 final int adj = proc.setAdj;
7512 if (adj > belowAdj && !proc.killedBackground) {
7513 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7514 EventLog.writeEvent(
7515 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7516 killed = true;
7517 proc.killedBackground = true;
7518 Process.killProcessQuiet(pid);
7519 }
7520 }
7521 }
7522 return killed;
7523 }
7524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 public final void startRunning(String pkg, String cls, String action,
7526 String data) {
7527 synchronized(this) {
7528 if (mStartRunning) {
7529 return;
7530 }
7531 mStartRunning = true;
7532 mTopComponent = pkg != null && cls != null
7533 ? new ComponentName(pkg, cls) : null;
7534 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7535 mTopData = data;
7536 if (!mSystemReady) {
7537 return;
7538 }
7539 }
7540
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007541 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 }
7543
7544 private void retrieveSettings() {
7545 final ContentResolver resolver = mContext.getContentResolver();
7546 String debugApp = Settings.System.getString(
7547 resolver, Settings.System.DEBUG_APP);
7548 boolean waitForDebugger = Settings.System.getInt(
7549 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7550 boolean alwaysFinishActivities = Settings.System.getInt(
7551 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7552
7553 Configuration configuration = new Configuration();
7554 Settings.System.getConfiguration(resolver, configuration);
7555
7556 synchronized (this) {
7557 mDebugApp = mOrigDebugApp = debugApp;
7558 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7559 mAlwaysFinishActivities = alwaysFinishActivities;
7560 // This happens before any activities are started, so we can
7561 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007562 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007563 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 }
7565 }
7566
7567 public boolean testIsSystemReady() {
7568 // no need to synchronize(this) just to read & return the value
7569 return mSystemReady;
7570 }
7571
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007572 private static File getCalledPreBootReceiversFile() {
7573 File dataDir = Environment.getDataDirectory();
7574 File systemDir = new File(dataDir, "system");
7575 File fname = new File(systemDir, "called_pre_boots.dat");
7576 return fname;
7577 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007578
7579 static final int LAST_DONE_VERSION = 10000;
7580
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007581 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7582 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7583 File file = getCalledPreBootReceiversFile();
7584 FileInputStream fis = null;
7585 try {
7586 fis = new FileInputStream(file);
7587 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007588 int fvers = dis.readInt();
7589 if (fvers == LAST_DONE_VERSION) {
7590 String vers = dis.readUTF();
7591 String codename = dis.readUTF();
7592 String build = dis.readUTF();
7593 if (android.os.Build.VERSION.RELEASE.equals(vers)
7594 && android.os.Build.VERSION.CODENAME.equals(codename)
7595 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7596 int num = dis.readInt();
7597 while (num > 0) {
7598 num--;
7599 String pkg = dis.readUTF();
7600 String cls = dis.readUTF();
7601 lastDoneReceivers.add(new ComponentName(pkg, cls));
7602 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007603 }
7604 }
7605 } catch (FileNotFoundException e) {
7606 } catch (IOException e) {
7607 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7608 } finally {
7609 if (fis != null) {
7610 try {
7611 fis.close();
7612 } catch (IOException e) {
7613 }
7614 }
7615 }
7616 return lastDoneReceivers;
7617 }
7618
7619 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7620 File file = getCalledPreBootReceiversFile();
7621 FileOutputStream fos = null;
7622 DataOutputStream dos = null;
7623 try {
7624 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7625 fos = new FileOutputStream(file);
7626 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007627 dos.writeInt(LAST_DONE_VERSION);
7628 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007629 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007630 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007631 dos.writeInt(list.size());
7632 for (int i=0; i<list.size(); i++) {
7633 dos.writeUTF(list.get(i).getPackageName());
7634 dos.writeUTF(list.get(i).getClassName());
7635 }
7636 } catch (IOException e) {
7637 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7638 file.delete();
7639 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007640 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007641 if (dos != null) {
7642 try {
7643 dos.close();
7644 } catch (IOException e) {
7645 // TODO Auto-generated catch block
7646 e.printStackTrace();
7647 }
7648 }
7649 }
7650 }
7651
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007652 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 synchronized(this) {
7654 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007655 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 return;
7657 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007658
7659 // Check to see if there are any update receivers to run.
7660 if (!mDidUpdate) {
7661 if (mWaitingUpdate) {
7662 return;
7663 }
7664 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7665 List<ResolveInfo> ris = null;
7666 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007667 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007668 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007669 } catch (RemoteException e) {
7670 }
7671 if (ris != null) {
7672 for (int i=ris.size()-1; i>=0; i--) {
7673 if ((ris.get(i).activityInfo.applicationInfo.flags
7674 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7675 ris.remove(i);
7676 }
7677 }
7678 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007679
7680 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7681
7682 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007683 for (int i=0; i<ris.size(); i++) {
7684 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007685 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7686 if (lastDoneReceivers.contains(comp)) {
7687 ris.remove(i);
7688 i--;
7689 }
7690 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007691
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007692 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007693 for (int i=0; i<ris.size(); i++) {
7694 ActivityInfo ai = ris.get(i).activityInfo;
7695 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7696 doneReceivers.add(comp);
7697 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007698 for (int j=0; j<users.length; j++) {
7699 IIntentReceiver finisher = null;
7700 if (i == ris.size()-1 && j == users.length-1) {
7701 finisher = new IIntentReceiver.Stub() {
7702 public void performReceive(Intent intent, int resultCode,
7703 String data, Bundle extras, boolean ordered,
7704 boolean sticky, int sendingUser) {
7705 // The raw IIntentReceiver interface is called
7706 // with the AM lock held, so redispatch to
7707 // execute our code without the lock.
7708 mHandler.post(new Runnable() {
7709 public void run() {
7710 synchronized (ActivityManagerService.this) {
7711 mDidUpdate = true;
7712 }
7713 writeLastDonePreBootReceivers(doneReceivers);
7714 showBootMessage(mContext.getText(
7715 R.string.android_upgrading_complete),
7716 false);
7717 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007718 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007719 });
7720 }
7721 };
7722 }
7723 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7724 + " for user " + users[j]);
7725 broadcastIntentLocked(null, null, intent, null, finisher,
7726 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7727 users[j]);
7728 if (finisher != null) {
7729 mWaitingUpdate = true;
7730 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007731 }
7732 }
7733 }
7734 if (mWaitingUpdate) {
7735 return;
7736 }
7737 mDidUpdate = true;
7738 }
7739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 mSystemReady = true;
7741 if (!mStartRunning) {
7742 return;
7743 }
7744 }
7745
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007746 ArrayList<ProcessRecord> procsToKill = null;
7747 synchronized(mPidsSelfLocked) {
7748 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7749 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7750 if (!isAllowedWhileBooting(proc.info)){
7751 if (procsToKill == null) {
7752 procsToKill = new ArrayList<ProcessRecord>();
7753 }
7754 procsToKill.add(proc);
7755 }
7756 }
7757 }
7758
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007759 synchronized(this) {
7760 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007761 for (int i=procsToKill.size()-1; i>=0; i--) {
7762 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007763 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007764 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007765 }
7766 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007767
7768 // Now that we have cleaned up any update processes, we
7769 // are ready to start launching real processes and know that
7770 // we won't trample on them any more.
7771 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007772 }
7773
Joe Onorato8a9b2202010-02-26 18:56:32 -08007774 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007775 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 SystemClock.uptimeMillis());
7777
7778 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007779 // Make sure we have no pre-ready processes sitting around.
7780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7782 ResolveInfo ri = mContext.getPackageManager()
7783 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007784 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 CharSequence errorMsg = null;
7786 if (ri != null) {
7787 ActivityInfo ai = ri.activityInfo;
7788 ApplicationInfo app = ai.applicationInfo;
7789 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7790 mTopAction = Intent.ACTION_FACTORY_TEST;
7791 mTopData = null;
7792 mTopComponent = new ComponentName(app.packageName,
7793 ai.name);
7794 } else {
7795 errorMsg = mContext.getResources().getText(
7796 com.android.internal.R.string.factorytest_not_system);
7797 }
7798 } else {
7799 errorMsg = mContext.getResources().getText(
7800 com.android.internal.R.string.factorytest_no_action);
7801 }
7802 if (errorMsg != null) {
7803 mTopAction = null;
7804 mTopData = null;
7805 mTopComponent = null;
7806 Message msg = Message.obtain();
7807 msg.what = SHOW_FACTORY_ERROR_MSG;
7808 msg.getData().putCharSequence("msg", errorMsg);
7809 mHandler.sendMessage(msg);
7810 }
7811 }
7812 }
7813
7814 retrieveSettings();
7815
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007816 if (goingCallback != null) goingCallback.run();
7817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 synchronized (this) {
7819 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7820 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007821 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007822 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 if (apps != null) {
7824 int N = apps.size();
7825 int i;
7826 for (i=0; i<N; i++) {
7827 ApplicationInfo info
7828 = (ApplicationInfo)apps.get(i);
7829 if (info != null &&
7830 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007831 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 }
7833 }
7834 }
7835 } catch (RemoteException ex) {
7836 // pm is in same process, this will never happen.
7837 }
7838 }
7839
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007840 // Start up initial activity.
7841 mBooting = true;
7842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007844 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007845 Message msg = Message.obtain();
7846 msg.what = SHOW_UID_ERROR_MSG;
7847 mHandler.sendMessage(msg);
7848 }
7849 } catch (RemoteException e) {
7850 }
7851
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007852 long ident = Binder.clearCallingIdentity();
7853 try {
7854 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7855 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7856 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7857 broadcastIntentLocked(null, null, intent,
7858 null, null, 0, null, null, null,
7859 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
7860 } finally {
7861 Binder.restoreCallingIdentity(ident);
7862 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007863 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007864 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007865 }
7866 }
7867
Dan Egnorb7f03672009-12-09 16:22:32 -08007868 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007869 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007870 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007871 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007872 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 startAppProblemLocked(app);
7874 app.stopFreezingAllLocked();
7875 return handleAppCrashLocked(app);
7876 }
7877
Dan Egnorb7f03672009-12-09 16:22:32 -08007878 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007879 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007880 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007881 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007882 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7883 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 startAppProblemLocked(app);
7885 app.stopFreezingAllLocked();
7886 }
7887
7888 /**
7889 * Generate a process error record, suitable for attachment to a ProcessRecord.
7890 *
7891 * @param app The ProcessRecord in which the error occurred.
7892 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7893 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007894 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 * @param shortMsg Short message describing the crash.
7896 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007897 * @param stackTrace Full crash stack trace, may be null.
7898 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 * @return Returns a fully-formed AppErrorStateInfo record.
7900 */
7901 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007902 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 report.condition = condition;
7906 report.processName = app.processName;
7907 report.pid = app.pid;
7908 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007909 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 report.shortMsg = shortMsg;
7911 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007912 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913
7914 return report;
7915 }
7916
Dan Egnor42471dd2010-01-07 17:25:22 -08007917 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 synchronized (this) {
7919 app.crashing = false;
7920 app.crashingReport = null;
7921 app.notResponding = false;
7922 app.notRespondingReport = null;
7923 if (app.anrDialog == fromDialog) {
7924 app.anrDialog = null;
7925 }
7926 if (app.waitDialog == fromDialog) {
7927 app.waitDialog = null;
7928 }
7929 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007930 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007931 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007932 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7933 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007934 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 }
7937 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007938
Dan Egnorb7f03672009-12-09 16:22:32 -08007939 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007940 if (mHeadless) {
7941 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7942 return false;
7943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 long now = SystemClock.uptimeMillis();
7945
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007946 Long crashTime;
7947 if (!app.isolated) {
7948 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7949 } else {
7950 crashTime = null;
7951 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007952 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007954 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007956 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007957 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007958 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7959 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007961 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007963 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7964 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007965 }
7966 }
7967 if (!app.persistent) {
7968 // We don't want to start this process again until the user
7969 // explicitly does so... but for persistent process, we really
7970 // need to keep it running. If a persistent process is actually
7971 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007972 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007974 if (!app.isolated) {
7975 // XXX We don't have a way to mark isolated processes
7976 // as bad, since they don't have a peristent identity.
7977 mBadProcesses.put(app.info.processName, app.uid, now);
7978 mProcessCrashTimes.remove(app.info.processName, app.uid);
7979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007982 // Don't let services in this process be restarted and potentially
7983 // annoy the user repeatedly. Unless it is persistent, since those
7984 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007985 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007986 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 return false;
7988 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007989 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007990 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007991 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007992 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007993 // If the top running activity is from this crashing
7994 // process, then terminate it to avoid getting in a loop.
7995 Slog.w(TAG, " Force finishing activity "
7996 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007997 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007998 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007999 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008000 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008001 // stopped, to avoid a situation where one will get
8002 // re-start our crashing activity once it gets resumed again.
8003 index--;
8004 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008005 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008006 if (r.state == ActivityState.RESUMED
8007 || r.state == ActivityState.PAUSING
8008 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008009 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008010 Slog.w(TAG, " Force finishing activity "
8011 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008012 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008013 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008014 }
8015 }
8016 }
8017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 }
8019
8020 // Bump up the crash count of any services currently running in the proc.
8021 if (app.services.size() != 0) {
8022 // Any services running in the application need to be placed
8023 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008024 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008025 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008026 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 sr.crashCount++;
8028 }
8029 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008030
8031 // If the crashing process is what we consider to be the "home process" and it has been
8032 // replaced by a third-party app, clear the package preferred activities from packages
8033 // with a home activity running in the process to prevent a repeatedly crashing app
8034 // from blocking the user to manually clear the list.
8035 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8036 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8037 Iterator it = mHomeProcess.activities.iterator();
8038 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008039 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008040 if (r.isHomeActivity) {
8041 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8042 try {
8043 ActivityThread.getPackageManager()
8044 .clearPackagePreferredActivities(r.packageName);
8045 } catch (RemoteException c) {
8046 // pm is in same process, this will never happen.
8047 }
8048 }
8049 }
8050 }
8051
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008052 if (!app.isolated) {
8053 // XXX Can't keep track of crash times for isolated processes,
8054 // because they don't have a perisistent identity.
8055 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8056 }
8057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008058 return true;
8059 }
8060
8061 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008062 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8063 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 skipCurrentReceiverLocked(app);
8065 }
8066
8067 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008068 for (BroadcastQueue queue : mBroadcastQueues) {
8069 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 }
8071 }
8072
Dan Egnor60d87622009-12-16 16:32:58 -08008073 /**
8074 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8075 * The application process will exit immediately after this call returns.
8076 * @param app object of the crashing app, null for the system server
8077 * @param crashInfo describing the exception
8078 */
8079 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008080 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008081 final String processName = app == null ? "system_server"
8082 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008083
8084 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008085 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008086 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008087 crashInfo.exceptionClassName,
8088 crashInfo.exceptionMessage,
8089 crashInfo.throwFileName,
8090 crashInfo.throwLineNumber);
8091
Jeff Sharkeya353d262011-10-28 11:12:06 -07008092 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008093
8094 crashApplication(r, crashInfo);
8095 }
8096
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008097 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008098 IBinder app,
8099 int violationMask,
8100 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008101 ProcessRecord r = findAppProcess(app, "StrictMode");
8102 if (r == null) {
8103 return;
8104 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008105
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008106 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008107 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008108 boolean logIt = true;
8109 synchronized (mAlreadyLoggedViolatedStacks) {
8110 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8111 logIt = false;
8112 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008113 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008114 // the relative pain numbers, without logging all
8115 // the stack traces repeatedly. We'd want to do
8116 // likewise in the client code, which also does
8117 // dup suppression, before the Binder call.
8118 } else {
8119 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8120 mAlreadyLoggedViolatedStacks.clear();
8121 }
8122 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8123 }
8124 }
8125 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008126 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008127 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008128 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008129
8130 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8131 AppErrorResult result = new AppErrorResult();
8132 synchronized (this) {
8133 final long origId = Binder.clearCallingIdentity();
8134
8135 Message msg = Message.obtain();
8136 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8137 HashMap<String, Object> data = new HashMap<String, Object>();
8138 data.put("result", result);
8139 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008140 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008141 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008142 msg.obj = data;
8143 mHandler.sendMessage(msg);
8144
8145 Binder.restoreCallingIdentity(origId);
8146 }
8147 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008148 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008149 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008150 }
8151
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008152 // Depending on the policy in effect, there could be a bunch of
8153 // these in quick succession so we try to batch these together to
8154 // minimize disk writes, number of dropbox entries, and maximize
8155 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008156 private void logStrictModeViolationToDropBox(
8157 ProcessRecord process,
8158 StrictMode.ViolationInfo info) {
8159 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008160 return;
8161 }
8162 final boolean isSystemApp = process == null ||
8163 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8164 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008165 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008166 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8167 final DropBoxManager dbox = (DropBoxManager)
8168 mContext.getSystemService(Context.DROPBOX_SERVICE);
8169
8170 // Exit early if the dropbox isn't configured to accept this report type.
8171 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8172
8173 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008174 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008175 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8176 synchronized (sb) {
8177 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008178 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008179 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8180 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008181 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8182 if (info.violationNumThisLoop != 0) {
8183 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8184 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008185 if (info.numAnimationsRunning != 0) {
8186 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8187 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008188 if (info.broadcastIntentAction != null) {
8189 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8190 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008191 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008192 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008193 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008194 if (info.numInstances != -1) {
8195 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8196 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008197 if (info.tags != null) {
8198 for (String tag : info.tags) {
8199 sb.append("Span-Tag: ").append(tag).append("\n");
8200 }
8201 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008202 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008203 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8204 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008205 }
8206 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008207
8208 // Only buffer up to ~64k. Various logging bits truncate
8209 // things at 128k.
8210 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008211 }
8212
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008213 // Flush immediately if the buffer's grown too large, or this
8214 // is a non-system app. Non-system apps are isolated with a
8215 // different tag & policy and not batched.
8216 //
8217 // Batching is useful during internal testing with
8218 // StrictMode settings turned up high. Without batching,
8219 // thousands of separate files could be created on boot.
8220 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008221 new Thread("Error dump: " + dropboxTag) {
8222 @Override
8223 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008224 String report;
8225 synchronized (sb) {
8226 report = sb.toString();
8227 sb.delete(0, sb.length());
8228 sb.trimToSize();
8229 }
8230 if (report.length() != 0) {
8231 dbox.addText(dropboxTag, report);
8232 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008233 }
8234 }.start();
8235 return;
8236 }
8237
8238 // System app batching:
8239 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008240 // An existing dropbox-writing thread is outstanding, so
8241 // we don't need to start it up. The existing thread will
8242 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008243 return;
8244 }
8245
8246 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8247 // (After this point, we shouldn't access AMS internal data structures.)
8248 new Thread("Error dump: " + dropboxTag) {
8249 @Override
8250 public void run() {
8251 // 5 second sleep to let stacks arrive and be batched together
8252 try {
8253 Thread.sleep(5000); // 5 seconds
8254 } catch (InterruptedException e) {}
8255
8256 String errorReport;
8257 synchronized (mStrictModeBuffer) {
8258 errorReport = mStrictModeBuffer.toString();
8259 if (errorReport.length() == 0) {
8260 return;
8261 }
8262 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8263 mStrictModeBuffer.trimToSize();
8264 }
8265 dbox.addText(dropboxTag, errorReport);
8266 }
8267 }.start();
8268 }
8269
Dan Egnor60d87622009-12-16 16:32:58 -08008270 /**
8271 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8272 * @param app object of the crashing app, null for the system server
8273 * @param tag reported by the caller
8274 * @param crashInfo describing the context of the error
8275 * @return true if the process should exit immediately (WTF is fatal)
8276 */
8277 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008278 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008279 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008280 final String processName = app == null ? "system_server"
8281 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008282
8283 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008284 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008285 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008286 tag, crashInfo.exceptionMessage);
8287
Jeff Sharkeya353d262011-10-28 11:12:06 -07008288 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008289
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008290 if (r != null && r.pid != Process.myPid() &&
8291 Settings.Secure.getInt(mContext.getContentResolver(),
8292 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008293 crashApplication(r, crashInfo);
8294 return true;
8295 } else {
8296 return false;
8297 }
8298 }
8299
8300 /**
8301 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8302 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8303 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008304 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008305 if (app == null) {
8306 return null;
8307 }
8308
8309 synchronized (this) {
8310 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8311 final int NA = apps.size();
8312 for (int ia=0; ia<NA; ia++) {
8313 ProcessRecord p = apps.valueAt(ia);
8314 if (p.thread != null && p.thread.asBinder() == app) {
8315 return p;
8316 }
8317 }
8318 }
8319
Dianne Hackborncb44d962011-03-10 17:02:27 -08008320 Slog.w(TAG, "Can't find mystery application for " + reason
8321 + " from pid=" + Binder.getCallingPid()
8322 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008323 return null;
8324 }
8325 }
8326
8327 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008328 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8329 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008330 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008331 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8332 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008333 // Watchdog thread ends up invoking this function (with
8334 // a null ProcessRecord) to add the stack file to dropbox.
8335 // Do not acquire a lock on this (am) in such cases, as it
8336 // could cause a potential deadlock, if and when watchdog
8337 // is invoked due to unavailability of lock on am and it
8338 // would prevent watchdog from killing system_server.
8339 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008340 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008341 return;
8342 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008343 // Note: ProcessRecord 'process' is guarded by the service
8344 // instance. (notably process.pkgList, which could otherwise change
8345 // concurrently during execution of this method)
8346 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008347 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008348 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008349 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008350 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8351 for (String pkg : process.pkgList) {
8352 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008353 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008354 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008355 if (pi != null) {
8356 sb.append(" v").append(pi.versionCode);
8357 if (pi.versionName != null) {
8358 sb.append(" (").append(pi.versionName).append(")");
8359 }
8360 }
8361 } catch (RemoteException e) {
8362 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008363 }
Dan Egnora455d192010-03-12 08:52:28 -08008364 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008365 }
Dan Egnora455d192010-03-12 08:52:28 -08008366 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008367 }
8368
8369 private static String processClass(ProcessRecord process) {
8370 if (process == null || process.pid == MY_PID) {
8371 return "system_server";
8372 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8373 return "system_app";
8374 } else {
8375 return "data_app";
8376 }
8377 }
8378
8379 /**
8380 * Write a description of an error (crash, WTF, ANR) to the drop box.
8381 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8382 * @param process which caused the error, null means the system server
8383 * @param activity which triggered the error, null if unknown
8384 * @param parent activity related to the error, null if unknown
8385 * @param subject line related to the error, null if absent
8386 * @param report in long form describing the error, null if absent
8387 * @param logFile to include in the report, null if none
8388 * @param crashInfo giving an application stack trace, null if absent
8389 */
8390 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008391 ProcessRecord process, String processName, ActivityRecord activity,
8392 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008393 final String report, final File logFile,
8394 final ApplicationErrorReport.CrashInfo crashInfo) {
8395 // NOTE -- this must never acquire the ActivityManagerService lock,
8396 // otherwise the watchdog may be prevented from resetting the system.
8397
8398 final String dropboxTag = processClass(process) + "_" + eventType;
8399 final DropBoxManager dbox = (DropBoxManager)
8400 mContext.getSystemService(Context.DROPBOX_SERVICE);
8401
8402 // Exit early if the dropbox isn't configured to accept this report type.
8403 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8404
8405 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008406 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008407 if (activity != null) {
8408 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8409 }
8410 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8411 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8412 }
8413 if (parent != null && parent != activity) {
8414 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8415 }
8416 if (subject != null) {
8417 sb.append("Subject: ").append(subject).append("\n");
8418 }
8419 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008420 if (Debug.isDebuggerConnected()) {
8421 sb.append("Debugger: Connected\n");
8422 }
Dan Egnora455d192010-03-12 08:52:28 -08008423 sb.append("\n");
8424
8425 // Do the rest in a worker thread to avoid blocking the caller on I/O
8426 // (After this point, we shouldn't access AMS internal data structures.)
8427 Thread worker = new Thread("Error dump: " + dropboxTag) {
8428 @Override
8429 public void run() {
8430 if (report != null) {
8431 sb.append(report);
8432 }
8433 if (logFile != null) {
8434 try {
8435 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8436 } catch (IOException e) {
8437 Slog.e(TAG, "Error reading " + logFile, e);
8438 }
8439 }
8440 if (crashInfo != null && crashInfo.stackTrace != null) {
8441 sb.append(crashInfo.stackTrace);
8442 }
8443
8444 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8445 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8446 if (lines > 0) {
8447 sb.append("\n");
8448
8449 // Merge several logcat streams, and take the last N lines
8450 InputStreamReader input = null;
8451 try {
8452 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8453 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8454 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8455
8456 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8457 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8458 input = new InputStreamReader(logcat.getInputStream());
8459
8460 int num;
8461 char[] buf = new char[8192];
8462 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8463 } catch (IOException e) {
8464 Slog.e(TAG, "Error running logcat", e);
8465 } finally {
8466 if (input != null) try { input.close(); } catch (IOException e) {}
8467 }
8468 }
8469
8470 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008471 }
Dan Egnora455d192010-03-12 08:52:28 -08008472 };
8473
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008474 if (process == null) {
8475 // If process is null, we are being called from some internal code
8476 // and may be about to die -- run this synchronously.
8477 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008478 } else {
8479 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008480 }
8481 }
8482
8483 /**
8484 * Bring up the "unexpected error" dialog box for a crashing app.
8485 * Deal with edge cases (intercepts from instrumented applications,
8486 * ActivityController, error intent receivers, that sort of thing).
8487 * @param r the application crashing
8488 * @param crashInfo describing the failure
8489 */
8490 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008491 long timeMillis = System.currentTimeMillis();
8492 String shortMsg = crashInfo.exceptionClassName;
8493 String longMsg = crashInfo.exceptionMessage;
8494 String stackTrace = crashInfo.stackTrace;
8495 if (shortMsg != null && longMsg != null) {
8496 longMsg = shortMsg + ": " + longMsg;
8497 } else if (shortMsg != null) {
8498 longMsg = shortMsg;
8499 }
8500
Dan Egnor60d87622009-12-16 16:32:58 -08008501 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008503 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 try {
8505 String name = r != null ? r.processName : null;
8506 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008507 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008508 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008509 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510 + " at watcher's request");
8511 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008512 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 }
8514 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008515 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 }
8517 }
8518
8519 final long origId = Binder.clearCallingIdentity();
8520
8521 // If this process is running instrumentation, finish it.
8522 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008523 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008525 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8526 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008527 Bundle info = new Bundle();
8528 info.putString("shortMsg", shortMsg);
8529 info.putString("longMsg", longMsg);
8530 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8531 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008532 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 }
8534
Dan Egnor60d87622009-12-16 16:32:58 -08008535 // If we can't identify the process or it's already exceeded its crash quota,
8536 // quit right away without showing a crash dialog.
8537 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008539 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008540 }
8541
8542 Message msg = Message.obtain();
8543 msg.what = SHOW_ERROR_MSG;
8544 HashMap data = new HashMap();
8545 data.put("result", result);
8546 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 msg.obj = data;
8548 mHandler.sendMessage(msg);
8549
8550 Binder.restoreCallingIdentity(origId);
8551 }
8552
8553 int res = result.get();
8554
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008555 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008557 if (r != null && !r.isolated) {
8558 // XXX Can't keep track of crash time for isolated processes,
8559 // since they don't have a persistent identity.
8560 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 SystemClock.uptimeMillis());
8562 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008563 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008564 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008565 }
8566 }
8567
8568 if (appErrorIntent != null) {
8569 try {
8570 mContext.startActivity(appErrorIntent);
8571 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008572 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008576
8577 Intent createAppErrorIntentLocked(ProcessRecord r,
8578 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8579 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008580 if (report == null) {
8581 return null;
8582 }
8583 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8584 result.setComponent(r.errorReportReceiver);
8585 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8586 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8587 return result;
8588 }
8589
Dan Egnorb7f03672009-12-09 16:22:32 -08008590 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8591 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008592 if (r.errorReportReceiver == null) {
8593 return null;
8594 }
8595
8596 if (!r.crashing && !r.notResponding) {
8597 return null;
8598 }
8599
Dan Egnorb7f03672009-12-09 16:22:32 -08008600 ApplicationErrorReport report = new ApplicationErrorReport();
8601 report.packageName = r.info.packageName;
8602 report.installerPackageName = r.errorReportReceiver.getPackageName();
8603 report.processName = r.processName;
8604 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008605 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008606
Dan Egnorb7f03672009-12-09 16:22:32 -08008607 if (r.crashing) {
8608 report.type = ApplicationErrorReport.TYPE_CRASH;
8609 report.crashInfo = crashInfo;
8610 } else if (r.notResponding) {
8611 report.type = ApplicationErrorReport.TYPE_ANR;
8612 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008613
Dan Egnorb7f03672009-12-09 16:22:32 -08008614 report.anrInfo.activity = r.notRespondingReport.tag;
8615 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8616 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008617 }
8618
Dan Egnorb7f03672009-12-09 16:22:32 -08008619 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008620 }
8621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008623 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 // assume our apps are happy - lazy create the list
8625 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8626
Dianne Hackborn0c380492012-08-20 17:23:30 -07008627 final boolean allUsers = ActivityManager.checkUidPermission(
8628 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8629 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8630 int userId = UserHandle.getUserId(Binder.getCallingUid());
8631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 synchronized (this) {
8633
8634 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008635 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8636 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008637 if (!allUsers && app.userId != userId) {
8638 continue;
8639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8641 // This one's in trouble, so we'll generate a report for it
8642 // crashes are higher priority (in case there's a crash *and* an anr)
8643 ActivityManager.ProcessErrorStateInfo report = null;
8644 if (app.crashing) {
8645 report = app.crashingReport;
8646 } else if (app.notResponding) {
8647 report = app.notRespondingReport;
8648 }
8649
8650 if (report != null) {
8651 if (errList == null) {
8652 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8653 }
8654 errList.add(report);
8655 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008656 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 " crashing = " + app.crashing +
8658 " notResponding = " + app.notResponding);
8659 }
8660 }
8661 }
8662 }
8663
8664 return errList;
8665 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008666
8667 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008668 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008669 if (currApp != null) {
8670 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8671 }
8672 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008673 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8674 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008675 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8676 if (currApp != null) {
8677 currApp.lru = 0;
8678 }
8679 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008680 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008681 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8682 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8683 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8684 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8685 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8686 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8687 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8688 } else {
8689 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8690 }
8691 }
8692
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008693 private void fillInProcMemInfo(ProcessRecord app,
8694 ActivityManager.RunningAppProcessInfo outInfo) {
8695 outInfo.pid = app.pid;
8696 outInfo.uid = app.info.uid;
8697 if (mHeavyWeightProcess == app) {
8698 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8699 }
8700 if (app.persistent) {
8701 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8702 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008703 if (app.hasActivities) {
8704 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8705 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008706 outInfo.lastTrimLevel = app.trimMemoryLevel;
8707 int adj = app.curAdj;
8708 outInfo.importance = oomAdjToImportance(adj, outInfo);
8709 outInfo.importanceReasonCode = app.adjTypeCode;
8710 }
8711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008713 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 // Lazy instantiation of list
8715 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008716 final boolean allUsers = ActivityManager.checkUidPermission(
8717 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8718 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8719 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 synchronized (this) {
8721 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008722 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8723 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008724 if (!allUsers && app.userId != userId) {
8725 continue;
8726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8728 // Generate process state info for running application
8729 ActivityManager.RunningAppProcessInfo currApp =
8730 new ActivityManager.RunningAppProcessInfo(app.processName,
8731 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008732 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008733 if (app.adjSource instanceof ProcessRecord) {
8734 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008735 currApp.importanceReasonImportance = oomAdjToImportance(
8736 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008737 } else if (app.adjSource instanceof ActivityRecord) {
8738 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008739 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8740 }
8741 if (app.adjTarget instanceof ComponentName) {
8742 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8743 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008744 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 // + " lru=" + currApp.lru);
8746 if (runList == null) {
8747 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8748 }
8749 runList.add(currApp);
8750 }
8751 }
8752 }
8753 return runList;
8754 }
8755
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008756 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008757 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008758 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8759 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8760 if (runningApps != null && runningApps.size() > 0) {
8761 Set<String> extList = new HashSet<String>();
8762 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8763 if (app.pkgList != null) {
8764 for (String pkg : app.pkgList) {
8765 extList.add(pkg);
8766 }
8767 }
8768 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008769 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008770 for (String pkg : extList) {
8771 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008772 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008773 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8774 retList.add(info);
8775 }
8776 } catch (RemoteException e) {
8777 }
8778 }
8779 }
8780 return retList;
8781 }
8782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008784 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8785 enforceNotIsolatedCaller("getMyMemoryState");
8786 synchronized (this) {
8787 ProcessRecord proc;
8788 synchronized (mPidsSelfLocked) {
8789 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8790 }
8791 fillInProcMemInfo(proc, outInfo);
8792 }
8793 }
8794
8795 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008797 if (checkCallingPermission(android.Manifest.permission.DUMP)
8798 != PackageManager.PERMISSION_GRANTED) {
8799 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8800 + Binder.getCallingPid()
8801 + ", uid=" + Binder.getCallingUid()
8802 + " without permission "
8803 + android.Manifest.permission.DUMP);
8804 return;
8805 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008806
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008807 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008808 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008809 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810
8811 int opti = 0;
8812 while (opti < args.length) {
8813 String opt = args[opti];
8814 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8815 break;
8816 }
8817 opti++;
8818 if ("-a".equals(opt)) {
8819 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008820 } else if ("-c".equals(opt)) {
8821 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008822 } else if ("-h".equals(opt)) {
8823 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008824 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008825 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008826 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008827 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8828 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8829 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008830 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008831 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008832 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008833 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008834 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008835 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008836 pw.println(" all: dump all activities");
8837 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008838 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008839 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8840 pw.println(" a partial substring in a component name, a");
8841 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008842 pw.println(" -a: include all available server state.");
8843 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 } else {
8846 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008849
8850 long origId = Binder.clearCallingIdentity();
8851 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 // Is the caller requesting to dump a particular piece of data?
8853 if (opti < args.length) {
8854 String cmd = args[opti];
8855 opti++;
8856 if ("activities".equals(cmd) || "a".equals(cmd)) {
8857 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008858 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008860 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008861 String[] newArgs;
8862 String name;
8863 if (opti >= args.length) {
8864 name = null;
8865 newArgs = EMPTY_STRING_ARRAY;
8866 } else {
8867 name = args[opti];
8868 opti++;
8869 newArgs = new String[args.length - opti];
8870 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8871 args.length - opti);
8872 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008873 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008874 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008875 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008876 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008877 String[] newArgs;
8878 String name;
8879 if (opti >= args.length) {
8880 name = null;
8881 newArgs = EMPTY_STRING_ARRAY;
8882 } else {
8883 name = args[opti];
8884 opti++;
8885 newArgs = new String[args.length - opti];
8886 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8887 args.length - opti);
8888 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008889 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008890 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008891 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008892 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008893 String[] newArgs;
8894 String name;
8895 if (opti >= args.length) {
8896 name = null;
8897 newArgs = EMPTY_STRING_ARRAY;
8898 } else {
8899 name = args[opti];
8900 opti++;
8901 newArgs = new String[args.length - opti];
8902 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8903 args.length - opti);
8904 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008905 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008906 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008907 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008908 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8909 synchronized (this) {
8910 dumpOomLocked(fd, pw, args, opti, true);
8911 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008912 } else if ("provider".equals(cmd)) {
8913 String[] newArgs;
8914 String name;
8915 if (opti >= args.length) {
8916 name = null;
8917 newArgs = EMPTY_STRING_ARRAY;
8918 } else {
8919 name = args[opti];
8920 opti++;
8921 newArgs = new String[args.length - opti];
8922 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8923 }
8924 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8925 pw.println("No providers match: " + name);
8926 pw.println("Use -h for help.");
8927 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008928 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8929 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008930 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008931 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008932 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008933 String[] newArgs;
8934 String name;
8935 if (opti >= args.length) {
8936 name = null;
8937 newArgs = EMPTY_STRING_ARRAY;
8938 } else {
8939 name = args[opti];
8940 opti++;
8941 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008942 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8943 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008944 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008945 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008946 pw.println("No services match: " + name);
8947 pw.println("Use -h for help.");
8948 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 } else if ("package".equals(cmd)) {
8950 String[] newArgs;
8951 if (opti >= args.length) {
8952 pw.println("package: no package name specified");
8953 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008954 } else {
8955 dumpPackage = args[opti];
8956 opti++;
8957 newArgs = new String[args.length - opti];
8958 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8959 args.length - opti);
8960 args = newArgs;
8961 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008962 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008963 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008964 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8965 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008966 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008967 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008968 } else {
8969 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008970 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8971 pw.println("Bad activity command, or no activities match: " + cmd);
8972 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008973 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008974 }
8975 if (!more) {
8976 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008977 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008979 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008980
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008981 // No piece of data specified, dump everything.
8982 synchronized (this) {
8983 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 if (needSep) {
8986 pw.println(" ");
8987 }
8988 if (dumpAll) {
8989 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 if (needSep) {
8993 pw.println(" ");
8994 }
8995 if (dumpAll) {
8996 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008998 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008999 if (needSep) {
9000 pw.println(" ");
9001 }
9002 if (dumpAll) {
9003 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009004 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009005 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 if (needSep) {
9007 pw.println(" ");
9008 }
9009 if (dumpAll) {
9010 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009012 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 if (needSep) {
9014 pw.println(" ");
9015 }
9016 if (dumpAll) {
9017 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009019 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009021 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009023
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009024 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009025 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009026 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9027 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009028 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9029 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009030 pw.println(" ");
9031 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009032 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9033 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009034 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009036 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009037 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009038 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009039 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009040 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009042 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009043 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009044 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009045 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009046 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9047 pw.println(" ");
9048 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009049 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009050 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009051 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009052 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009053 pw.println(" ");
9054 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009055 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009056 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009060 if (mMainStack.mPausingActivity != null) {
9061 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009062 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009063 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009064 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009065 if (dumpAll) {
9066 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9067 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009068 pw.println(" mDismissKeyguardOnNextActivity: "
9069 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009072 if (mRecentTasks.size() > 0) {
9073 pw.println();
9074 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009075
9076 final int N = mRecentTasks.size();
9077 for (int i=0; i<N; i++) {
9078 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009079 if (dumpPackage != null) {
9080 if (tr.realActivity == null ||
9081 !dumpPackage.equals(tr.realActivity)) {
9082 continue;
9083 }
9084 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9086 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009087 if (dumpAll) {
9088 mRecentTasks.get(i).dump(pw, " ");
9089 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009090 }
9091 }
9092
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009093 if (dumpAll) {
9094 pw.println(" ");
9095 pw.println(" mCurTask: " + mCurTask);
9096 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097
9098 return true;
9099 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009100
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009102 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009103 boolean needSep = false;
9104 int numPers = 0;
9105
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009106 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9107
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009108 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9110 final int NA = procs.size();
9111 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009112 ProcessRecord r = procs.valueAt(ia);
9113 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9114 continue;
9115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009116 if (!needSep) {
9117 pw.println(" All known processes:");
9118 needSep = true;
9119 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009120 pw.print(r.persistent ? " *PERS*" : " *APP*");
9121 pw.print(" UID "); pw.print(procs.keyAt(ia));
9122 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 r.dump(pw, " ");
9124 if (r.persistent) {
9125 numPers++;
9126 }
9127 }
9128 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009129 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009130
9131 if (mIsolatedProcesses.size() > 0) {
9132 if (needSep) pw.println(" ");
9133 needSep = true;
9134 pw.println(" Isolated process list (sorted by uid):");
9135 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9136 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9137 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9138 continue;
9139 }
9140 pw.println(String.format("%sIsolated #%2d: %s",
9141 " ", i, r.toString()));
9142 }
9143 }
9144
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 if (mLruProcesses.size() > 0) {
9146 if (needSep) pw.println(" ");
9147 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009148 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009149 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009150 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009151 needSep = true;
9152 }
9153
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009154 if (dumpAll) {
9155 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009156 boolean printed = false;
9157 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9158 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9159 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9160 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009161 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009162 if (!printed) {
9163 if (needSep) pw.println(" ");
9164 needSep = true;
9165 pw.println(" PID mappings:");
9166 printed = true;
9167 }
9168 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9169 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009170 }
9171 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009172 }
9173
9174 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009175 synchronized (mPidsSelfLocked) {
9176 boolean printed = false;
9177 for (int i=0; i<mForegroundProcesses.size(); i++) {
9178 ProcessRecord r = mPidsSelfLocked.get(
9179 mForegroundProcesses.valueAt(i).pid);
9180 if (dumpPackage != null && (r == null
9181 || !dumpPackage.equals(r.info.packageName))) {
9182 continue;
9183 }
9184 if (!printed) {
9185 if (needSep) pw.println(" ");
9186 needSep = true;
9187 pw.println(" Foreground Processes:");
9188 printed = true;
9189 }
9190 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9191 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009194 }
9195
9196 if (mPersistentStartingProcesses.size() > 0) {
9197 if (needSep) pw.println(" ");
9198 needSep = true;
9199 pw.println(" Persisent processes that are starting:");
9200 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009201 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009203
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009204 if (mRemovedProcesses.size() > 0) {
9205 if (needSep) pw.println(" ");
9206 needSep = true;
9207 pw.println(" Processes that are being removed:");
9208 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009210 }
9211
9212 if (mProcessesOnHold.size() > 0) {
9213 if (needSep) pw.println(" ");
9214 needSep = true;
9215 pw.println(" Processes that are on old until the system is ready:");
9216 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009217 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009220 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009221
9222 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009223 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 long now = SystemClock.uptimeMillis();
9225 for (Map.Entry<String, SparseArray<Long>> procs
9226 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009227 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009228 SparseArray<Long> uids = procs.getValue();
9229 final int N = uids.size();
9230 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009231 int puid = uids.keyAt(i);
9232 ProcessRecord r = mProcessNames.get(pname, puid);
9233 if (dumpPackage != null && (r == null
9234 || !dumpPackage.equals(r.info.packageName))) {
9235 continue;
9236 }
9237 if (!printed) {
9238 if (needSep) pw.println(" ");
9239 needSep = true;
9240 pw.println(" Time since processes crashed:");
9241 printed = true;
9242 }
9243 pw.print(" Process "); pw.print(pname);
9244 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009245 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009246 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9247 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009248 }
9249 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009252 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009253 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009254 for (Map.Entry<String, SparseArray<Long>> procs
9255 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009256 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009257 SparseArray<Long> uids = procs.getValue();
9258 final int N = uids.size();
9259 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009260 int puid = uids.keyAt(i);
9261 ProcessRecord r = mProcessNames.get(pname, puid);
9262 if (dumpPackage != null && (r == null
9263 || !dumpPackage.equals(r.info.packageName))) {
9264 continue;
9265 }
9266 if (!printed) {
9267 if (needSep) pw.println(" ");
9268 needSep = true;
9269 pw.println(" Bad processes:");
9270 }
9271 pw.print(" Bad process "); pw.print(pname);
9272 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009273 pw.print(": crashed at time ");
9274 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009275 }
9276 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009278
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009279 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009280 pw.println(" mStartedUsers:");
9281 for (int i=0; i<mStartedUsers.size(); i++) {
9282 UserStartedState uss = mStartedUsers.valueAt(i);
9283 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009284 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009285 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009286 pw.print(" mUserLru: [");
9287 for (int i=0; i<mUserLru.size(); i++) {
9288 if (i > 0) pw.print(", ");
9289 pw.print(mUserLru.get(i));
9290 }
9291 pw.println("]");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009292 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009293 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009294 if (dumpAll) {
9295 StringBuilder sb = new StringBuilder(128);
9296 sb.append(" mPreviousProcessVisibleTime: ");
9297 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9298 pw.println(sb);
9299 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009300 if (mHeavyWeightProcess != null) {
9301 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009304 if (dumpAll) {
9305 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009306 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009307 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009308 for (Map.Entry<String, Integer> entry
9309 : mCompatModePackages.getPackages().entrySet()) {
9310 String pkg = entry.getKey();
9311 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009312 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9313 continue;
9314 }
9315 if (!printed) {
9316 pw.println(" mScreenCompatPackages:");
9317 printed = true;
9318 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009319 pw.print(" "); pw.print(pkg); pw.print(": ");
9320 pw.print(mode); pw.println();
9321 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009322 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009323 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009324 if (mSleeping || mWentToSleep || mLockScreenShown) {
9325 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9326 + " mLockScreenShown " + mLockScreenShown);
9327 }
9328 if (mShuttingDown) {
9329 pw.println(" mShuttingDown=" + mShuttingDown);
9330 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009331 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9332 || mOrigWaitForDebugger) {
9333 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9334 + " mDebugTransient=" + mDebugTransient
9335 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9336 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009337 if (mOpenGlTraceApp != null) {
9338 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9339 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009340 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9341 || mProfileFd != null) {
9342 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9343 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9344 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9345 + mAutoStopProfiler);
9346 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009347 if (mAlwaysFinishActivities || mController != null) {
9348 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9349 + " mController=" + mController);
9350 }
9351 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009354 + " mProcessesReady=" + mProcessesReady
9355 + " mSystemReady=" + mSystemReady);
9356 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 + " mBooted=" + mBooted
9358 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009359 pw.print(" mLastPowerCheckRealtime=");
9360 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9361 pw.println("");
9362 pw.print(" mLastPowerCheckUptime=");
9363 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9364 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009365 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9366 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009367 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009368 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9369 + " mNumHiddenProcs=" + mNumHiddenProcs
9370 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009371 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009373
9374 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 }
9376
Dianne Hackborn287952c2010-09-22 22:34:31 -07009377 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009378 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009379 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009380 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009381 long now = SystemClock.uptimeMillis();
9382 for (int i=0; i<mProcessesToGc.size(); i++) {
9383 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009384 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9385 continue;
9386 }
9387 if (!printed) {
9388 if (needSep) pw.println(" ");
9389 needSep = true;
9390 pw.println(" Processes that are waiting to GC:");
9391 printed = true;
9392 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009393 pw.print(" Process "); pw.println(proc);
9394 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9395 pw.print(", last gced=");
9396 pw.print(now-proc.lastRequestedGc);
9397 pw.print(" ms ago, last lowMem=");
9398 pw.print(now-proc.lastLowMemory);
9399 pw.println(" ms ago");
9400
9401 }
9402 }
9403 return needSep;
9404 }
9405
9406 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9407 int opti, boolean dumpAll) {
9408 boolean needSep = false;
9409
9410 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009411 if (needSep) pw.println(" ");
9412 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009413 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009414 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009415 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009416 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9417 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9418 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9419 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9420 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009421 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009422 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009423 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009424 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009425 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009426 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009427
9428 if (needSep) pw.println(" ");
9429 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009430 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009431 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009432 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009433 needSep = true;
9434 }
9435
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009436 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009437
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009438 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009439 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009440 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009441 if (mHeavyWeightProcess != null) {
9442 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9443 }
9444
9445 return true;
9446 }
9447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 /**
9449 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009450 * - no provider specified: dump all the providers
9451 * - a flattened component name that matched an existing provider was specified as the
9452 * first arg: dump that one provider
9453 * - the first arg isn't the flattened component name of an existing provider:
9454 * dump all providers whose component contains the first arg as a substring
9455 */
9456 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9457 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009458 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009459 }
9460
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009461 static class ItemMatcher {
9462 ArrayList<ComponentName> components;
9463 ArrayList<String> strings;
9464 ArrayList<Integer> objects;
9465 boolean all;
9466
9467 ItemMatcher() {
9468 all = true;
9469 }
9470
9471 void build(String name) {
9472 ComponentName componentName = ComponentName.unflattenFromString(name);
9473 if (componentName != null) {
9474 if (components == null) {
9475 components = new ArrayList<ComponentName>();
9476 }
9477 components.add(componentName);
9478 all = false;
9479 } else {
9480 int objectId = 0;
9481 // Not a '/' separated full component name; maybe an object ID?
9482 try {
9483 objectId = Integer.parseInt(name, 16);
9484 if (objects == null) {
9485 objects = new ArrayList<Integer>();
9486 }
9487 objects.add(objectId);
9488 all = false;
9489 } catch (RuntimeException e) {
9490 // Not an integer; just do string match.
9491 if (strings == null) {
9492 strings = new ArrayList<String>();
9493 }
9494 strings.add(name);
9495 all = false;
9496 }
9497 }
9498 }
9499
9500 int build(String[] args, int opti) {
9501 for (; opti<args.length; opti++) {
9502 String name = args[opti];
9503 if ("--".equals(name)) {
9504 return opti+1;
9505 }
9506 build(name);
9507 }
9508 return opti;
9509 }
9510
9511 boolean match(Object object, ComponentName comp) {
9512 if (all) {
9513 return true;
9514 }
9515 if (components != null) {
9516 for (int i=0; i<components.size(); i++) {
9517 if (components.get(i).equals(comp)) {
9518 return true;
9519 }
9520 }
9521 }
9522 if (objects != null) {
9523 for (int i=0; i<objects.size(); i++) {
9524 if (System.identityHashCode(object) == objects.get(i)) {
9525 return true;
9526 }
9527 }
9528 }
9529 if (strings != null) {
9530 String flat = comp.flattenToString();
9531 for (int i=0; i<strings.size(); i++) {
9532 if (flat.contains(strings.get(i))) {
9533 return true;
9534 }
9535 }
9536 }
9537 return false;
9538 }
9539 }
9540
Dianne Hackborn625ac272010-09-17 18:29:22 -07009541 /**
9542 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009543 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009544 * - the cmd arg isn't the flattened component name of an existing activity:
9545 * dump all activity whose component contains the cmd as a substring
9546 * - A hex number of the ActivityRecord object instance.
9547 */
9548 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9549 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009550 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009551
9552 if ("all".equals(name)) {
9553 synchronized (this) {
9554 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009555 activities.add(r1);
9556 }
9557 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009558 } else if ("top".equals(name)) {
9559 synchronized (this) {
9560 final int N = mMainStack.mHistory.size();
9561 if (N > 0) {
9562 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9563 }
9564 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009565 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009566 ItemMatcher matcher = new ItemMatcher();
9567 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009568
9569 synchronized (this) {
9570 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009571 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009572 activities.add(r1);
9573 }
9574 }
9575 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009576 }
9577
9578 if (activities.size() <= 0) {
9579 return false;
9580 }
9581
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009582 String[] newArgs = new String[args.length - opti];
9583 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9584
Dianne Hackborn30d71892010-12-11 10:37:55 -08009585 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009586 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009587 for (int i=activities.size()-1; i>=0; i--) {
9588 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009589 if (needSep) {
9590 pw.println();
9591 }
9592 needSep = true;
9593 synchronized (this) {
9594 if (lastTask != r.task) {
9595 lastTask = r.task;
9596 pw.print("TASK "); pw.print(lastTask.affinity);
9597 pw.print(" id="); pw.println(lastTask.taskId);
9598 if (dumpAll) {
9599 lastTask.dump(pw, " ");
9600 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009601 }
9602 }
9603 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009604 }
9605 return true;
9606 }
9607
9608 /**
9609 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9610 * there is a thread associated with the activity.
9611 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009612 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009613 final ActivityRecord r, String[] args, boolean dumpAll) {
9614 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009615 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009616 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9617 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9618 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009619 if (r.app != null) pw.println(r.app.pid);
9620 else pw.println("(not running)");
9621 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009622 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009623 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009624 }
9625 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009626 // flush anything that is already in the PrintWriter since the thread is going
9627 // to write to the file descriptor directly
9628 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009629 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009630 TransferPipe tp = new TransferPipe();
9631 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009632 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9633 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009634 tp.go(fd);
9635 } finally {
9636 tp.kill();
9637 }
9638 } catch (IOException e) {
9639 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009640 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009641 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009642 }
9643 }
9644 }
9645
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009646 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009647 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009648 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009649 boolean onlyHistory = false;
9650
9651 if ("history".equals(dumpPackage)) {
9652 onlyHistory = true;
9653 dumpPackage = null;
9654 }
9655
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009656 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009657 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009658 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009659 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 Iterator it = mRegisteredReceivers.values().iterator();
9661 while (it.hasNext()) {
9662 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009663 if (dumpPackage != null && (r.app == null ||
9664 !dumpPackage.equals(r.app.info.packageName))) {
9665 continue;
9666 }
9667 if (!printed) {
9668 pw.println(" Registered Receivers:");
9669 needSep = true;
9670 printed = true;
9671 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009672 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 r.dump(pw, " ");
9674 }
9675 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009676
9677 if (mReceiverResolver.dump(pw, needSep ?
9678 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9679 " ", dumpPackage, false)) {
9680 needSep = true;
9681 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009682 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009683
9684 for (BroadcastQueue q : mBroadcastQueues) {
9685 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009687
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009688 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009689
Dianne Hackborn786b4402012-08-27 15:14:02 -07009690 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009691 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9692 if (needSep) {
9693 pw.println();
9694 }
9695 needSep = true;
9696 pw.print(" Sticky broadcasts for user ");
9697 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9698 StringBuilder sb = new StringBuilder(128);
9699 for (Map.Entry<String, ArrayList<Intent>> ent
9700 : mStickyBroadcasts.valueAt(user).entrySet()) {
9701 pw.print(" * Sticky action "); pw.print(ent.getKey());
9702 if (dumpAll) {
9703 pw.println(":");
9704 ArrayList<Intent> intents = ent.getValue();
9705 final int N = intents.size();
9706 for (int i=0; i<N; i++) {
9707 sb.setLength(0);
9708 sb.append(" Intent: ");
9709 intents.get(i).toShortString(sb, false, true, false, false);
9710 pw.println(sb.toString());
9711 Bundle bundle = intents.get(i).getExtras();
9712 if (bundle != null) {
9713 pw.print(" ");
9714 pw.println(bundle.toString());
9715 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009716 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009717 } else {
9718 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009719 }
9720 }
9721 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009722 }
9723
Dianne Hackborn786b4402012-08-27 15:14:02 -07009724 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009725 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009726 for (BroadcastQueue queue : mBroadcastQueues) {
9727 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9728 + queue.mBroadcastsScheduled);
9729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009730 pw.println(" mHandler:");
9731 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009732 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009733 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009734
9735 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009736 }
9737
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009738 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009739 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009740 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009741
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009742 ItemMatcher matcher = new ItemMatcher();
9743 matcher.build(args, opti);
9744
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009745 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009746
9747 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009748
9749 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009750 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009751 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009752 ContentProviderRecord r = mLaunchingProviders.get(i);
9753 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9754 continue;
9755 }
9756 if (!printed) {
9757 if (needSep) pw.println(" ");
9758 needSep = true;
9759 pw.println(" Launching content providers:");
9760 printed = true;
9761 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009762 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009763 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009764 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009765 }
9766
9767 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009768 if (needSep) pw.println();
9769 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009770 pw.println("Granted Uri Permissions:");
9771 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9772 int uid = mGrantedUriPermissions.keyAt(i);
9773 HashMap<Uri, UriPermission> perms
9774 = mGrantedUriPermissions.valueAt(i);
9775 pw.print(" * UID "); pw.print(uid);
9776 pw.println(" holds:");
9777 for (UriPermission perm : perms.values()) {
9778 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009779 if (dumpAll) {
9780 perm.dump(pw, " ");
9781 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009782 }
9783 }
9784 needSep = true;
9785 }
9786
9787 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009788 }
9789
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009790 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009791 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009792 boolean needSep = false;
9793
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009794 if (mIntentSenderRecords.size() > 0) {
9795 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009796 Iterator<WeakReference<PendingIntentRecord>> it
9797 = mIntentSenderRecords.values().iterator();
9798 while (it.hasNext()) {
9799 WeakReference<PendingIntentRecord> ref = it.next();
9800 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009801 if (dumpPackage != null && (rec == null
9802 || !dumpPackage.equals(rec.key.packageName))) {
9803 continue;
9804 }
9805 if (!printed) {
9806 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9807 printed = true;
9808 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009809 needSep = true;
9810 if (rec != null) {
9811 pw.print(" * "); pw.println(rec);
9812 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009813 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009814 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009815 } else {
9816 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009817 }
9818 }
9819 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009820
9821 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009822 }
9823
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009824 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009825 String prefix, String label, boolean complete, boolean brief, boolean client,
9826 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009827 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009828 boolean needNL = false;
9829 final String innerPrefix = prefix + " ";
9830 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009831 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009832 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009833 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9834 continue;
9835 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009836 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009837 if (needNL) {
9838 pw.println(" ");
9839 needNL = false;
9840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 if (lastTask != r.task) {
9842 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009843 pw.print(prefix);
9844 pw.print(full ? "* " : " ");
9845 pw.println(lastTask);
9846 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009847 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009848 } else if (complete) {
9849 // Complete + brief == give a summary. Isn't that obvious?!?
9850 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009851 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009852 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009853 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009855 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009856 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9857 pw.print(" #"); pw.print(i); pw.print(": ");
9858 pw.println(r);
9859 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 r.dump(pw, innerPrefix);
9861 } else if (complete) {
9862 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009863 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009864 if (r.app != null) {
9865 pw.print(innerPrefix); pw.println(r.app);
9866 }
9867 }
9868 if (client && r.app != null && r.app.thread != null) {
9869 // flush anything that is already in the PrintWriter since the thread is going
9870 // to write to the file descriptor directly
9871 pw.flush();
9872 try {
9873 TransferPipe tp = new TransferPipe();
9874 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009875 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9876 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009877 // Short timeout, since blocking here can
9878 // deadlock with the application.
9879 tp.go(fd, 2000);
9880 } finally {
9881 tp.kill();
9882 }
9883 } catch (IOException e) {
9884 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9885 } catch (RemoteException e) {
9886 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9887 }
9888 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009890 }
9891 }
9892
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009893 private static String buildOomTag(String prefix, String space, int val, int base) {
9894 if (val == base) {
9895 if (space == null) return prefix;
9896 return prefix + " ";
9897 }
9898 return prefix + "+" + Integer.toString(val-base);
9899 }
9900
9901 private static final int dumpProcessList(PrintWriter pw,
9902 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009903 String prefix, String normalLabel, String persistentLabel,
9904 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009905 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009906 final int N = list.size()-1;
9907 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009908 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009909 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9910 continue;
9911 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009912 pw.println(String.format("%s%s #%2d: %s",
9913 prefix, (r.persistent ? persistentLabel : normalLabel),
9914 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 if (r.persistent) {
9916 numPers++;
9917 }
9918 }
9919 return numPers;
9920 }
9921
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009922 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009923 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009924 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009925 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009926
Dianne Hackborn905577f2011-09-07 18:31:28 -07009927 ArrayList<Pair<ProcessRecord, Integer>> list
9928 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9929 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009930 ProcessRecord r = origList.get(i);
9931 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9932 continue;
9933 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009934 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9935 }
9936
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009937 if (list.size() <= 0) {
9938 return false;
9939 }
9940
Dianne Hackborn905577f2011-09-07 18:31:28 -07009941 Comparator<Pair<ProcessRecord, Integer>> comparator
9942 = new Comparator<Pair<ProcessRecord, Integer>>() {
9943 @Override
9944 public int compare(Pair<ProcessRecord, Integer> object1,
9945 Pair<ProcessRecord, Integer> object2) {
9946 if (object1.first.setAdj != object2.first.setAdj) {
9947 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9948 }
9949 if (object1.second.intValue() != object2.second.intValue()) {
9950 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9951 }
9952 return 0;
9953 }
9954 };
9955
9956 Collections.sort(list, comparator);
9957
Dianne Hackborn287952c2010-09-22 22:34:31 -07009958 final long curRealtime = SystemClock.elapsedRealtime();
9959 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9960 final long curUptime = SystemClock.uptimeMillis();
9961 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9962
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009963 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009964 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009965 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009966 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009967 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009968 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9969 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009970 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9971 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009972 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9973 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009974 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9975 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009976 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009977 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009978 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9979 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9980 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9981 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9982 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9983 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9984 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9985 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009986 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9987 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009988 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9989 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009990 } else {
9991 oomAdj = Integer.toString(r.setAdj);
9992 }
9993 String schedGroup;
9994 switch (r.setSchedGroup) {
9995 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9996 schedGroup = "B";
9997 break;
9998 case Process.THREAD_GROUP_DEFAULT:
9999 schedGroup = "F";
10000 break;
10001 default:
10002 schedGroup = Integer.toString(r.setSchedGroup);
10003 break;
10004 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010005 String foreground;
10006 if (r.foregroundActivities) {
10007 foreground = "A";
10008 } else if (r.foregroundServices) {
10009 foreground = "S";
10010 } else {
10011 foreground = " ";
10012 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010013 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010014 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010015 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10016 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010017 if (r.adjSource != null || r.adjTarget != null) {
10018 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010019 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010020 if (r.adjTarget instanceof ComponentName) {
10021 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10022 } else if (r.adjTarget != null) {
10023 pw.print(r.adjTarget.toString());
10024 } else {
10025 pw.print("{null}");
10026 }
10027 pw.print("<=");
10028 if (r.adjSource instanceof ProcessRecord) {
10029 pw.print("Proc{");
10030 pw.print(((ProcessRecord)r.adjSource).toShortString());
10031 pw.println("}");
10032 } else if (r.adjSource != null) {
10033 pw.println(r.adjSource.toString());
10034 } else {
10035 pw.println("{null}");
10036 }
10037 }
10038 if (inclDetails) {
10039 pw.print(prefix);
10040 pw.print(" ");
10041 pw.print("oom: max="); pw.print(r.maxAdj);
10042 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010043 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010044 pw.print(" curRaw="); pw.print(r.curRawAdj);
10045 pw.print(" setRaw="); pw.print(r.setRawAdj);
10046 pw.print(" cur="); pw.print(r.curAdj);
10047 pw.print(" set="); pw.println(r.setAdj);
10048 pw.print(prefix);
10049 pw.print(" ");
10050 pw.print("keeping="); pw.print(r.keeping);
10051 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010052 pw.print(" empty="); pw.print(r.empty);
10053 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010054
10055 if (!r.keeping) {
10056 if (r.lastWakeTime != 0) {
10057 long wtime;
10058 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10059 synchronized (stats) {
10060 wtime = stats.getProcessWakeTime(r.info.uid,
10061 r.pid, curRealtime);
10062 }
10063 long timeUsed = wtime - r.lastWakeTime;
10064 pw.print(prefix);
10065 pw.print(" ");
10066 pw.print("keep awake over ");
10067 TimeUtils.formatDuration(realtimeSince, pw);
10068 pw.print(" used ");
10069 TimeUtils.formatDuration(timeUsed, pw);
10070 pw.print(" (");
10071 pw.print((timeUsed*100)/realtimeSince);
10072 pw.println("%)");
10073 }
10074 if (r.lastCpuTime != 0) {
10075 long timeUsed = r.curCpuTime - r.lastCpuTime;
10076 pw.print(prefix);
10077 pw.print(" ");
10078 pw.print("run cpu over ");
10079 TimeUtils.formatDuration(uptimeSince, pw);
10080 pw.print(" used ");
10081 TimeUtils.formatDuration(timeUsed, pw);
10082 pw.print(" (");
10083 pw.print((timeUsed*100)/uptimeSince);
10084 pw.println("%)");
10085 }
10086 }
10087 }
10088 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010089 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010090 }
10091
Dianne Hackbornb437e092011-08-05 17:50:29 -070010092 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010093 ArrayList<ProcessRecord> procs;
10094 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010095 if (args != null && args.length > start
10096 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010097 procs = new ArrayList<ProcessRecord>();
10098 int pid = -1;
10099 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010100 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010101 } catch (NumberFormatException e) {
10102
10103 }
10104 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10105 ProcessRecord proc = mLruProcesses.get(i);
10106 if (proc.pid == pid) {
10107 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010108 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010109 procs.add(proc);
10110 }
10111 }
10112 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010113 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010114 return null;
10115 }
10116 } else {
10117 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10118 }
10119 }
10120 return procs;
10121 }
10122
10123 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10124 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010125 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010126 if (procs == null) {
10127 return;
10128 }
10129
10130 long uptime = SystemClock.uptimeMillis();
10131 long realtime = SystemClock.elapsedRealtime();
10132 pw.println("Applications Graphics Acceleration Info:");
10133 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10134
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010135 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10136 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010137 if (r.thread != null) {
10138 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10139 pw.flush();
10140 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010141 TransferPipe tp = new TransferPipe();
10142 try {
10143 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10144 tp.go(fd);
10145 } finally {
10146 tp.kill();
10147 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010148 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010149 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010150 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010151 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010152 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010153 pw.flush();
10154 }
10155 }
10156 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010157 }
10158
Jeff Brown6754ba22011-12-14 20:20:01 -080010159 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10160 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10161 if (procs == null) {
10162 return;
10163 }
10164
10165 pw.println("Applications Database Info:");
10166
10167 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10168 ProcessRecord r = procs.get(i);
10169 if (r.thread != null) {
10170 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10171 pw.flush();
10172 try {
10173 TransferPipe tp = new TransferPipe();
10174 try {
10175 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10176 tp.go(fd);
10177 } finally {
10178 tp.kill();
10179 }
10180 } catch (IOException e) {
10181 pw.println("Failure while dumping the app: " + r);
10182 pw.flush();
10183 } catch (RemoteException e) {
10184 pw.println("Got a RemoteException while dumping the app " + r);
10185 pw.flush();
10186 }
10187 }
10188 }
10189 }
10190
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010191 final static class MemItem {
10192 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010193 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010194 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010195 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010196 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010197
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010198 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010199 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010200 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010201 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010202 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010203 }
10204 }
10205
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010206 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010207 boolean sort) {
10208 if (sort) {
10209 Collections.sort(items, new Comparator<MemItem>() {
10210 @Override
10211 public int compare(MemItem lhs, MemItem rhs) {
10212 if (lhs.pss < rhs.pss) {
10213 return 1;
10214 } else if (lhs.pss > rhs.pss) {
10215 return -1;
10216 }
10217 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010218 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010219 });
10220 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010221
10222 for (int i=0; i<items.size(); i++) {
10223 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010224 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010225 if (mi.subitems != null) {
10226 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10227 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010228 }
10229 }
10230
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010231 // These are in KB.
10232 static final long[] DUMP_MEM_BUCKETS = new long[] {
10233 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10234 120*1024, 160*1024, 200*1024,
10235 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10236 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10237 };
10238
Dianne Hackborn672342c2011-11-29 11:29:02 -080010239 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10240 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010241 int start = label.lastIndexOf('.');
10242 if (start >= 0) start++;
10243 else start = 0;
10244 int end = label.length();
10245 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10246 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10247 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10248 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010249 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010250 out.append(label, start, end);
10251 return;
10252 }
10253 }
10254 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010255 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010256 out.append(label, start, end);
10257 }
10258
10259 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10260 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10261 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10262 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10263 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10264 };
10265 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10266 "System", "Persistent", "Foreground",
10267 "Visible", "Perceptible", "Heavy Weight",
10268 "Backup", "A Services", "Home", "Previous",
10269 "B Services", "Background"
10270 };
10271
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010272 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010273 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010274 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010275 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010276 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010277
10278 int opti = 0;
10279 while (opti < args.length) {
10280 String opt = args[opti];
10281 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10282 break;
10283 }
10284 opti++;
10285 if ("-a".equals(opt)) {
10286 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010287 } else if ("--oom".equals(opt)) {
10288 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010289 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010290 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010291 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010292 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010293 pw.println("If [process] is specified it can be the name or ");
10294 pw.println("pid of a specific process to dump.");
10295 return;
10296 } else {
10297 pw.println("Unknown argument: " + opt + "; use -h for help");
10298 }
10299 }
10300
10301 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010302 if (procs == null) {
10303 return;
10304 }
10305
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010306 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010307 long uptime = SystemClock.uptimeMillis();
10308 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010309
10310 if (procs.size() == 1 || isCheckinRequest) {
10311 dumpAll = true;
10312 }
10313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010314 if (isCheckinRequest) {
10315 // short checkin version
10316 pw.println(uptime + "," + realtime);
10317 pw.flush();
10318 } else {
10319 pw.println("Applications Memory Usage (kB):");
10320 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10321 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010322
Dianne Hackbornb437e092011-08-05 17:50:29 -070010323 String[] innerArgs = new String[args.length-opti];
10324 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10325
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010326 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10327 long nativePss=0, dalvikPss=0, otherPss=0;
10328 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10329
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010330 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10331 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10332 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010333
10334 long totalPss = 0;
10335
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010336 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10337 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010338 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010339 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010340 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10341 pw.flush();
10342 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010343 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010344 if (dumpAll) {
10345 try {
10346 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10347 } catch (RemoteException e) {
10348 if (!isCheckinRequest) {
10349 pw.println("Got RemoteException!");
10350 pw.flush();
10351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010353 } else {
10354 mi = new Debug.MemoryInfo();
10355 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010356 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010357
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010358 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010359 long myTotalPss = mi.getTotalPss();
10360 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010361 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010362 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010363 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010364
10365 nativePss += mi.nativePss;
10366 dalvikPss += mi.dalvikPss;
10367 otherPss += mi.otherPss;
10368 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10369 long mem = mi.getOtherPss(j);
10370 miscPss[j] += mem;
10371 otherPss -= mem;
10372 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010373
10374 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010375 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10376 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010377 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010378 if (oomProcs[oomIndex] == null) {
10379 oomProcs[oomIndex] = new ArrayList<MemItem>();
10380 }
10381 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010382 break;
10383 }
10384 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010386 }
10387 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010388
10389 if (!isCheckinRequest && procs.size() > 1) {
10390 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10391
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010392 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10393 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10394 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010395 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010396 String label = Debug.MemoryInfo.getOtherLabel(j);
10397 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010398 }
10399
Dianne Hackbornb437e092011-08-05 17:50:29 -070010400 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10401 for (int j=0; j<oomPss.length; j++) {
10402 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010403 String label = DUMP_MEM_OOM_LABEL[j];
10404 MemItem item = new MemItem(label, label, oomPss[j],
10405 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010406 item.subitems = oomProcs[j];
10407 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010408 }
10409 }
10410
Dianne Hackborn672342c2011-11-29 11:29:02 -080010411 if (outTag != null || outStack != null) {
10412 if (outTag != null) {
10413 appendMemBucket(outTag, totalPss, "total", false);
10414 }
10415 if (outStack != null) {
10416 appendMemBucket(outStack, totalPss, "total", true);
10417 }
10418 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010419 for (int i=0; i<oomMems.size(); i++) {
10420 MemItem miCat = oomMems.get(i);
10421 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10422 continue;
10423 }
10424 if (miCat.id < ProcessList.SERVICE_ADJ
10425 || miCat.id == ProcessList.HOME_APP_ADJ
10426 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010427 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10428 outTag.append(" / ");
10429 }
10430 if (outStack != null) {
10431 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10432 if (firstLine) {
10433 outStack.append(":");
10434 firstLine = false;
10435 }
10436 outStack.append("\n\t at ");
10437 } else {
10438 outStack.append("$");
10439 }
10440 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010441 for (int j=0; j<miCat.subitems.size(); j++) {
10442 MemItem mi = miCat.subitems.get(j);
10443 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010444 if (outTag != null) {
10445 outTag.append(" ");
10446 }
10447 if (outStack != null) {
10448 outStack.append("$");
10449 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010450 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010451 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10452 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10453 }
10454 if (outStack != null) {
10455 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10456 }
10457 }
10458 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10459 outStack.append("(");
10460 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10461 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10462 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10463 outStack.append(":");
10464 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10465 }
10466 }
10467 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010468 }
10469 }
10470 }
10471 }
10472
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010473 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010474 pw.println();
10475 pw.println("Total PSS by process:");
10476 dumpMemItems(pw, " ", procMems, true);
10477 pw.println();
10478 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010479 pw.println("Total PSS by OOM adjustment:");
10480 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010481 if (!oomOnly) {
10482 PrintWriter out = categoryPw != null ? categoryPw : pw;
10483 out.println();
10484 out.println("Total PSS by category:");
10485 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010486 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010487 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010488 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010489 final int[] SINGLE_LONG_FORMAT = new int[] {
10490 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10491 };
10492 long[] longOut = new long[1];
10493 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10494 SINGLE_LONG_FORMAT, null, longOut, null);
10495 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10496 longOut[0] = 0;
10497 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10498 SINGLE_LONG_FORMAT, null, longOut, null);
10499 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10500 longOut[0] = 0;
10501 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10502 SINGLE_LONG_FORMAT, null, longOut, null);
10503 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10504 longOut[0] = 0;
10505 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10506 SINGLE_LONG_FORMAT, null, longOut, null);
10507 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10508 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10509 pw.print(shared); pw.println(" kB");
10510 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10511 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010513 }
10514
10515 /**
10516 * Searches array of arguments for the specified string
10517 * @param args array of argument strings
10518 * @param value value to search for
10519 * @return true if the value is contained in the array
10520 */
10521 private static boolean scanArgs(String[] args, String value) {
10522 if (args != null) {
10523 for (String arg : args) {
10524 if (value.equals(arg)) {
10525 return true;
10526 }
10527 }
10528 }
10529 return false;
10530 }
10531
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010532 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10533 ContentProviderRecord cpr, boolean always) {
10534 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10535
10536 if (!inLaunching || always) {
10537 synchronized (cpr) {
10538 cpr.launchingApp = null;
10539 cpr.notifyAll();
10540 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010541 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010542 String names[] = cpr.info.authority.split(";");
10543 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010544 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 }
10546 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010547
10548 for (int i=0; i<cpr.connections.size(); i++) {
10549 ContentProviderConnection conn = cpr.connections.get(i);
10550 if (conn.waiting) {
10551 // If this connection is waiting for the provider, then we don't
10552 // need to mess with its process unless we are always removing
10553 // or for some reason the provider is not currently launching.
10554 if (inLaunching && !always) {
10555 continue;
10556 }
10557 }
10558 ProcessRecord capp = conn.client;
10559 conn.dead = true;
10560 if (conn.stableCount > 0) {
10561 if (!capp.persistent && capp.thread != null
10562 && capp.pid != 0
10563 && capp.pid != MY_PID) {
10564 Slog.i(TAG, "Kill " + capp.processName
10565 + " (pid " + capp.pid + "): provider " + cpr.info.name
10566 + " in dying process " + (proc != null ? proc.processName : "??"));
10567 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10568 capp.processName, capp.setAdj, "dying provider "
10569 + cpr.name.toShortString());
10570 Process.killProcessQuiet(capp.pid);
10571 }
10572 } else if (capp.thread != null && conn.provider.provider != null) {
10573 try {
10574 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10575 } catch (RemoteException e) {
10576 }
10577 // In the protocol here, we don't expect the client to correctly
10578 // clean up this connection, we'll just remove it.
10579 cpr.connections.remove(i);
10580 conn.client.conProviders.remove(conn);
10581 }
10582 }
10583
10584 if (inLaunching && always) {
10585 mLaunchingProviders.remove(cpr);
10586 }
10587 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 }
10589
10590 /**
10591 * Main code for cleaning up a process when it has gone away. This is
10592 * called both as a result of the process dying, or directly when stopping
10593 * a process when running in single process mode.
10594 */
10595 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010596 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010597 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010598 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 }
10600
Dianne Hackborn36124872009-10-08 16:22:03 -070010601 mProcessesToGc.remove(app);
10602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010603 // Dismiss any open dialogs.
10604 if (app.crashDialog != null) {
10605 app.crashDialog.dismiss();
10606 app.crashDialog = null;
10607 }
10608 if (app.anrDialog != null) {
10609 app.anrDialog.dismiss();
10610 app.anrDialog = null;
10611 }
10612 if (app.waitDialog != null) {
10613 app.waitDialog.dismiss();
10614 app.waitDialog = null;
10615 }
10616
10617 app.crashing = false;
10618 app.notResponding = false;
10619
10620 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010621 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010622 app.thread = null;
10623 app.forcingToForeground = null;
10624 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010625 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010626 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010627 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010629 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630
10631 boolean restart = false;
10632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 // Remove published content providers.
10634 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010635 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010637 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010638
10639 final boolean always = app.bad || !allowRestart;
10640 if (removeDyingProviderLocked(app, cpr, always) || always) {
10641 // We left the provider in the launching list, need to
10642 // restart it.
10643 restart = true;
10644 }
10645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010647 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 }
10649 app.pubProviders.clear();
10650 }
10651
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010652 // Take care of any launching providers waiting for this process.
10653 if (checkAppInLaunchingProvidersLocked(app, false)) {
10654 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010655 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657 // Unregister from connected content providers.
10658 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010659 for (int i=0; i<app.conProviders.size(); i++) {
10660 ContentProviderConnection conn = app.conProviders.get(i);
10661 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010662 }
10663 app.conProviders.clear();
10664 }
10665
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010666 // At this point there may be remaining entries in mLaunchingProviders
10667 // where we were the only one waiting, so they are no longer of use.
10668 // Look for these and clean up if found.
10669 // XXX Commented out for now. Trying to figure out a way to reproduce
10670 // the actual situation to identify what is actually going on.
10671 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010672 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010673 ContentProviderRecord cpr = (ContentProviderRecord)
10674 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010675 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010676 synchronized (cpr) {
10677 cpr.launchingApp = null;
10678 cpr.notifyAll();
10679 }
10680 }
10681 }
10682 }
10683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684 skipCurrentReceiverLocked(app);
10685
10686 // Unregister any receivers.
10687 if (app.receivers.size() > 0) {
10688 Iterator<ReceiverList> it = app.receivers.iterator();
10689 while (it.hasNext()) {
10690 removeReceiverLocked(it.next());
10691 }
10692 app.receivers.clear();
10693 }
10694
Christopher Tate181fafa2009-05-14 11:12:14 -070010695 // If the app is undergoing backup, tell the backup manager about it
10696 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010697 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010698 try {
10699 IBackupManager bm = IBackupManager.Stub.asInterface(
10700 ServiceManager.getService(Context.BACKUP_SERVICE));
10701 bm.agentDisconnected(app.info.packageName);
10702 } catch (RemoteException e) {
10703 // can't happen; backup manager is local
10704 }
10705 }
10706
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010707 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10708 ProcessChangeItem item = mPendingProcessChanges.get(i);
10709 if (item.pid == app.pid) {
10710 mPendingProcessChanges.remove(i);
10711 mAvailProcessChanges.add(item);
10712 }
10713 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010714 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010716 // If the caller is restarting this app, then leave it in its
10717 // current lists and let the caller take care of it.
10718 if (restarting) {
10719 return;
10720 }
10721
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010722 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010723 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010724 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010725 mProcessNames.remove(app.processName, app.uid);
10726 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010727 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010728 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10729 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010730 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010732 } else if (!app.removed) {
10733 // This app is persistent, so we need to keep its record around.
10734 // If it is not already on the pending app list, add it there
10735 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10737 mPersistentStartingProcesses.add(app);
10738 restart = true;
10739 }
10740 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010741 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10742 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743 mProcessesOnHold.remove(app);
10744
The Android Open Source Project4df24232009-03-05 14:34:35 -080010745 if (app == mHomeProcess) {
10746 mHomeProcess = null;
10747 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010748 if (app == mPreviousProcess) {
10749 mPreviousProcess = null;
10750 }
10751
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010752 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 // We have components that still need to be running in the
10754 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010755 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 startProcessLocked(app, "restart", app.processName);
10757 } else if (app.pid > 0 && app.pid != MY_PID) {
10758 // Goodbye!
10759 synchronized (mPidsSelfLocked) {
10760 mPidsSelfLocked.remove(app.pid);
10761 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10762 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010763 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010764 }
10765 }
10766
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010767 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10768 // Look through the content providers we are waiting to have launched,
10769 // and if any run in this process then either schedule a restart of
10770 // the process or kill the client waiting for it if this process has
10771 // gone bad.
10772 int NL = mLaunchingProviders.size();
10773 boolean restart = false;
10774 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010775 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010776 if (cpr.launchingApp == app) {
10777 if (!alwaysBad && !app.bad) {
10778 restart = true;
10779 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010780 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010781 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010782 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010783 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010784 }
10785 }
10786 }
10787 return restart;
10788 }
10789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010790 // =========================================================
10791 // SERVICES
10792 // =========================================================
10793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010794 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10795 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010796 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010797 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010798 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799 }
10800 }
10801
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010802 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010803 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010804 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010805 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010806 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010807 }
10808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010810 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010811 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010812 // Refuse possible leaked file descriptors
10813 if (service != null && service.hasFileDescriptors() == true) {
10814 throw new IllegalArgumentException("File descriptors passed in Intent");
10815 }
10816
Amith Yamasani742a6712011-05-04 14:49:28 -070010817 if (DEBUG_SERVICE)
10818 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 synchronized(this) {
10820 final int callingPid = Binder.getCallingPid();
10821 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010822 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010823 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010824 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010825 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 Binder.restoreCallingIdentity(origId);
10827 return res;
10828 }
10829 }
10830
10831 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010832 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010834 if (DEBUG_SERVICE)
10835 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010837 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010838 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010839 Binder.restoreCallingIdentity(origId);
10840 return res;
10841 }
10842 }
10843
10844 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010845 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010846 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 // Refuse possible leaked file descriptors
10848 if (service != null && service.hasFileDescriptors() == true) {
10849 throw new IllegalArgumentException("File descriptors passed in Intent");
10850 }
10851
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010852 checkValidCaller(Binder.getCallingUid(), userId);
10853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010855 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 }
10858
10859 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010860 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010861 // Refuse possible leaked file descriptors
10862 if (service != null && service.hasFileDescriptors() == true) {
10863 throw new IllegalArgumentException("File descriptors passed in Intent");
10864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010866 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 }
10869
10870 public boolean stopServiceToken(ComponentName className, IBinder token,
10871 int startId) {
10872 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010873 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 }
10876
10877 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010878 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010879 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010880 mServices.setServiceForegroundLocked(className, token, id, notification,
10881 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 }
10883 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010884
Dianne Hackborn41203752012-08-31 14:05:51 -070010885 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10886 boolean requireFull, String name, String callerPackage) {
10887 synchronized(this) {
10888 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10889 requireFull, name, callerPackage);
10890 }
10891 }
10892
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010893 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10894 boolean requireFull, String name, String callerPackage) {
10895 final int callingUserId = UserHandle.getUserId(callingUid);
10896 if (callingUserId != userId) {
10897 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10898 if ((requireFull || checkComponentPermission(
10899 android.Manifest.permission.INTERACT_ACROSS_USERS,
10900 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10901 && checkComponentPermission(
10902 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10903 callingPid, callingUid, -1, true)
10904 != PackageManager.PERMISSION_GRANTED) {
10905 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10906 // In this case, they would like to just execute as their
10907 // owner user instead of failing.
10908 userId = callingUserId;
10909 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010910 StringBuilder builder = new StringBuilder(128);
10911 builder.append("Permission Denial: ");
10912 builder.append(name);
10913 if (callerPackage != null) {
10914 builder.append(" from ");
10915 builder.append(callerPackage);
10916 }
10917 builder.append(" asks to run as user ");
10918 builder.append(userId);
10919 builder.append(" but is calling from user ");
10920 builder.append(UserHandle.getUserId(callingUid));
10921 builder.append("; this requires ");
10922 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10923 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010924 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010925 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10926 }
10927 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010928 Slog.w(TAG, msg);
10929 throw new SecurityException(msg);
10930 }
10931 }
10932 }
10933 if (userId == UserHandle.USER_CURRENT
10934 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10935 userId = mCurrentUserId;
10936 }
10937 if (!allowAll && userId < 0) {
10938 throw new IllegalArgumentException(
10939 "Call does not support special user #" + userId);
10940 }
10941 }
10942 return userId;
10943 }
10944
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010945 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10946 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010947 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010948 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010949 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10950 if (ActivityManager.checkUidPermission(
10951 android.Manifest.permission.INTERACT_ACROSS_USERS,
10952 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10953 ComponentName comp = new ComponentName(aInfo.packageName, className);
10954 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10955 + " requests FLAG_SINGLE_USER, but app does not hold "
10956 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10957 Slog.w(TAG, msg);
10958 throw new SecurityException(msg);
10959 }
10960 result = true;
10961 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010962 } else if (componentProcessName == aInfo.packageName) {
10963 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10964 } else if ("system".equals(componentProcessName)) {
10965 result = true;
10966 }
10967 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010968 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10969 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010970 }
10971 return result;
10972 }
10973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010974 public int bindService(IApplicationThread caller, IBinder token,
10975 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010976 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010977 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010978 // Refuse possible leaked file descriptors
10979 if (service != null && service.hasFileDescriptors() == true) {
10980 throw new IllegalArgumentException("File descriptors passed in Intent");
10981 }
10982
10983 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010984 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10985 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 }
10987 }
10988
10989 public boolean unbindService(IServiceConnection connection) {
10990 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010991 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010993 }
10994
10995 public void publishService(IBinder token, Intent intent, IBinder service) {
10996 // Refuse possible leaked file descriptors
10997 if (intent != null && intent.hasFileDescriptors() == true) {
10998 throw new IllegalArgumentException("File descriptors passed in Intent");
10999 }
11000
11001 synchronized(this) {
11002 if (!(token instanceof ServiceRecord)) {
11003 throw new IllegalArgumentException("Invalid service token");
11004 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011005 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011006 }
11007 }
11008
11009 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11010 // Refuse possible leaked file descriptors
11011 if (intent != null && intent.hasFileDescriptors() == true) {
11012 throw new IllegalArgumentException("File descriptors passed in Intent");
11013 }
11014
11015 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011016 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017 }
11018 }
11019
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011020 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 synchronized(this) {
11022 if (!(token instanceof ServiceRecord)) {
11023 throw new IllegalArgumentException("Invalid service token");
11024 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011025 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 }
11028
11029 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011030 // BACKUP AND RESTORE
11031 // =========================================================
11032
11033 // Cause the target app to be launched if necessary and its backup agent
11034 // instantiated. The backup agent will invoke backupAgentCreated() on the
11035 // activity manager to announce its creation.
11036 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011037 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011038 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11039
11040 synchronized(this) {
11041 // !!! TODO: currently no check here that we're already bound
11042 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11043 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11044 synchronized (stats) {
11045 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11046 }
11047
Dianne Hackborne7f97212011-02-24 14:40:20 -080011048 // Backup agent is now in use, its package can't be stopped.
11049 try {
11050 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011051 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011052 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011053 } catch (IllegalArgumentException e) {
11054 Slog.w(TAG, "Failed trying to unstop package "
11055 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011056 }
11057
Christopher Tate181fafa2009-05-14 11:12:14 -070011058 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011059 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11060 ? new ComponentName(app.packageName, app.backupAgentName)
11061 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011062 // startProcessLocked() returns existing proc's record if it's already running
11063 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011064 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011065 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011066 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011067 return false;
11068 }
11069
11070 r.app = proc;
11071 mBackupTarget = r;
11072 mBackupAppName = app.packageName;
11073
Christopher Tate6fa95972009-06-05 18:43:55 -070011074 // Try not to kill the process during backup
11075 updateOomAdjLocked(proc);
11076
Christopher Tate181fafa2009-05-14 11:12:14 -070011077 // If the process is already attached, schedule the creation of the backup agent now.
11078 // If it is not yet live, this will be done when it attaches to the framework.
11079 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011080 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011081 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011082 proc.thread.scheduleCreateBackupAgent(app,
11083 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011084 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011085 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011086 }
11087 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011088 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011089 }
11090 // Invariants: at this point, the target app process exists and the application
11091 // is either already running or in the process of coming up. mBackupTarget and
11092 // mBackupAppName describe the app, so that when it binds back to the AM we
11093 // know that it's scheduled for a backup-agent operation.
11094 }
11095
11096 return true;
11097 }
11098
11099 // A backup agent has just come up
11100 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011101 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011102 + " = " + agent);
11103
11104 synchronized(this) {
11105 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011106 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011107 return;
11108 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011109 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011110
Dianne Hackborn06740692010-09-22 22:46:21 -070011111 long oldIdent = Binder.clearCallingIdentity();
11112 try {
11113 IBackupManager bm = IBackupManager.Stub.asInterface(
11114 ServiceManager.getService(Context.BACKUP_SERVICE));
11115 bm.agentConnected(agentPackageName, agent);
11116 } catch (RemoteException e) {
11117 // can't happen; the backup manager service is local
11118 } catch (Exception e) {
11119 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11120 e.printStackTrace();
11121 } finally {
11122 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011123 }
11124 }
11125
11126 // done with this agent
11127 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011128 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011129 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011130 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011131 return;
11132 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011133
11134 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011135 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011136 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011137 return;
11138 }
11139
Christopher Tate181fafa2009-05-14 11:12:14 -070011140 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011141 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011142 return;
11143 }
11144
Christopher Tate6fa95972009-06-05 18:43:55 -070011145 ProcessRecord proc = mBackupTarget.app;
11146 mBackupTarget = null;
11147 mBackupAppName = null;
11148
11149 // Not backing this app up any more; reset its OOM adjustment
11150 updateOomAdjLocked(proc);
11151
Christopher Tatec7b31e32009-06-10 15:49:30 -070011152 // If the app crashed during backup, 'thread' will be null here
11153 if (proc.thread != null) {
11154 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011155 proc.thread.scheduleDestroyBackupAgent(appInfo,
11156 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011157 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011158 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011159 e.printStackTrace();
11160 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011161 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011162 }
11163 }
11164 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 // BROADCASTS
11166 // =========================================================
11167
Josh Bartel7f208742010-02-25 11:01:44 -060011168 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011169 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011170 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011171 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11172 if (stickies == null) {
11173 return cur;
11174 }
11175 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011176 if (list == null) {
11177 return cur;
11178 }
11179 int N = list.size();
11180 for (int i=0; i<N; i++) {
11181 Intent intent = list.get(i);
11182 if (filter.match(resolver, intent, true, TAG) >= 0) {
11183 if (cur == null) {
11184 cur = new ArrayList<Intent>();
11185 }
11186 cur.add(intent);
11187 }
11188 }
11189 return cur;
11190 }
11191
Christopher Tatef46723b2012-01-26 14:19:24 -080011192 boolean isPendingBroadcastProcessLocked(int pid) {
11193 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11194 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196
Christopher Tatef46723b2012-01-26 14:19:24 -080011197 void skipPendingBroadcastLocked(int pid) {
11198 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11199 for (BroadcastQueue queue : mBroadcastQueues) {
11200 queue.skipPendingBroadcastLocked(pid);
11201 }
11202 }
11203
11204 // The app just attached; send any pending broadcasts that it should receive
11205 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11206 boolean didSomething = false;
11207 for (BroadcastQueue queue : mBroadcastQueues) {
11208 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011210 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 }
11212
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011213 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011214 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011215 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011216 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011217 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011218 synchronized(this) {
11219 ProcessRecord callerApp = null;
11220 if (caller != null) {
11221 callerApp = getRecordForAppLocked(caller);
11222 if (callerApp == null) {
11223 throw new SecurityException(
11224 "Unable to find app for caller " + caller
11225 + " (pid=" + Binder.getCallingPid()
11226 + ") when registering receiver " + receiver);
11227 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011228 if (callerApp.info.uid != Process.SYSTEM_UID &&
11229 !callerApp.pkgList.contains(callerPackage)) {
11230 throw new SecurityException("Given caller package " + callerPackage
11231 + " is not running in process " + callerApp);
11232 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011233 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011234 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011235 } else {
11236 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011237 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011238 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 }
11240
Dianne Hackborn20e80982012-08-31 19:00:44 -070011241 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11242 true, true, "registerReceiver", callerPackage);
11243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011244 List allSticky = null;
11245
11246 // Look for any matching sticky broadcasts...
11247 Iterator actions = filter.actionsIterator();
11248 if (actions != null) {
11249 while (actions.hasNext()) {
11250 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011251 allSticky = getStickiesLocked(action, filter, allSticky,
11252 UserHandle.USER_ALL);
11253 allSticky = getStickiesLocked(action, filter, allSticky,
11254 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011255 }
11256 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011257 allSticky = getStickiesLocked(null, filter, allSticky,
11258 UserHandle.USER_ALL);
11259 allSticky = getStickiesLocked(null, filter, allSticky,
11260 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 }
11262
11263 // The first sticky in the list is returned directly back to
11264 // the client.
11265 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11266
Joe Onorato8a9b2202010-02-26 18:56:32 -080011267 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011268 + ": " + sticky);
11269
11270 if (receiver == null) {
11271 return sticky;
11272 }
11273
11274 ReceiverList rl
11275 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11276 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011277 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11278 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011279 if (rl.app != null) {
11280 rl.app.receivers.add(rl);
11281 } else {
11282 try {
11283 receiver.asBinder().linkToDeath(rl, 0);
11284 } catch (RemoteException e) {
11285 return sticky;
11286 }
11287 rl.linkedToDeath = true;
11288 }
11289 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011290 } else if (rl.uid != callingUid) {
11291 throw new IllegalArgumentException(
11292 "Receiver requested to register for uid " + callingUid
11293 + " was previously registered for uid " + rl.uid);
11294 } else if (rl.pid != callingPid) {
11295 throw new IllegalArgumentException(
11296 "Receiver requested to register for pid " + callingPid
11297 + " was previously registered for pid " + rl.pid);
11298 } else if (rl.userId != userId) {
11299 throw new IllegalArgumentException(
11300 "Receiver requested to register for user " + userId
11301 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011302 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011303 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011304 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 rl.add(bf);
11306 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011307 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011308 }
11309 mReceiverResolver.addFilter(bf);
11310
11311 // Enqueue broadcasts for all existing stickies that match
11312 // this filter.
11313 if (allSticky != null) {
11314 ArrayList receivers = new ArrayList();
11315 receivers.add(bf);
11316
11317 int N = allSticky.size();
11318 for (int i=0; i<N; i++) {
11319 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011320 BroadcastQueue queue = broadcastQueueForIntent(intent);
11321 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011323 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011324 queue.enqueueParallelBroadcastLocked(r);
11325 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 }
11327 }
11328
11329 return sticky;
11330 }
11331 }
11332
11333 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011334 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011335
Christopher Tatef46723b2012-01-26 14:19:24 -080011336 final long origId = Binder.clearCallingIdentity();
11337 try {
11338 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011339
Christopher Tatef46723b2012-01-26 14:19:24 -080011340 synchronized(this) {
11341 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011343 if (rl != null) {
11344 if (rl.curBroadcast != null) {
11345 BroadcastRecord r = rl.curBroadcast;
11346 final boolean doNext = finishReceiverLocked(
11347 receiver.asBinder(), r.resultCode, r.resultData,
11348 r.resultExtras, r.resultAbort, true);
11349 if (doNext) {
11350 doTrim = true;
11351 r.queue.processNextBroadcast(false);
11352 }
11353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354
Christopher Tatef46723b2012-01-26 14:19:24 -080011355 if (rl.app != null) {
11356 rl.app.receivers.remove(rl);
11357 }
11358 removeReceiverLocked(rl);
11359 if (rl.linkedToDeath) {
11360 rl.linkedToDeath = false;
11361 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011363 }
11364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365
Christopher Tatef46723b2012-01-26 14:19:24 -080011366 // If we actually concluded any broadcasts, we might now be able
11367 // to trim the recipients' apps from our working set
11368 if (doTrim) {
11369 trimApplications();
11370 return;
11371 }
11372
11373 } finally {
11374 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 }
11377
11378 void removeReceiverLocked(ReceiverList rl) {
11379 mRegisteredReceivers.remove(rl.receiver.asBinder());
11380 int N = rl.size();
11381 for (int i=0; i<N; i++) {
11382 mReceiverResolver.removeFilter(rl.get(i));
11383 }
11384 }
11385
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011386 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011387 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11388 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011389 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011390 try {
11391 r.thread.dispatchPackageBroadcast(cmd, packages);
11392 } catch (RemoteException ex) {
11393 }
11394 }
11395 }
11396 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011397
11398 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11399 int[] users) {
11400 List<ResolveInfo> receivers = null;
11401 try {
11402 HashSet<ComponentName> singleUserReceivers = null;
11403 boolean scannedFirstReceivers = false;
11404 for (int user : users) {
11405 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11406 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11407 if (newReceivers != null && newReceivers.size() == 0) {
11408 newReceivers = null;
11409 }
11410 if (receivers == null) {
11411 receivers = newReceivers;
11412 } else if (newReceivers != null) {
11413 // We need to concatenate the additional receivers
11414 // found with what we have do far. This would be easy,
11415 // but we also need to de-dup any receivers that are
11416 // singleUser.
11417 if (!scannedFirstReceivers) {
11418 // Collect any single user receivers we had already retrieved.
11419 scannedFirstReceivers = true;
11420 for (int i=0; i<receivers.size(); i++) {
11421 ResolveInfo ri = receivers.get(i);
11422 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11423 ComponentName cn = new ComponentName(
11424 ri.activityInfo.packageName, ri.activityInfo.name);
11425 if (singleUserReceivers == null) {
11426 singleUserReceivers = new HashSet<ComponentName>();
11427 }
11428 singleUserReceivers.add(cn);
11429 }
11430 }
11431 }
11432 // Add the new results to the existing results, tracking
11433 // and de-dupping single user receivers.
11434 for (int i=0; i<newReceivers.size(); i++) {
11435 ResolveInfo ri = receivers.get(i);
11436 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11437 ComponentName cn = new ComponentName(
11438 ri.activityInfo.packageName, ri.activityInfo.name);
11439 if (singleUserReceivers == null) {
11440 singleUserReceivers = new HashSet<ComponentName>();
11441 }
11442 if (!singleUserReceivers.contains(cn)) {
11443 singleUserReceivers.add(cn);
11444 receivers.add(ri);
11445 }
11446 } else {
11447 receivers.add(ri);
11448 }
11449 }
11450 }
11451 }
11452 } catch (RemoteException ex) {
11453 // pm is in same process, this will never happen.
11454 }
11455 return receivers;
11456 }
11457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 private final int broadcastIntentLocked(ProcessRecord callerApp,
11459 String callerPackage, Intent intent, String resolvedType,
11460 IIntentReceiver resultTo, int resultCode, String resultData,
11461 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011462 boolean ordered, boolean sticky, int callingPid, int callingUid,
11463 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464 intent = new Intent(intent);
11465
Dianne Hackborne7f97212011-02-24 14:40:20 -080011466 // By default broadcasts do not go to stopped apps.
11467 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11468
Joe Onorato8a9b2202010-02-26 18:56:32 -080011469 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011471 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011472 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011473 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011475
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011476 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11477 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011478
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011479 // Make sure that the user who is receiving this broadcast is started
11480 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011481 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011482 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11483 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11484 Slog.w(TAG, "Skipping broadcast of " + intent
11485 + ": user " + userId + " is stopped");
11486 return ActivityManager.BROADCAST_SUCCESS;
11487 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011488 }
11489
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011490 /*
11491 * Prevent non-system code (defined here to be non-persistent
11492 * processes) from sending protected broadcasts.
11493 */
11494 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11495 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11496 callingUid == 0) {
11497 // Always okay.
11498 } else if (callerApp == null || !callerApp.persistent) {
11499 try {
11500 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11501 intent.getAction())) {
11502 String msg = "Permission Denial: not allowed to send broadcast "
11503 + intent.getAction() + " from pid="
11504 + callingPid + ", uid=" + callingUid;
11505 Slog.w(TAG, msg);
11506 throw new SecurityException(msg);
11507 }
11508 } catch (RemoteException e) {
11509 Slog.w(TAG, "Remote exception", e);
11510 return ActivityManager.BROADCAST_SUCCESS;
11511 }
11512 }
11513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011514 // Handle special intents: if this broadcast is from the package
11515 // manager about a package being removed, we need to remove all of
11516 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011517 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011519 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11520 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011521 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 || uidRemoved) {
11523 if (checkComponentPermission(
11524 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011525 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 == PackageManager.PERMISSION_GRANTED) {
11527 if (uidRemoved) {
11528 final Bundle intentExtras = intent.getExtras();
11529 final int uid = intentExtras != null
11530 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11531 if (uid >= 0) {
11532 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11533 synchronized (bs) {
11534 bs.removeUidStatsLocked(uid);
11535 }
11536 }
11537 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011538 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011539 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011540 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011541 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11542 if (list != null && (list.length > 0)) {
11543 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011544 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011545 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011546 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011547 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011548 }
11549 } else {
11550 Uri data = intent.getData();
11551 String ssp;
11552 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11553 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11554 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011555 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11556 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011557 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011558 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011559 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011560 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 }
11563 }
11564 }
11565 } else {
11566 String msg = "Permission Denial: " + intent.getAction()
11567 + " broadcast from " + callerPackage + " (pid=" + callingPid
11568 + ", uid=" + callingUid + ")"
11569 + " requires "
11570 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011571 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011572 throw new SecurityException(msg);
11573 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011574
11575 // Special case for adding a package: by default turn on compatibility
11576 // mode.
11577 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011578 Uri data = intent.getData();
11579 String ssp;
11580 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11581 mCompatModePackages.handlePackageAddedLocked(ssp,
11582 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011584 }
11585
11586 /*
11587 * If this is the time zone changed action, queue up a message that will reset the timezone
11588 * of all currently running processes. This message will get queued up before the broadcast
11589 * happens.
11590 */
11591 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11592 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11593 }
11594
Robert Greenwalt03595d02010-11-02 14:08:23 -070011595 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11596 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11597 }
11598
Robert Greenwalt434203a2010-10-11 16:00:27 -070011599 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11600 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11601 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11602 }
11603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604 // Add to the sticky list if requested.
11605 if (sticky) {
11606 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11607 callingPid, callingUid)
11608 != PackageManager.PERMISSION_GRANTED) {
11609 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11610 + callingPid + ", uid=" + callingUid
11611 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011612 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011613 throw new SecurityException(msg);
11614 }
11615 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011616 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011618 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 }
11620 if (intent.getComponent() != null) {
11621 throw new SecurityException(
11622 "Sticky broadcasts can't target a specific component");
11623 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011624 // We use userId directly here, since the "all" target is maintained
11625 // as a separate set of sticky broadcasts.
11626 if (userId != UserHandle.USER_ALL) {
11627 // But first, if this is not a broadcast to all users, then
11628 // make sure it doesn't conflict with an existing broadcast to
11629 // all users.
11630 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11631 UserHandle.USER_ALL);
11632 if (stickies != null) {
11633 ArrayList<Intent> list = stickies.get(intent.getAction());
11634 if (list != null) {
11635 int N = list.size();
11636 int i;
11637 for (i=0; i<N; i++) {
11638 if (intent.filterEquals(list.get(i))) {
11639 throw new IllegalArgumentException(
11640 "Sticky broadcast " + intent + " for user "
11641 + userId + " conflicts with existing global broadcast");
11642 }
11643 }
11644 }
11645 }
11646 }
11647 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11648 if (stickies == null) {
11649 stickies = new HashMap<String, ArrayList<Intent>>();
11650 mStickyBroadcasts.put(userId, stickies);
11651 }
11652 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 if (list == null) {
11654 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011655 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011656 }
11657 int N = list.size();
11658 int i;
11659 for (i=0; i<N; i++) {
11660 if (intent.filterEquals(list.get(i))) {
11661 // This sticky already exists, replace it.
11662 list.set(i, new Intent(intent));
11663 break;
11664 }
11665 }
11666 if (i >= N) {
11667 list.add(new Intent(intent));
11668 }
11669 }
11670
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011671 int[] users;
11672 if (userId == UserHandle.USER_ALL) {
11673 // Caller wants broadcast to go to all started users.
11674 users = new int[mStartedUsers.size()];
11675 for (int i=0; i<mStartedUsers.size(); i++) {
11676 users[i] = mStartedUsers.keyAt(i);
11677 }
11678 } else {
11679 // Caller wants broadcast to go to one specific user.
11680 users = new int[] {userId};
11681 }
11682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011683 // Figure out who all will receive this broadcast.
11684 List receivers = null;
11685 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011686 // Need to resolve the intent to interested receivers...
11687 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11688 == 0) {
11689 receivers = collectReceiverComponents(intent, resolvedType, users);
11690 }
11691 if (intent.getComponent() == null) {
11692 registeredReceivers = mReceiverResolver.queryIntent(intent,
11693 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011694 }
11695
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011696 final boolean replacePending =
11697 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11698
Joe Onorato8a9b2202010-02-26 18:56:32 -080011699 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011700 + " replacePending=" + replacePending);
11701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011702 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11703 if (!ordered && NR > 0) {
11704 // If we are not serializing this broadcast, then send the
11705 // registered receivers separately so they don't wait for the
11706 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011707 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11708 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709 callerPackage, callingPid, callingUid, requiredPermission,
11710 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011711 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011712 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011713 TAG, "Enqueueing parallel broadcast " + r);
11714 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011715 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011716 queue.enqueueParallelBroadcastLocked(r);
11717 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 registeredReceivers = null;
11720 NR = 0;
11721 }
11722
11723 // Merge into one list.
11724 int ir = 0;
11725 if (receivers != null) {
11726 // A special case for PACKAGE_ADDED: do not allow the package
11727 // being added to see this broadcast. This prevents them from
11728 // using this as a back door to get run as soon as they are
11729 // installed. Maybe in the future we want to have a special install
11730 // broadcast or such for apps, but we'd like to deliberately make
11731 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011732 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011733 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11734 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11735 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011736 Uri data = intent.getData();
11737 if (data != null) {
11738 String pkgName = data.getSchemeSpecificPart();
11739 if (pkgName != null) {
11740 skipPackages = new String[] { pkgName };
11741 }
11742 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011743 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011744 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011745 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011746 if (skipPackages != null && (skipPackages.length > 0)) {
11747 for (String skipPackage : skipPackages) {
11748 if (skipPackage != null) {
11749 int NT = receivers.size();
11750 for (int it=0; it<NT; it++) {
11751 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11752 if (curt.activityInfo.packageName.equals(skipPackage)) {
11753 receivers.remove(it);
11754 it--;
11755 NT--;
11756 }
11757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758 }
11759 }
11760 }
11761
11762 int NT = receivers != null ? receivers.size() : 0;
11763 int it = 0;
11764 ResolveInfo curt = null;
11765 BroadcastFilter curr = null;
11766 while (it < NT && ir < NR) {
11767 if (curt == null) {
11768 curt = (ResolveInfo)receivers.get(it);
11769 }
11770 if (curr == null) {
11771 curr = registeredReceivers.get(ir);
11772 }
11773 if (curr.getPriority() >= curt.priority) {
11774 // Insert this broadcast record into the final list.
11775 receivers.add(it, curr);
11776 ir++;
11777 curr = null;
11778 it++;
11779 NT++;
11780 } else {
11781 // Skip to the next ResolveInfo in the final list.
11782 it++;
11783 curt = null;
11784 }
11785 }
11786 }
11787 while (ir < NR) {
11788 if (receivers == null) {
11789 receivers = new ArrayList();
11790 }
11791 receivers.add(registeredReceivers.get(ir));
11792 ir++;
11793 }
11794
11795 if ((receivers != null && receivers.size() > 0)
11796 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011797 BroadcastQueue queue = broadcastQueueForIntent(intent);
11798 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011800 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011801 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011802 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011804 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 if (DEBUG_BROADCAST) {
11806 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011807 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011809 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011810 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011811 queue.enqueueOrderedBroadcastLocked(r);
11812 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 }
11815
Dianne Hackborna4972e92012-03-14 10:38:05 -070011816 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011817 }
11818
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011819 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 // Refuse possible leaked file descriptors
11821 if (intent != null && intent.hasFileDescriptors() == true) {
11822 throw new IllegalArgumentException("File descriptors passed in Intent");
11823 }
11824
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011825 int flags = intent.getFlags();
11826
11827 if (!mProcessesReady) {
11828 // if the caller really truly claims to know what they're doing, go
11829 // ahead and allow the broadcast without launching any receivers
11830 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11831 intent = new Intent(intent);
11832 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11833 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11834 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11835 + " before boot completion");
11836 throw new IllegalStateException("Cannot broadcast before boot completed");
11837 }
11838 }
11839
11840 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11841 throw new IllegalArgumentException(
11842 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11843 }
11844
11845 return intent;
11846 }
11847
11848 public final int broadcastIntent(IApplicationThread caller,
11849 Intent intent, String resolvedType, IIntentReceiver resultTo,
11850 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011851 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011852 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011854 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11857 final int callingPid = Binder.getCallingPid();
11858 final int callingUid = Binder.getCallingUid();
11859 final long origId = Binder.clearCallingIdentity();
11860 int res = broadcastIntentLocked(callerApp,
11861 callerApp != null ? callerApp.info.packageName : null,
11862 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011863 resultCode, resultData, map, requiredPermission, serialized, sticky,
11864 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011865 Binder.restoreCallingIdentity(origId);
11866 return res;
11867 }
11868 }
11869
11870 int broadcastIntentInPackage(String packageName, int uid,
11871 Intent intent, String resolvedType, IIntentReceiver resultTo,
11872 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011873 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011875 intent = verifyBroadcastLocked(intent);
11876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 final long origId = Binder.clearCallingIdentity();
11878 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11879 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011880 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881 Binder.restoreCallingIdentity(origId);
11882 return res;
11883 }
11884 }
11885
Amith Yamasani742a6712011-05-04 14:49:28 -070011886 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011887 // Refuse possible leaked file descriptors
11888 if (intent != null && intent.hasFileDescriptors() == true) {
11889 throw new IllegalArgumentException("File descriptors passed in Intent");
11890 }
11891
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011892 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11893 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011895 synchronized(this) {
11896 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11897 != PackageManager.PERMISSION_GRANTED) {
11898 String msg = "Permission Denial: unbroadcastIntent() from pid="
11899 + Binder.getCallingPid()
11900 + ", uid=" + Binder.getCallingUid()
11901 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011902 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011903 throw new SecurityException(msg);
11904 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011905 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11906 if (stickies != null) {
11907 ArrayList<Intent> list = stickies.get(intent.getAction());
11908 if (list != null) {
11909 int N = list.size();
11910 int i;
11911 for (i=0; i<N; i++) {
11912 if (intent.filterEquals(list.get(i))) {
11913 list.remove(i);
11914 break;
11915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011916 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011917 if (list.size() <= 0) {
11918 stickies.remove(intent.getAction());
11919 }
11920 }
11921 if (stickies.size() <= 0) {
11922 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 }
11924 }
11925 }
11926 }
11927
11928 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11929 String resultData, Bundle resultExtras, boolean resultAbort,
11930 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011931 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11932 if (r == null) {
11933 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011934 return false;
11935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936
Christopher Tatef46723b2012-01-26 14:19:24 -080011937 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11938 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 }
11940
11941 public void finishReceiver(IBinder who, int resultCode, String resultData,
11942 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011943 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944
11945 // Refuse possible leaked file descriptors
11946 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11947 throw new IllegalArgumentException("File descriptors passed in Bundle");
11948 }
11949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011950 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011951 try {
11952 boolean doNext = false;
11953 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011954
Christopher Tatef46723b2012-01-26 14:19:24 -080011955 synchronized(this) {
11956 r = broadcastRecordForReceiverLocked(who);
11957 if (r != null) {
11958 doNext = r.queue.finishReceiverLocked(r, resultCode,
11959 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011962
Christopher Tatef46723b2012-01-26 14:19:24 -080011963 if (doNext) {
11964 r.queue.processNextBroadcast(false);
11965 }
11966 trimApplications();
11967 } finally {
11968 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972 // =========================================================
11973 // INSTRUMENTATION
11974 // =========================================================
11975
11976 public boolean startInstrumentation(ComponentName className,
11977 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011978 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011979 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011980 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
11981 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 // Refuse possible leaked file descriptors
11983 if (arguments != null && arguments.hasFileDescriptors()) {
11984 throw new IllegalArgumentException("File descriptors passed in Bundle");
11985 }
11986
11987 synchronized(this) {
11988 InstrumentationInfo ii = null;
11989 ApplicationInfo ai = null;
11990 try {
11991 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011992 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011993 ai = AppGlobals.getPackageManager().getApplicationInfo(
11994 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011995 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011996 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 }
11998 if (ii == null) {
11999 reportStartInstrumentationFailure(watcher, className,
12000 "Unable to find instrumentation info for: " + className);
12001 return false;
12002 }
12003 if (ai == null) {
12004 reportStartInstrumentationFailure(watcher, className,
12005 "Unable to find instrumentation target package: " + ii.targetPackage);
12006 return false;
12007 }
12008
12009 int match = mContext.getPackageManager().checkSignatures(
12010 ii.targetPackage, ii.packageName);
12011 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12012 String msg = "Permission Denial: starting instrumentation "
12013 + className + " from pid="
12014 + Binder.getCallingPid()
12015 + ", uid=" + Binder.getCallingPid()
12016 + " not allowed because package " + ii.packageName
12017 + " does not have a signature matching the target "
12018 + ii.targetPackage;
12019 reportStartInstrumentationFailure(watcher, className, msg);
12020 throw new SecurityException(msg);
12021 }
12022
12023 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012024 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012025 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012026 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012028 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029 app.instrumentationProfileFile = profileFile;
12030 app.instrumentationArguments = arguments;
12031 app.instrumentationWatcher = watcher;
12032 app.instrumentationResultClass = className;
12033 Binder.restoreCallingIdentity(origId);
12034 }
12035
12036 return true;
12037 }
12038
12039 /**
12040 * Report errors that occur while attempting to start Instrumentation. Always writes the
12041 * error to the logs, but if somebody is watching, send the report there too. This enables
12042 * the "am" command to report errors with more information.
12043 *
12044 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12045 * @param cn The component name of the instrumentation.
12046 * @param report The error report.
12047 */
12048 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12049 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012050 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012051 try {
12052 if (watcher != null) {
12053 Bundle results = new Bundle();
12054 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12055 results.putString("Error", report);
12056 watcher.instrumentationStatus(cn, -1, results);
12057 }
12058 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012059 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012060 }
12061 }
12062
12063 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12064 if (app.instrumentationWatcher != null) {
12065 try {
12066 // NOTE: IInstrumentationWatcher *must* be oneway here
12067 app.instrumentationWatcher.instrumentationFinished(
12068 app.instrumentationClass,
12069 resultCode,
12070 results);
12071 } catch (RemoteException e) {
12072 }
12073 }
12074 app.instrumentationWatcher = null;
12075 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012076 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012077 app.instrumentationProfileFile = null;
12078 app.instrumentationArguments = null;
12079
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012080 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012081 }
12082
12083 public void finishInstrumentation(IApplicationThread target,
12084 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012085 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012086 // Refuse possible leaked file descriptors
12087 if (results != null && results.hasFileDescriptors()) {
12088 throw new IllegalArgumentException("File descriptors passed in Intent");
12089 }
12090
12091 synchronized(this) {
12092 ProcessRecord app = getRecordForAppLocked(target);
12093 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012094 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 return;
12096 }
12097 final long origId = Binder.clearCallingIdentity();
12098 finishInstrumentationLocked(app, resultCode, results);
12099 Binder.restoreCallingIdentity(origId);
12100 }
12101 }
12102
12103 // =========================================================
12104 // CONFIGURATION
12105 // =========================================================
12106
12107 public ConfigurationInfo getDeviceConfigurationInfo() {
12108 ConfigurationInfo config = new ConfigurationInfo();
12109 synchronized (this) {
12110 config.reqTouchScreen = mConfiguration.touchscreen;
12111 config.reqKeyboardType = mConfiguration.keyboard;
12112 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012113 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12114 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12116 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012117 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12118 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012119 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12120 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012121 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 }
12123 return config;
12124 }
12125
12126 public Configuration getConfiguration() {
12127 Configuration ci;
12128 synchronized(this) {
12129 ci = new Configuration(mConfiguration);
12130 }
12131 return ci;
12132 }
12133
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012134 public void updatePersistentConfiguration(Configuration values) {
12135 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12136 "updateConfiguration()");
12137 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12138 "updateConfiguration()");
12139 if (values == null) {
12140 throw new NullPointerException("Configuration must not be null");
12141 }
12142
12143 synchronized(this) {
12144 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012145 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012146 Binder.restoreCallingIdentity(origId);
12147 }
12148 }
12149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012150 public void updateConfiguration(Configuration values) {
12151 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12152 "updateConfiguration()");
12153
12154 synchronized(this) {
12155 if (values == null && mWindowManager != null) {
12156 // sentinel: fetch the current configuration from the window manager
12157 values = mWindowManager.computeNewConfiguration();
12158 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012159
12160 if (mWindowManager != null) {
12161 mProcessList.applyDisplaySize(mWindowManager);
12162 }
12163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012164 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012165 if (values != null) {
12166 Settings.System.clearConfiguration(values);
12167 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012168 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 Binder.restoreCallingIdentity(origId);
12170 }
12171 }
12172
12173 /**
12174 * Do either or both things: (1) change the current configuration, and (2)
12175 * make sure the given activity is running with the (now) current
12176 * configuration. Returns true if the activity has been left running, or
12177 * false if <var>starting</var> is being destroyed to match the new
12178 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012179 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012180 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012181 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012182 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012183 // do nothing if we are headless
12184 if (mHeadless) return true;
12185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 int changes = 0;
12187
12188 boolean kept = true;
12189
12190 if (values != null) {
12191 Configuration newConfig = new Configuration(mConfiguration);
12192 changes = newConfig.updateFrom(values);
12193 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012194 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012195 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196 }
12197
Doug Zongker2bec3d42009-12-04 12:52:44 -080012198 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012199
Dianne Hackborn813075a62011-11-14 17:45:19 -080012200 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012201 saveLocaleLocked(values.locale,
12202 !values.locale.equals(mConfiguration.locale),
12203 values.userSetLocale);
12204 }
12205
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012206 mConfigurationSeq++;
12207 if (mConfigurationSeq <= 0) {
12208 mConfigurationSeq = 1;
12209 }
12210 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012211 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012212 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012213
12214 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012215
12216 // TODO: If our config changes, should we auto dismiss any currently
12217 // showing dialogs?
12218 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012219
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012220 AttributeCache ac = AttributeCache.instance();
12221 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012222 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012225 // Make sure all resources in our process are updated
12226 // right now, so that anyone who is going to retrieve
12227 // resource values after we return will be sure to get
12228 // the new ones. This is especially important during
12229 // boot, where the first config change needs to guarantee
12230 // all resources have that config before following boot
12231 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012232 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012233
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012234 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012235 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012236 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012237 mHandler.sendMessage(msg);
12238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012240 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12241 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012242 try {
12243 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012244 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012245 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012246 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012247 }
12248 } catch (Exception e) {
12249 }
12250 }
12251 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012252 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12253 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012254 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012255 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012256 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12257 broadcastIntentLocked(null, null,
12258 new Intent(Intent.ACTION_LOCALE_CHANGED),
12259 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012260 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012262 }
12263 }
12264
12265 if (changes != 0 && starting == null) {
12266 // If the configuration changed, and the caller is not already
12267 // in the process of starting an activity, then find the top
12268 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012269 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012270 }
12271
12272 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012273 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012274 // And we need to make sure at this point that all other activities
12275 // are made visible with the correct configuration.
12276 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012277 }
12278
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012279 if (values != null && mWindowManager != null) {
12280 mWindowManager.setNewConfiguration(mConfiguration);
12281 }
12282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 return kept;
12284 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012285
12286 /**
12287 * Decide based on the configuration whether we should shouw the ANR,
12288 * crash, etc dialogs. The idea is that if there is no affordnace to
12289 * press the on-screen buttons, we shouldn't show the dialog.
12290 *
12291 * A thought: SystemUI might also want to get told about this, the Power
12292 * dialog / global actions also might want different behaviors.
12293 */
12294 private static final boolean shouldShowDialogs(Configuration config) {
12295 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12296 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012298
12299 /**
12300 * Save the locale. You must be inside a synchronized (this) block.
12301 */
12302 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12303 if(isDiff) {
12304 SystemProperties.set("user.language", l.getLanguage());
12305 SystemProperties.set("user.region", l.getCountry());
12306 }
12307
12308 if(isPersist) {
12309 SystemProperties.set("persist.sys.language", l.getLanguage());
12310 SystemProperties.set("persist.sys.country", l.getCountry());
12311 SystemProperties.set("persist.sys.localevar", l.getVariant());
12312 }
12313 }
12314
Adam Powelldd8fab22012-03-22 17:47:27 -070012315 @Override
12316 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12317 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012318 return srec != null && srec.task.affinity != null &&
12319 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012320 }
12321
12322 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12323 Intent resultData) {
12324 ComponentName dest = destIntent.getComponent();
12325
12326 synchronized (this) {
12327 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012328 if (srec == null) {
12329 return false;
12330 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012331 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12332 final int start = history.indexOf(srec);
12333 if (start < 0) {
12334 // Current activity is not in history stack; do nothing.
12335 return false;
12336 }
12337 int finishTo = start - 1;
12338 ActivityRecord parent = null;
12339 boolean foundParentInTask = false;
12340 if (dest != null) {
12341 TaskRecord tr = srec.task;
12342 for (int i = start - 1; i >= 0; i--) {
12343 ActivityRecord r = history.get(i);
12344 if (tr != r.task) {
12345 // Couldn't find parent in the same task; stop at the one above this.
12346 // (Root of current task; in-app "home" behavior)
12347 // Always at least finish the current activity.
12348 finishTo = Math.min(start - 1, i + 1);
12349 parent = history.get(finishTo);
12350 break;
12351 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12352 r.info.name.equals(dest.getClassName())) {
12353 finishTo = i;
12354 parent = r;
12355 foundParentInTask = true;
12356 break;
12357 }
12358 }
12359 }
12360
12361 if (mController != null) {
12362 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12363 if (next != null) {
12364 // ask watcher if this is allowed
12365 boolean resumeOK = true;
12366 try {
12367 resumeOK = mController.activityResuming(next.packageName);
12368 } catch (RemoteException e) {
12369 mController = null;
12370 }
12371
12372 if (!resumeOK) {
12373 return false;
12374 }
12375 }
12376 }
12377 final long origId = Binder.clearCallingIdentity();
12378 for (int i = start; i > finishTo; i--) {
12379 ActivityRecord r = history.get(i);
12380 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012381 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012382 // Only return the supplied result for the first activity finished
12383 resultCode = Activity.RESULT_CANCELED;
12384 resultData = null;
12385 }
12386
12387 if (parent != null && foundParentInTask) {
12388 final int parentLaunchMode = parent.info.launchMode;
12389 final int destIntentFlags = destIntent.getFlags();
12390 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12391 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12392 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12393 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012394 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012395 } else {
12396 try {
12397 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012398 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012399 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12400 null, aInfo, parent.appToken, null,
12401 0, -1, parent.launchedFromUid, 0, null, true, null);
12402 foundParentInTask = res == ActivityManager.START_SUCCESS;
12403 } catch (RemoteException e) {
12404 foundParentInTask = false;
12405 }
12406 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012407 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012408 }
12409 }
12410 Binder.restoreCallingIdentity(origId);
12411 return foundParentInTask;
12412 }
12413 }
12414
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012415 public int getLaunchedFromUid(IBinder activityToken) {
12416 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12417 if (srec == null) {
12418 return -1;
12419 }
12420 return srec.launchedFromUid;
12421 }
12422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 // =========================================================
12424 // LIFETIME MANAGEMENT
12425 // =========================================================
12426
Christopher Tatef46723b2012-01-26 14:19:24 -080012427 // Returns which broadcast queue the app is the current [or imminent] receiver
12428 // on, or 'null' if the app is not an active broadcast recipient.
12429 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12430 BroadcastRecord r = app.curReceiver;
12431 if (r != null) {
12432 return r.queue;
12433 }
12434
12435 // It's not the current receiver, but it might be starting up to become one
12436 synchronized (this) {
12437 for (BroadcastQueue queue : mBroadcastQueues) {
12438 r = queue.mPendingBroadcast;
12439 if (r != null && r.curApp == app) {
12440 // found it; report which queue it's in
12441 return queue;
12442 }
12443 }
12444 }
12445
12446 return null;
12447 }
12448
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012449 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012450 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012452 // This adjustment has already been computed. If we are calling
12453 // from the top, we may have already computed our adjustment with
12454 // an earlier hidden adjustment that isn't really for us... if
12455 // so, use the new hidden adjustment.
12456 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012457 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12458 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012459 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012460 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 }
12462
12463 if (app.thread == null) {
12464 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012465 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012466 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012467 }
12468
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012469 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12470 app.adjSource = null;
12471 app.adjTarget = null;
12472 app.empty = false;
12473 app.hidden = false;
12474
12475 final int activitiesSize = app.activities.size();
12476
Dianne Hackborn7d608422011-08-07 16:24:18 -070012477 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012478 // The max adjustment doesn't allow this app to be anything
12479 // below foreground, so it is not worth doing work for it.
12480 app.adjType = "fixed";
12481 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012482 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012483 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012484 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012485 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012486 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012487 // System process can do UI, and when they do we want to have
12488 // them trim their memory after the user leaves the UI. To
12489 // facilitate this, here we need to determine whether or not it
12490 // is currently showing UI.
12491 app.systemNoUi = true;
12492 if (app == TOP_APP) {
12493 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012494 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012495 } else if (activitiesSize > 0) {
12496 for (int j = 0; j < activitiesSize; j++) {
12497 final ActivityRecord r = app.activities.get(j);
12498 if (r.visible) {
12499 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012500 }
12501 if (r.app == app) {
12502 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012503 }
12504 }
12505 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012506 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012507 }
12508
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012509 app.keeping = false;
12510 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012511 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012512
The Android Open Source Project4df24232009-03-05 14:34:35 -080012513 // Determine the importance of the process, starting with most
12514 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012516 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012517 boolean foregroundActivities = false;
12518 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012519 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012520 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012522 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012523 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012524 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012525 foregroundActivities = true;
12526 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012527 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012528 } else if (app.instrumentationClass != null) {
12529 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012530 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012531 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012532 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012533 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012534 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012536 // counts as being in the foreground for OOM killer purposes.
12537 // It's placed in a sched group based on the nature of the
12538 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012539 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012540 schedGroup = (queue == mFgBroadcastQueue)
12541 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012542 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 } else if (app.executingServices.size() > 0) {
12544 // An app that is currently executing a service callback also
12545 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012546 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012547 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012548 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012549 } else {
12550 // Assume process is hidden (has activities); we will correct
12551 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012552 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012553 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012554 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012555 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012557
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012558 boolean hasStoppingActivities = false;
12559
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012560 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012561 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012562 for (int j = 0; j < activitiesSize; j++) {
12563 final ActivityRecord r = app.activities.get(j);
12564 if (r.visible) {
12565 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012566 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12567 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012568 app.adjType = "visible";
12569 }
12570 schedGroup = Process.THREAD_GROUP_DEFAULT;
12571 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012572 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012573 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012574 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012575 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012576 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12577 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012578 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012579 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012580 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012581 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012582 } else if (r.state == ActivityState.STOPPING) {
12583 // We will apply the actual adjustment later, because
12584 // we want to allow this process to immediately go through
12585 // any memory trimming that is in effect.
12586 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012587 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012588 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012589 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012590 if (r.app == app) {
12591 app.hasActivities = true;
12592 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012593 }
12594 }
12595
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012596 if (adj == hiddenAdj && !app.hasActivities) {
12597 // Whoops, this process is completely empty as far as we know
12598 // at this point.
12599 adj = emptyAdj;
12600 app.empty = true;
12601 app.adjType = "bg-empty";
12602 }
12603
Dianne Hackborn7d608422011-08-07 16:24:18 -070012604 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012605 if (app.foregroundServices) {
12606 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012607 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012608 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012609 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012610 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012611 } else if (app.forcingToForeground != null) {
12612 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012613 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012614 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012615 app.adjType = "force-foreground";
12616 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012617 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012618 }
12619 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012620
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012621 if (app.foregroundServices) {
12622 interesting = true;
12623 }
12624
Dianne Hackborn7d608422011-08-07 16:24:18 -070012625 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012626 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012627 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012628 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012629 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012630 app.adjType = "heavy";
12631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632
Dianne Hackborn7d608422011-08-07 16:24:18 -070012633 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012634 // This process is hosting what we currently consider to be the
12635 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012636 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012637 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012638 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012639 app.adjType = "home";
12640 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012641
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012642 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12643 && app.activities.size() > 0) {
12644 // This was the previous process that showed UI to the user.
12645 // We want to try to keep it around more aggressively, to give
12646 // a good experience around switching between two apps.
12647 adj = ProcessList.PREVIOUS_APP_ADJ;
12648 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12649 app.hidden = false;
12650 app.adjType = "previous";
12651 }
12652
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012653 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12654 + " reason=" + app.adjType);
12655
The Android Open Source Project4df24232009-03-05 14:34:35 -080012656 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012657 // there are applications dependent on our services or providers, but
12658 // this gives us a baseline and makes sure we don't get into an
12659 // infinite recursion.
12660 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012661 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012662
Christopher Tate6fa95972009-06-05 18:43:55 -070012663 if (mBackupTarget != null && app == mBackupTarget.app) {
12664 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012665 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012666 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012667 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012668 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012669 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012670 }
12671 }
12672
Dianne Hackborn7d608422011-08-07 16:24:18 -070012673 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012674 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012675 final long now = SystemClock.uptimeMillis();
12676 // This process is more important if the top activity is
12677 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012678 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012679 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012680 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012682 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012683 // If this process has shown some UI, let it immediately
12684 // go to the LRU list because it may be pretty heavy with
12685 // UI stuff. We'll tag it with a label just to help
12686 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012687 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012688 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012689 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012690 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012691 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012692 // This service has seen some activity within
12693 // recent memory, so we will keep its process ahead
12694 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012695 if (adj > ProcessList.SERVICE_ADJ) {
12696 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012697 app.adjType = "started-services";
12698 app.hidden = false;
12699 }
12700 }
12701 // If we have let the service slide into the background
12702 // state, still have some text describing what it is doing
12703 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012704 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012705 app.adjType = "started-bg-services";
12706 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012707 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012708 // Don't kill this process because it is doing work; it
12709 // has said it is doing work.
12710 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012711 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012712 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012713 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012714 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012715 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012716 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012717 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012718 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012719 // XXX should compute this based on the max of
12720 // all connected clients.
12721 ConnectionRecord cr = clist.get(i);
12722 if (cr.binding.client == app) {
12723 // Binding to ourself is not interesting.
12724 continue;
12725 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012726 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012727 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012728 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012729 int myHiddenAdj = hiddenAdj;
12730 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012731 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012732 myHiddenAdj = client.hiddenAdj;
12733 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012734 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012735 }
12736 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012737 int myEmptyAdj = emptyAdj;
12738 if (myEmptyAdj > client.emptyAdj) {
12739 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12740 myEmptyAdj = client.emptyAdj;
12741 } else {
12742 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12743 }
12744 }
12745 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12746 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012747 String adjType = null;
12748 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12749 // Not doing bind OOM management, so treat
12750 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012751 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012752 // If this process has shown some UI, let it immediately
12753 // go to the LRU list because it may be pretty heavy with
12754 // UI stuff. We'll tag it with a label just to help
12755 // debug and understand what is going on.
12756 if (adj > clientAdj) {
12757 adjType = "bound-bg-ui-services";
12758 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012759 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012760 clientAdj = adj;
12761 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012762 if (now >= (s.lastActivity
12763 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012764 // This service has not seen activity within
12765 // recent memory, so allow it to drop to the
12766 // LRU list if there is no other reason to keep
12767 // it around. We'll also tag it with a label just
12768 // to help debug and undertand what is going on.
12769 if (adj > clientAdj) {
12770 adjType = "bound-bg-services";
12771 }
12772 clientAdj = adj;
12773 }
12774 }
12775 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012776 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012777 // If this process has recently shown UI, and
12778 // the process that is binding to it is less
12779 // important than being visible, then we don't
12780 // care about the binding as much as we care
12781 // about letting this process get into the LRU
12782 // list to be killed and restarted if needed for
12783 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012784 if (app.hasShownUi && app != mHomeProcess
12785 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012786 adjType = "bound-bg-ui-services";
12787 } else {
12788 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12789 |Context.BIND_IMPORTANT)) != 0) {
12790 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012791 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12792 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12793 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12794 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12795 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012796 adj = clientAdj;
12797 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012798 app.pendingUiClean = true;
12799 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12800 adj = ProcessList.VISIBLE_APP_ADJ;
12801 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012802 }
12803 if (!client.hidden) {
12804 app.hidden = false;
12805 }
12806 if (client.keeping) {
12807 app.keeping = true;
12808 }
12809 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012810 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012811 }
12812 if (adjType != null) {
12813 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012814 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12815 .REASON_SERVICE_IN_USE;
12816 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012817 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012818 app.adjTarget = s.name;
12819 }
12820 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12821 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12822 schedGroup = Process.THREAD_GROUP_DEFAULT;
12823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 }
12825 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012826 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12827 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012828 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012829 (a.visible || a.state == ActivityState.RESUMED
12830 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012831 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012832 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12833 schedGroup = Process.THREAD_GROUP_DEFAULT;
12834 }
12835 app.hidden = false;
12836 app.adjType = "service";
12837 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12838 .REASON_SERVICE_IN_USE;
12839 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012840 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012841 app.adjTarget = s.name;
12842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012844 }
12845 }
12846 }
12847 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012848
Dianne Hackborn287952c2010-09-22 22:34:31 -070012849 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012850 // would like to avoid killing it unless it would prevent the current
12851 // application from running. By default we put the process in
12852 // with the rest of the background processes; as we scan through
12853 // its services we may bump it up from there.
12854 if (adj > hiddenAdj) {
12855 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012856 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012857 app.adjType = "bg-services";
12858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859 }
12860
Dianne Hackborn7d608422011-08-07 16:24:18 -070012861 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012862 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012863 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012864 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012865 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012866 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012867 for (int i = cpr.connections.size()-1;
12868 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12869 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12870 i--) {
12871 ContentProviderConnection conn = cpr.connections.get(i);
12872 ProcessRecord client = conn.client;
12873 if (client == app) {
12874 // Being our own client is not interesting.
12875 continue;
12876 }
12877 int myHiddenAdj = hiddenAdj;
12878 if (myHiddenAdj > client.hiddenAdj) {
12879 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12880 myHiddenAdj = client.hiddenAdj;
12881 } else {
12882 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012883 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012884 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012885 int myEmptyAdj = emptyAdj;
12886 if (myEmptyAdj > client.emptyAdj) {
12887 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12888 myEmptyAdj = client.emptyAdj;
12889 } else {
12890 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12891 }
12892 }
12893 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12894 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012895 if (adj > clientAdj) {
12896 if (app.hasShownUi && app != mHomeProcess
12897 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12898 app.adjType = "bg-ui-provider";
12899 } else {
12900 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12901 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12902 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012904 if (!client.hidden) {
12905 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012907 if (client.keeping) {
12908 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012909 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012910 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12911 .REASON_PROVIDER_IN_USE;
12912 app.adjSource = client;
12913 app.adjSourceOom = clientAdj;
12914 app.adjTarget = cpr.name;
12915 }
12916 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12917 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012918 }
12919 }
12920 // If the provider has external (non-framework) process
12921 // dependencies, ensure that its adjustment is at least
12922 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012923 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012924 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12925 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012926 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012927 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012928 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012929 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012930 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 }
12932 }
12933 }
12934 }
12935
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012936 if (adj == ProcessList.SERVICE_ADJ) {
12937 if (doingAll) {
12938 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12939 mNewNumServiceProcs++;
12940 }
12941 if (app.serviceb) {
12942 adj = ProcessList.SERVICE_B_ADJ;
12943 }
12944 } else {
12945 app.serviceb = false;
12946 }
12947
12948 app.nonStoppingAdj = adj;
12949
12950 if (hasStoppingActivities) {
12951 // Only upgrade adjustment.
12952 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12953 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12954 app.adjType = "stopping";
12955 }
12956 }
12957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012958 app.curRawAdj = adj;
12959
Joe Onorato8a9b2202010-02-26 18:56:32 -080012960 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12962 if (adj > app.maxAdj) {
12963 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012964 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012965 schedGroup = Process.THREAD_GROUP_DEFAULT;
12966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012968 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012969 app.keeping = true;
12970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012972 if (app.hasAboveClient) {
12973 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12974 // then we need to drop its adjustment to be lower than the service's
12975 // in order to honor the request. We want to drop it by one adjustment
12976 // level... but there is special meaning applied to various levels so
12977 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012978 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012979 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012980 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12981 adj = ProcessList.VISIBLE_APP_ADJ;
12982 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12983 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12984 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12985 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012986 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012987 adj++;
12988 }
12989 }
12990
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012991 int importance = app.memImportance;
12992 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12993 app.curAdj = adj;
12994 app.curSchedGroup = schedGroup;
12995 if (!interesting) {
12996 // For this reporting, if there is not something explicitly
12997 // interesting in this process then we will push it to the
12998 // background importance.
12999 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13000 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13001 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13002 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13003 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13004 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13005 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13006 } else if (adj >= ProcessList.SERVICE_ADJ) {
13007 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13008 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13009 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13010 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13011 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13012 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13013 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13014 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13015 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13016 } else {
13017 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13018 }
13019 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013020
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013021 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13022 if (foregroundActivities != app.foregroundActivities) {
13023 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13024 }
13025 if (changes != 0) {
13026 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13027 app.memImportance = importance;
13028 app.foregroundActivities = foregroundActivities;
13029 int i = mPendingProcessChanges.size()-1;
13030 ProcessChangeItem item = null;
13031 while (i >= 0) {
13032 item = mPendingProcessChanges.get(i);
13033 if (item.pid == app.pid) {
13034 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13035 break;
13036 }
13037 i--;
13038 }
13039 if (i < 0) {
13040 // No existing item in pending changes; need a new one.
13041 final int NA = mAvailProcessChanges.size();
13042 if (NA > 0) {
13043 item = mAvailProcessChanges.remove(NA-1);
13044 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13045 } else {
13046 item = new ProcessChangeItem();
13047 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13048 }
13049 item.changes = 0;
13050 item.pid = app.pid;
13051 item.uid = app.info.uid;
13052 if (mPendingProcessChanges.size() == 0) {
13053 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13054 "*** Enqueueing dispatch processes changed!");
13055 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13056 }
13057 mPendingProcessChanges.add(item);
13058 }
13059 item.changes |= changes;
13060 item.importance = importance;
13061 item.foregroundActivities = foregroundActivities;
13062 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13063 + Integer.toHexString(System.identityHashCode(item))
13064 + " " + app.toShortString() + ": changes=" + item.changes
13065 + " importance=" + item.importance
13066 + " foreground=" + item.foregroundActivities
13067 + " type=" + app.adjType + " source=" + app.adjSource
13068 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013069 }
13070
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013071 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072 }
13073
13074 /**
13075 * Ask a given process to GC right now.
13076 */
13077 final void performAppGcLocked(ProcessRecord app) {
13078 try {
13079 app.lastRequestedGc = SystemClock.uptimeMillis();
13080 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013081 if (app.reportLowMemory) {
13082 app.reportLowMemory = false;
13083 app.thread.scheduleLowMemory();
13084 } else {
13085 app.thread.processInBackground();
13086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013087 }
13088 } catch (Exception e) {
13089 // whatever.
13090 }
13091 }
13092
13093 /**
13094 * Returns true if things are idle enough to perform GCs.
13095 */
Josh Bartel7f208742010-02-25 11:01:44 -060013096 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013097 boolean processingBroadcasts = false;
13098 for (BroadcastQueue q : mBroadcastQueues) {
13099 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13100 processingBroadcasts = true;
13101 }
13102 }
13103 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013104 && (mSleeping || (mMainStack.mResumedActivity != null &&
13105 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 }
13107
13108 /**
13109 * Perform GCs on all processes that are waiting for it, but only
13110 * if things are idle.
13111 */
13112 final void performAppGcsLocked() {
13113 final int N = mProcessesToGc.size();
13114 if (N <= 0) {
13115 return;
13116 }
Josh Bartel7f208742010-02-25 11:01:44 -060013117 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 while (mProcessesToGc.size() > 0) {
13119 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013120 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013121 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13122 <= SystemClock.uptimeMillis()) {
13123 // To avoid spamming the system, we will GC processes one
13124 // at a time, waiting a few seconds between each.
13125 performAppGcLocked(proc);
13126 scheduleAppGcsLocked();
13127 return;
13128 } else {
13129 // It hasn't been long enough since we last GCed this
13130 // process... put it in the list to wait for its time.
13131 addProcessToGcListLocked(proc);
13132 break;
13133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013134 }
13135 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013136
13137 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013138 }
13139 }
13140
13141 /**
13142 * If all looks good, perform GCs on all processes waiting for them.
13143 */
13144 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013145 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013146 performAppGcsLocked();
13147 return;
13148 }
13149 // Still not idle, wait some more.
13150 scheduleAppGcsLocked();
13151 }
13152
13153 /**
13154 * Schedule the execution of all pending app GCs.
13155 */
13156 final void scheduleAppGcsLocked() {
13157 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013158
13159 if (mProcessesToGc.size() > 0) {
13160 // Schedule a GC for the time to the next process.
13161 ProcessRecord proc = mProcessesToGc.get(0);
13162 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13163
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013164 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013165 long now = SystemClock.uptimeMillis();
13166 if (when < (now+GC_TIMEOUT)) {
13167 when = now + GC_TIMEOUT;
13168 }
13169 mHandler.sendMessageAtTime(msg, when);
13170 }
13171 }
13172
13173 /**
13174 * Add a process to the array of processes waiting to be GCed. Keeps the
13175 * list in sorted order by the last GC time. The process can't already be
13176 * on the list.
13177 */
13178 final void addProcessToGcListLocked(ProcessRecord proc) {
13179 boolean added = false;
13180 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13181 if (mProcessesToGc.get(i).lastRequestedGc <
13182 proc.lastRequestedGc) {
13183 added = true;
13184 mProcessesToGc.add(i+1, proc);
13185 break;
13186 }
13187 }
13188 if (!added) {
13189 mProcessesToGc.add(0, proc);
13190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013191 }
13192
13193 /**
13194 * Set up to ask a process to GC itself. This will either do it
13195 * immediately, or put it on the list of processes to gc the next
13196 * time things are idle.
13197 */
13198 final void scheduleAppGcLocked(ProcessRecord app) {
13199 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013200 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013201 return;
13202 }
13203 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013204 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013205 scheduleAppGcsLocked();
13206 }
13207 }
13208
Dianne Hackborn287952c2010-09-22 22:34:31 -070013209 final void checkExcessivePowerUsageLocked(boolean doKills) {
13210 updateCpuStatsNow();
13211
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013212 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013213 boolean doWakeKills = doKills;
13214 boolean doCpuKills = doKills;
13215 if (mLastPowerCheckRealtime == 0) {
13216 doWakeKills = false;
13217 }
13218 if (mLastPowerCheckUptime == 0) {
13219 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013220 }
13221 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013222 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013223 }
13224 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013225 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13226 final long curUptime = SystemClock.uptimeMillis();
13227 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13228 mLastPowerCheckRealtime = curRealtime;
13229 mLastPowerCheckUptime = curUptime;
13230 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13231 doWakeKills = false;
13232 }
13233 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13234 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013235 }
13236 int i = mLruProcesses.size();
13237 while (i > 0) {
13238 i--;
13239 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013240 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013241 long wtime;
13242 synchronized (stats) {
13243 wtime = stats.getProcessWakeTime(app.info.uid,
13244 app.pid, curRealtime);
13245 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013246 long wtimeUsed = wtime - app.lastWakeTime;
13247 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13248 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013249 StringBuilder sb = new StringBuilder(128);
13250 sb.append("Wake for ");
13251 app.toShortString(sb);
13252 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013253 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013254 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013255 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013256 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013257 sb.append((wtimeUsed*100)/realtimeSince);
13258 sb.append("%)");
13259 Slog.i(TAG, sb.toString());
13260 sb.setLength(0);
13261 sb.append("CPU for ");
13262 app.toShortString(sb);
13263 sb.append(": over ");
13264 TimeUtils.formatDuration(uptimeSince, sb);
13265 sb.append(" used ");
13266 TimeUtils.formatDuration(cputimeUsed, sb);
13267 sb.append(" (");
13268 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013269 sb.append("%)");
13270 Slog.i(TAG, sb.toString());
13271 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013272 // If a process has held a wake lock for more
13273 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013274 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013275 if (doWakeKills && realtimeSince > 0
13276 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13277 synchronized (stats) {
13278 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13279 realtimeSince, wtimeUsed);
13280 }
13281 Slog.w(TAG, "Excessive wake lock in " + app.processName
13282 + " (pid " + app.pid + "): held " + wtimeUsed
13283 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013284 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13285 app.processName, app.setAdj, "excessive wake lock");
13286 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013287 } else if (doCpuKills && uptimeSince > 0
13288 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13289 synchronized (stats) {
13290 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13291 uptimeSince, cputimeUsed);
13292 }
13293 Slog.w(TAG, "Excessive CPU in " + app.processName
13294 + " (pid " + app.pid + "): used " + cputimeUsed
13295 + " during " + uptimeSince);
13296 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13297 app.processName, app.setAdj, "excessive cpu");
13298 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013299 } else {
13300 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013301 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013302 }
13303 }
13304 }
13305 }
13306
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013307 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13308 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013309 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013310 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013311
13312 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013313 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013314 }
13315
Dianne Hackborn287952c2010-09-22 22:34:31 -070013316 final boolean wasKeeping = app.keeping;
13317
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013318 boolean success = true;
13319
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013320 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013321
Jeff Brown10e89712011-07-08 18:52:57 -070013322 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013323 if (wasKeeping && !app.keeping) {
13324 // This app is no longer something we want to keep. Note
13325 // its current wake lock time to later know to kill it if
13326 // it is not behaving well.
13327 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13328 synchronized (stats) {
13329 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13330 app.pid, SystemClock.elapsedRealtime());
13331 }
13332 app.lastCpuTime = app.curCpuTime;
13333 }
13334
13335 app.setRawAdj = app.curRawAdj;
13336 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013337
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013338 if (app.curAdj != app.setAdj) {
13339 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013340 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013341 TAG, "Set " + app.pid + " " + app.processName +
13342 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013343 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013344 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013345 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013346 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013347 }
13348 }
13349 if (app.setSchedGroup != app.curSchedGroup) {
13350 app.setSchedGroup = app.curSchedGroup;
13351 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13352 "Setting process group of " + app.processName
13353 + " to " + app.curSchedGroup);
13354 if (app.waitingToKill != null &&
13355 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13356 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13357 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13358 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013359 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013360 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013361 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013362 } else {
13363 if (true) {
13364 long oldId = Binder.clearCallingIdentity();
13365 try {
13366 Process.setProcessGroup(app.pid, app.curSchedGroup);
13367 } catch (Exception e) {
13368 Slog.w(TAG, "Failed setting process group of " + app.pid
13369 + " to " + app.curSchedGroup);
13370 e.printStackTrace();
13371 } finally {
13372 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013373 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013374 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013375 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013376 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013377 app.thread.setSchedulingGroup(app.curSchedGroup);
13378 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013379 }
13380 }
13381 }
13382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013383 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013384 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013385 }
13386
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013387 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013388 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013390 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013391 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013392 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013393 }
13394 }
13395 return resumedActivity;
13396 }
13397
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013398 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013399 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013400 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13401 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013402 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13403 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404
13405 mAdjSeq++;
13406
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013407 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13408 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013409 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13410 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013411 if (nowHidden != wasHidden) {
13412 // Changed to/from hidden state, so apps after it in the LRU
13413 // list may also be changed.
13414 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013415 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013416 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013417 }
13418
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013419 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013420 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013421 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13422
13423 if (false) {
13424 RuntimeException e = new RuntimeException();
13425 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013426 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013427 }
13428
13429 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013430 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013431
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013432 // Let's determine how many processes we have running vs.
13433 // how many slots we have for background processes; we may want
13434 // to put multiple processes in a slot of there are enough of
13435 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013436 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13437 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13438 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13439 if (emptyFactor < 1) emptyFactor = 1;
13440 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13441 if (hiddenFactor < 1) hiddenFactor = 1;
13442 int stepHidden = 0;
13443 int stepEmpty = 0;
13444 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13445 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013446 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013447 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013448 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013449
13450 mNumNonHiddenProcs = 0;
13451 mNumHiddenProcs = 0;
13452
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013453 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013454 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013455 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013456 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013457 int nextHiddenAdj = curHiddenAdj+1;
13458 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13459 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013460 while (i > 0) {
13461 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013462 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013463 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013464 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013465 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013466 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13467 // This process was assigned as a hidden process... step the
13468 // hidden level.
13469 mNumHiddenProcs++;
13470 if (curHiddenAdj != nextHiddenAdj) {
13471 stepHidden++;
13472 if (stepHidden >= hiddenFactor) {
13473 stepHidden = 0;
13474 curHiddenAdj = nextHiddenAdj;
13475 nextHiddenAdj += 2;
13476 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13477 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13478 }
13479 }
13480 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013481 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013482 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013483 Slog.i(TAG, "No longer want " + app.processName
13484 + " (pid " + app.pid + "): hidden #" + numHidden);
13485 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13486 app.processName, app.setAdj, "too many background");
13487 app.killedBackground = true;
13488 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013489 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013490 } else {
13491 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13492 // This process was assigned as an empty process... step the
13493 // empty level.
13494 if (curEmptyAdj != nextEmptyAdj) {
13495 stepEmpty++;
13496 if (stepEmpty >= emptyFactor) {
13497 stepEmpty = 0;
13498 curEmptyAdj = nextEmptyAdj;
13499 nextEmptyAdj += 2;
13500 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13501 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13502 }
13503 }
13504 }
13505 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13506 mNumNonHiddenProcs++;
13507 }
13508 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13509 numEmpty++;
13510 if (numEmpty > emptyProcessLimit) {
13511 Slog.i(TAG, "No longer want " + app.processName
13512 + " (pid " + app.pid + "): empty #" + numEmpty);
13513 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13514 app.processName, app.setAdj, "too many background");
13515 app.killedBackground = true;
13516 Process.killProcessQuiet(app.pid);
13517 }
13518 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013519 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013520 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013521 // If this is an isolated process, and there are no
13522 // services running in it, then the process is no longer
13523 // needed. We agressively kill these because we can by
13524 // definition not re-use the same process again, and it is
13525 // good to avoid having whatever code was running in them
13526 // left sitting around after no longer needed.
13527 Slog.i(TAG, "Isolated process " + app.processName
13528 + " (pid " + app.pid + ") no longer needed");
13529 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13530 app.processName, app.setAdj, "isolated not needed");
13531 app.killedBackground = true;
13532 Process.killProcessQuiet(app.pid);
13533 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013534 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13535 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13536 && !app.killedBackground) {
13537 numTrimming++;
13538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013539 }
13540 }
13541
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013542 mNumServiceProcs = mNewNumServiceProcs;
13543
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013544 // Now determine the memory trimming level of background processes.
13545 // Unfortunately we need to start at the back of the list to do this
13546 // properly. We only do this if the number of background apps we
13547 // are managing to keep around is less than half the maximum we desire;
13548 // if we are keeping a good number around, we'll let them use whatever
13549 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013550 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13551 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13552 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013553 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013554 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013555 int minFactor = 2;
13556 if (mHomeProcess != null) minFactor++;
13557 if (mPreviousProcess != null) minFactor++;
13558 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013559 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013560 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013561 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013562 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013563 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013564 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13565 } else {
13566 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13567 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013568 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013569 for (i=0; i<N; i++) {
13570 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013571 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13572 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013573 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013574 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13575 try {
13576 app.thread.scheduleTrimMemory(curLevel);
13577 } catch (RemoteException e) {
13578 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013579 if (false) {
13580 // For now we won't do this; our memory trimming seems
13581 // to be good enough at this point that destroying
13582 // activities causes more harm than good.
13583 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13584 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013585 // Need to do this on its own message because the stack may not
13586 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013587 // For these apps we will also finish their activities
13588 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013589 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013590 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013591 }
13592 }
13593 app.trimMemoryLevel = curLevel;
13594 step++;
13595 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013596 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013597 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013598 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13599 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013600 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013601 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13602 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013603 break;
13604 }
13605 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013606 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013607 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013608 && app.thread != null) {
13609 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013610 app.thread.scheduleTrimMemory(
13611 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013612 } catch (RemoteException e) {
13613 }
13614 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013615 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013616 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013617 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013618 && app.pendingUiClean) {
13619 // If this application is now in the background and it
13620 // had done UI, then give it the special trim level to
13621 // have it free UI resources.
13622 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13623 if (app.trimMemoryLevel < level && app.thread != null) {
13624 try {
13625 app.thread.scheduleTrimMemory(level);
13626 } catch (RemoteException e) {
13627 }
13628 }
13629 app.pendingUiClean = false;
13630 }
13631 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013632 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013633 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013634 } catch (RemoteException e) {
13635 }
13636 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013637 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013638 }
13639 }
13640 } else {
13641 final int N = mLruProcesses.size();
13642 for (i=0; i<N; i++) {
13643 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013644 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013645 && app.pendingUiClean) {
13646 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13647 && app.thread != null) {
13648 try {
13649 app.thread.scheduleTrimMemory(
13650 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13651 } catch (RemoteException e) {
13652 }
13653 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013654 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013655 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013656 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013657 }
13658 }
13659
13660 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013661 // Need to do this on its own message because the stack may not
13662 // be in a consistent state at this point.
13663 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013665 }
13666
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013667 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013668 synchronized (this) {
13669 int i;
13670
13671 // First remove any unused application processes whose package
13672 // has been removed.
13673 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13674 final ProcessRecord app = mRemovedProcesses.get(i);
13675 if (app.activities.size() == 0
13676 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013677 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013678 TAG, "Exiting empty application process "
13679 + app.processName + " ("
13680 + (app.thread != null ? app.thread.asBinder() : null)
13681 + ")\n");
13682 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013683 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13684 app.processName, app.setAdj, "empty");
13685 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013686 } else {
13687 try {
13688 app.thread.scheduleExit();
13689 } catch (Exception e) {
13690 // Ignore exceptions.
13691 }
13692 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013693 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013694 mRemovedProcesses.remove(i);
13695
13696 if (app.persistent) {
13697 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013698 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013699 }
13700 }
13701 }
13702 }
13703
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013704 // Now update the oom adj for all processes.
13705 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013706 }
13707 }
13708
13709 /** This method sends the specified signal to each of the persistent apps */
13710 public void signalPersistentProcesses(int sig) throws RemoteException {
13711 if (sig != Process.SIGNAL_USR1) {
13712 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13713 }
13714
13715 synchronized (this) {
13716 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13717 != PackageManager.PERMISSION_GRANTED) {
13718 throw new SecurityException("Requires permission "
13719 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13720 }
13721
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013722 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13723 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013724 if (r.thread != null && r.persistent) {
13725 Process.sendSignal(r.pid, sig);
13726 }
13727 }
13728 }
13729 }
13730
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013731 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13732 if (proc == null || proc == mProfileProc) {
13733 proc = mProfileProc;
13734 path = mProfileFile;
13735 profileType = mProfileType;
13736 clearProfilerLocked();
13737 }
13738 if (proc == null) {
13739 return;
13740 }
13741 try {
13742 proc.thread.profilerControl(false, path, null, profileType);
13743 } catch (RemoteException e) {
13744 throw new IllegalStateException("Process disappeared");
13745 }
13746 }
13747
13748 private void clearProfilerLocked() {
13749 if (mProfileFd != null) {
13750 try {
13751 mProfileFd.close();
13752 } catch (IOException e) {
13753 }
13754 }
13755 mProfileApp = null;
13756 mProfileProc = null;
13757 mProfileFile = null;
13758 mProfileType = 0;
13759 mAutoStopProfiler = false;
13760 }
13761
Dianne Hackborn1676c852012-09-10 14:52:30 -070013762 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013763 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013764
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013765 try {
13766 synchronized (this) {
13767 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13768 // its own permission.
13769 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13770 != PackageManager.PERMISSION_GRANTED) {
13771 throw new SecurityException("Requires permission "
13772 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013773 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013774
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013775 if (start && fd == null) {
13776 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013777 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013778
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013779 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013780 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013781 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013782 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013783
13784 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013785 throw new IllegalArgumentException("Unknown process: " + process);
13786 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013787
13788 if (start) {
13789 stopProfilerLocked(null, null, 0);
13790 setProfileApp(proc.info, proc.processName, path, fd, false);
13791 mProfileProc = proc;
13792 mProfileType = profileType;
13793 try {
13794 fd = fd.dup();
13795 } catch (IOException e) {
13796 fd = null;
13797 }
13798 proc.thread.profilerControl(start, path, fd, profileType);
13799 fd = null;
13800 mProfileFd = null;
13801 } else {
13802 stopProfilerLocked(proc, path, profileType);
13803 if (fd != null) {
13804 try {
13805 fd.close();
13806 } catch (IOException e) {
13807 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013808 }
13809 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013810
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013811 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013812 }
13813 } catch (RemoteException e) {
13814 throw new IllegalStateException("Process disappeared");
13815 } finally {
13816 if (fd != null) {
13817 try {
13818 fd.close();
13819 } catch (IOException e) {
13820 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013821 }
13822 }
13823 }
Andy McFadden824c5102010-07-09 16:26:57 -070013824
Dianne Hackborn1676c852012-09-10 14:52:30 -070013825 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
13826 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
13827 userId, true, true, callName, null);
13828 ProcessRecord proc = null;
13829 try {
13830 int pid = Integer.parseInt(process);
13831 synchronized (mPidsSelfLocked) {
13832 proc = mPidsSelfLocked.get(pid);
13833 }
13834 } catch (NumberFormatException e) {
13835 }
13836
13837 if (proc == null) {
13838 HashMap<String, SparseArray<ProcessRecord>> all
13839 = mProcessNames.getMap();
13840 SparseArray<ProcessRecord> procs = all.get(process);
13841 if (procs != null && procs.size() > 0) {
13842 proc = procs.valueAt(0);
13843 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13844 for (int i=1; i<procs.size(); i++) {
13845 ProcessRecord thisProc = procs.valueAt(i);
13846 if (thisProc.userId == userId) {
13847 proc = thisProc;
13848 break;
13849 }
13850 }
13851 }
13852 }
13853 }
13854
13855 return proc;
13856 }
13857
13858 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013859 String path, ParcelFileDescriptor fd) throws RemoteException {
13860
13861 try {
13862 synchronized (this) {
13863 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13864 // its own permission (same as profileControl).
13865 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13866 != PackageManager.PERMISSION_GRANTED) {
13867 throw new SecurityException("Requires permission "
13868 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13869 }
13870
13871 if (fd == null) {
13872 throw new IllegalArgumentException("null fd");
13873 }
13874
Dianne Hackborn1676c852012-09-10 14:52:30 -070013875 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013876 if (proc == null || proc.thread == null) {
13877 throw new IllegalArgumentException("Unknown process: " + process);
13878 }
13879
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013880 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13881 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013882 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13883 throw new SecurityException("Process not debuggable: " + proc);
13884 }
13885 }
13886
13887 proc.thread.dumpHeap(managed, path, fd);
13888 fd = null;
13889 return true;
13890 }
13891 } catch (RemoteException e) {
13892 throw new IllegalStateException("Process disappeared");
13893 } finally {
13894 if (fd != null) {
13895 try {
13896 fd.close();
13897 } catch (IOException e) {
13898 }
13899 }
13900 }
13901 }
13902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013903 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13904 public void monitor() {
13905 synchronized (this) { }
13906 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013907
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013908 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013909 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13910 ProcessRecord processRecord = mLruProcesses.get(i);
13911 try {
13912 if (processRecord.thread != null) {
13913 processRecord.thread.setCoreSettings(settings);
13914 }
13915 } catch (RemoteException re) {
13916 /* ignore */
13917 }
13918 }
13919 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013920
13921 // Multi-user methods
13922
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013923 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013924 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013925 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13926 != PackageManager.PERMISSION_GRANTED) {
13927 String msg = "Permission Denial: switchUser() from pid="
13928 + Binder.getCallingPid()
13929 + ", uid=" + Binder.getCallingUid()
13930 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13931 Slog.w(TAG, msg);
13932 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013933 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013934
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013935 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013936 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013937 synchronized (this) {
13938 final int oldUserId = mCurrentUserId;
13939 if (oldUserId == userId) {
13940 return true;
13941 }
13942
13943 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
13944 if (userInfo == null) {
13945 Slog.w(TAG, "No user info for user #" + userId);
13946 return false;
13947 }
13948
13949 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
13950 R.anim.screen_user_enter);
13951
13952 // If the user we are switching to is not currently started, then
13953 // we need to start it now.
13954 if (mStartedUsers.get(userId) == null) {
13955 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
13956 }
13957
13958 mCurrentUserId = userId;
13959 final Integer userIdInt = Integer.valueOf(userId);
13960 mUserLru.remove(userIdInt);
13961 mUserLru.add(userIdInt);
13962
13963 final UserStartedState uss = mStartedUsers.get(userId);
13964
13965 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
13966 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
13967 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
13968 oldUserId, userId, uss));
13969 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
13970 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
13971 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
13972 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13973 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13974 broadcastIntentLocked(null, null, intent,
13975 null, null, 0, null, null, null,
13976 false, false, MY_PID, Process.SYSTEM_UID, userId);
13977
13978 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
13979 if (userId != 0) {
13980 intent = new Intent(Intent.ACTION_USER_INITIALIZE);
13981 broadcastIntentLocked(null, null, intent, null,
13982 new IIntentReceiver.Stub() {
13983 public void performReceive(Intent intent, int resultCode,
13984 String data, Bundle extras, boolean ordered,
13985 boolean sticky, int sendingUser) {
13986 synchronized (ActivityManagerService.this) {
13987 getUserManagerLocked().makeInitialized(userInfo.id);
13988 }
13989 }
13990 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
13991 userId);
13992 } else {
13993 getUserManagerLocked().makeInitialized(userInfo.id);
13994 }
13995 }
13996
13997 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
13998 if (!haveActivities) {
13999 startHomeActivityLocked(userId);
14000 }
14001
14002 sendUserSwitchBroadcastsLocked(oldUserId, userId);
14003 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014004 } finally {
14005 Binder.restoreCallingIdentity(ident);
14006 }
Amith Yamasani13593602012-03-22 16:16:17 -070014007
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014008 return true;
14009 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014010
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014011 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14012 long ident = Binder.clearCallingIdentity();
14013 try {
14014 Intent intent;
14015 if (oldUserId >= 0) {
14016 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
14017 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14018 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14019 broadcastIntentLocked(null, null, intent,
14020 null, null, 0, null, null, null,
14021 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14022 }
14023 if (newUserId >= 0) {
14024 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
14025 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14026 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14027 broadcastIntentLocked(null, null, intent,
14028 null, null, 0, null, null, null,
14029 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14030 intent = new Intent(Intent.ACTION_USER_SWITCHED);
14031 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14032 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14033 broadcastIntentLocked(null, null, intent,
14034 null, null, 0, null, null,
14035 android.Manifest.permission.MANAGE_USERS,
14036 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14037 }
14038 } finally {
14039 Binder.restoreCallingIdentity(ident);
14040 }
14041 }
14042
14043 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14044 final int newUserId) {
14045 final int N = mUserSwitchObservers.beginBroadcast();
14046 if (N > 0) {
14047 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14048 int mCount = 0;
14049 @Override
14050 public void sendResult(Bundle data) throws RemoteException {
14051 synchronized (ActivityManagerService.this) {
14052 if (mCurUserSwitchCallback == this) {
14053 mCount++;
14054 if (mCount == N) {
14055 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14056 }
14057 }
14058 }
14059 }
14060 };
14061 synchronized (this) {
14062 mCurUserSwitchCallback = callback;
14063 }
14064 for (int i=0; i<N; i++) {
14065 try {
14066 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14067 newUserId, callback);
14068 } catch (RemoteException e) {
14069 }
14070 }
14071 } else {
14072 synchronized (this) {
14073 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14074 }
14075 }
14076 mUserSwitchObservers.finishBroadcast();
14077 }
14078
14079 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14080 synchronized (this) {
14081 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14082 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14083 }
14084 }
14085
14086 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14087 mCurUserSwitchCallback = null;
14088 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14089 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14090 oldUserId, newUserId, uss));
14091 }
14092
14093 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14094 final int N = mUserSwitchObservers.beginBroadcast();
14095 for (int i=0; i<N; i++) {
14096 try {
14097 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14098 } catch (RemoteException e) {
14099 }
14100 }
14101 mUserSwitchObservers.finishBroadcast();
14102 synchronized (this) {
14103 mWindowManager.stopFreezingScreen();
14104 }
14105 }
14106
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014107 void finishUserSwitch(UserStartedState uss) {
14108 synchronized (this) {
14109 if (uss.mState == UserStartedState.STATE_BOOTING
14110 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14111 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014112 final int userId = uss.mHandle.getIdentifier();
14113 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14114 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14115 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014116 null, null, 0, null, null,
14117 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014118 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014119 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014120 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014121 }
14122
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014123 @Override
14124 public int stopUser(final int userId, final IStopUserCallback callback) {
14125 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14126 != PackageManager.PERMISSION_GRANTED) {
14127 String msg = "Permission Denial: switchUser() from pid="
14128 + Binder.getCallingPid()
14129 + ", uid=" + Binder.getCallingUid()
14130 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14131 Slog.w(TAG, msg);
14132 throw new SecurityException(msg);
14133 }
14134 if (userId <= 0) {
14135 throw new IllegalArgumentException("Can't stop primary user " + userId);
14136 }
Amith Yamasani13593602012-03-22 16:16:17 -070014137 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014138 if (mCurrentUserId == userId) {
14139 return ActivityManager.USER_OP_IS_CURRENT;
14140 }
14141
14142 final UserStartedState uss = mStartedUsers.get(userId);
14143 if (uss == null) {
14144 // User is not started, nothing to do... but we do need to
14145 // callback if requested.
14146 if (callback != null) {
14147 mHandler.post(new Runnable() {
14148 @Override
14149 public void run() {
14150 try {
14151 callback.userStopped(userId);
14152 } catch (RemoteException e) {
14153 }
14154 }
14155 });
14156 }
14157 return ActivityManager.USER_OP_SUCCESS;
14158 }
14159
14160 if (callback != null) {
14161 uss.mStopCallbacks.add(callback);
14162 }
14163
14164 if (uss.mState != UserStartedState.STATE_STOPPING) {
14165 uss.mState = UserStartedState.STATE_STOPPING;
14166
14167 long ident = Binder.clearCallingIdentity();
14168 try {
14169 // Inform of user switch
14170 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
14171 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
14172 @Override
14173 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070014174 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014175 finishUserStop(uss);
14176 }
14177 };
14178 broadcastIntentLocked(null, null, intent,
14179 null, resultReceiver, 0, null, null, null,
14180 true, false, MY_PID, Process.SYSTEM_UID, userId);
14181 } finally {
14182 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014183 }
14184 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014185 }
Amith Yamasani13593602012-03-22 16:16:17 -070014186
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014187 return ActivityManager.USER_OP_SUCCESS;
14188 }
14189
14190 void finishUserStop(UserStartedState uss) {
14191 final int userId = uss.mHandle.getIdentifier();
14192 boolean stopped;
14193 ArrayList<IStopUserCallback> callbacks;
14194 synchronized (this) {
14195 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
14196 if (uss.mState != UserStartedState.STATE_STOPPING
14197 || mStartedUsers.get(userId) != uss) {
14198 stopped = false;
14199 } else {
14200 stopped = true;
14201 // User can no longer run.
14202 mStartedUsers.remove(userId);
14203
14204 // Clean up all state and processes associated with the user.
14205 // Kill all the processes for the user.
14206 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014207 }
14208 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014209
14210 for (int i=0; i<callbacks.size(); i++) {
14211 try {
14212 if (stopped) callbacks.get(i).userStopped(userId);
14213 else callbacks.get(i).userStopAborted(userId);
14214 } catch (RemoteException e) {
14215 }
14216 }
14217 }
14218
14219 @Override
14220 public UserInfo getCurrentUser() {
14221 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14222 != PackageManager.PERMISSION_GRANTED) {
14223 String msg = "Permission Denial: getCurrentUser() from pid="
14224 + Binder.getCallingPid()
14225 + ", uid=" + Binder.getCallingUid()
14226 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14227 Slog.w(TAG, msg);
14228 throw new SecurityException(msg);
14229 }
14230 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014231 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014232 }
Amith Yamasani13593602012-03-22 16:16:17 -070014233 }
14234
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014235 @Override
14236 public boolean isUserRunning(int userId) {
14237 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14238 != PackageManager.PERMISSION_GRANTED) {
14239 String msg = "Permission Denial: isUserRunning() from pid="
14240 + Binder.getCallingPid()
14241 + ", uid=" + Binder.getCallingUid()
14242 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14243 Slog.w(TAG, msg);
14244 throw new SecurityException(msg);
14245 }
14246 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014247 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014248 }
14249 }
14250
Dianne Hackborn1676c852012-09-10 14:52:30 -070014251 boolean isUserRunningLocked(int userId) {
14252 UserStartedState state = mStartedUsers.get(userId);
14253 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014254 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014255
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014256 @Override
14257 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14258 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14259 != PackageManager.PERMISSION_GRANTED) {
14260 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14261 + Binder.getCallingPid()
14262 + ", uid=" + Binder.getCallingUid()
14263 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14264 Slog.w(TAG, msg);
14265 throw new SecurityException(msg);
14266 }
14267
14268 mUserSwitchObservers.register(observer);
14269 }
14270
14271 @Override
14272 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14273 mUserSwitchObservers.unregister(observer);
14274 }
14275
Dianne Hackborn1676c852012-09-10 14:52:30 -070014276 private boolean userExists(int userId) {
14277 if (userId == 0) {
14278 return true;
14279 }
14280 UserManagerService ums = getUserManagerLocked();
14281 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14282 }
14283
14284 int[] getUsersLocked() {
14285 UserManagerService ums = getUserManagerLocked();
14286 return ums != null ? ums.getUserIds() : new int[] { 0 };
14287 }
14288
14289 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014290 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014291 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14292 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014293 }
14294 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014295 }
14296
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014297 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014298 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014299
14300 throw new SecurityException("Caller uid=" + uid
14301 + " is not privileged to communicate with user=" + userId);
14302 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014303
14304 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014305 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014306 }
14307
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014308 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014309 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014310 ApplicationInfo newInfo = new ApplicationInfo(info);
14311 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014312 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14313 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014314 return newInfo;
14315 }
14316
14317 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014318 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014319 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014320 return aInfo;
14321 }
14322
14323 ActivityInfo info = new ActivityInfo(aInfo);
14324 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14325 return info;
14326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014327}