blob: db042b514c7ca679f4d6d5062d20ae8e086880d3 [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,
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001797 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) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001854 updateLruProcessInternalLocked(cr.binding.service.app,
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) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001862 updateLruProcessInternalLocked(cpr.proc,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001863 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001864 }
1865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001868 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001869 boolean oomAdj, boolean updateActivityTime) {
1870 mLruSeq++;
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001871 updateLruProcessInternalLocked(app, updateActivityTime, 0);
1872
1873 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1874 if (oomAdj) {
1875 updateOomAdjLocked();
1876 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001877 }
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 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004458
4459 public final void activityResumed(IBinder token) {
4460 final long origId = Binder.clearCallingIdentity();
4461 mMainStack.activityResumed(token);
4462 Binder.restoreCallingIdentity(origId);
4463 }
4464
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004465 public final void activityPaused(IBinder token) {
4466 final long origId = Binder.clearCallingIdentity();
4467 mMainStack.activityPaused(token, false);
4468 Binder.restoreCallingIdentity(origId);
4469 }
4470
4471 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4472 CharSequence description) {
4473 if (localLOGV) Slog.v(
4474 TAG, "Activity stopped: token=" + token);
4475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 // Refuse possible leaked file descriptors
4477 if (icicle != null && icicle.hasFileDescriptors()) {
4478 throw new IllegalArgumentException("File descriptors passed in Bundle");
4479 }
4480
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004481 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482
4483 final long origId = Binder.clearCallingIdentity();
4484
4485 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004486 r = mMainStack.isInStackLocked(token);
4487 if (r != null) {
4488 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 }
4490 }
4491
4492 if (r != null) {
4493 sendPendingThumbnail(r, null, null, null, false);
4494 }
4495
4496 trimApplications();
4497
4498 Binder.restoreCallingIdentity(origId);
4499 }
4500
4501 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004502 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004503 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
4505
4506 public String getCallingPackage(IBinder token) {
4507 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004508 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004509 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 }
4511 }
4512
4513 public ComponentName getCallingActivity(IBinder token) {
4514 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004515 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 return r != null ? r.intent.getComponent() : null;
4517 }
4518 }
4519
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004520 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004521 ActivityRecord r = mMainStack.isInStackLocked(token);
4522 if (r == null) {
4523 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004525 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 }
4527
4528 public ComponentName getActivityClassForToken(IBinder token) {
4529 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004530 ActivityRecord r = mMainStack.isInStackLocked(token);
4531 if (r == null) {
4532 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004534 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 }
4536 }
4537
4538 public String getPackageForToken(IBinder token) {
4539 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004540 ActivityRecord r = mMainStack.isInStackLocked(token);
4541 if (r == null) {
4542 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004544 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 }
4546 }
4547
4548 public IIntentSender getIntentSender(int type,
4549 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004550 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004551 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004552 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004554 if (intents != null) {
4555 if (intents.length < 1) {
4556 throw new IllegalArgumentException("Intents array length must be >= 1");
4557 }
4558 for (int i=0; i<intents.length; i++) {
4559 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004560 if (intent != null) {
4561 if (intent.hasFileDescriptors()) {
4562 throw new IllegalArgumentException("File descriptors passed in Intent");
4563 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004564 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004565 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4566 throw new IllegalArgumentException(
4567 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4568 }
4569 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004570 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004571 }
4572 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004573 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004574 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004575 }
4576 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004577 if (options != null) {
4578 if (options.hasFileDescriptors()) {
4579 throw new IllegalArgumentException("File descriptors passed in options");
4580 }
4581 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 synchronized(this) {
4584 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004585 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4586 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004588 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004589 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004590 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4591 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 String msg = "Permission Denial: getIntentSender() from pid="
4593 + Binder.getCallingPid()
4594 + ", uid=" + Binder.getCallingUid()
4595 + ", (need uid=" + uid + ")"
4596 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004597 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 throw new SecurityException(msg);
4599 }
4600 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004601
4602 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004603 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 } catch (RemoteException e) {
4606 throw new SecurityException(e);
4607 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004608 }
4609 }
4610
Dianne Hackborn41203752012-08-31 14:05:51 -07004611 IIntentSender getIntentSenderLocked(int type, String packageName,
4612 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004613 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4614 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004615 if (DEBUG_MU)
4616 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004617 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004618 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004619 activity = mMainStack.isInStackLocked(token);
4620 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004621 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004623 if (activity.finishing) {
4624 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004626 }
4627
4628 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4629 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4630 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4631 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4632 |PendingIntent.FLAG_UPDATE_CURRENT);
4633
4634 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4635 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004636 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004637 WeakReference<PendingIntentRecord> ref;
4638 ref = mIntentSenderRecords.get(key);
4639 PendingIntentRecord rec = ref != null ? ref.get() : null;
4640 if (rec != null) {
4641 if (!cancelCurrent) {
4642 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004643 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004644 rec.key.requestIntent.replaceExtras(intents != null ?
4645 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004646 }
4647 if (intents != null) {
4648 intents[intents.length-1] = rec.key.requestIntent;
4649 rec.key.allIntents = intents;
4650 rec.key.allResolvedTypes = resolvedTypes;
4651 } else {
4652 rec.key.allIntents = null;
4653 rec.key.allResolvedTypes = null;
4654 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 return rec;
4657 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004658 rec.canceled = true;
4659 mIntentSenderRecords.remove(key);
4660 }
4661 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 return rec;
4663 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004664 rec = new PendingIntentRecord(this, key, callingUid);
4665 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004666 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004667 if (activity.pendingResults == null) {
4668 activity.pendingResults
4669 = new HashSet<WeakReference<PendingIntentRecord>>();
4670 }
4671 activity.pendingResults.add(rec.ref);
4672 }
4673 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 }
4675
4676 public void cancelIntentSender(IIntentSender sender) {
4677 if (!(sender instanceof PendingIntentRecord)) {
4678 return;
4679 }
4680 synchronized(this) {
4681 PendingIntentRecord rec = (PendingIntentRecord)sender;
4682 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004683 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004684 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4685 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 String msg = "Permission Denial: cancelIntentSender() from pid="
4687 + Binder.getCallingPid()
4688 + ", uid=" + Binder.getCallingUid()
4689 + " is not allowed to cancel packges "
4690 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004691 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 throw new SecurityException(msg);
4693 }
4694 } catch (RemoteException e) {
4695 throw new SecurityException(e);
4696 }
4697 cancelIntentSenderLocked(rec, true);
4698 }
4699 }
4700
4701 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4702 rec.canceled = true;
4703 mIntentSenderRecords.remove(rec.key);
4704 if (cleanActivity && rec.key.activity != null) {
4705 rec.key.activity.pendingResults.remove(rec.ref);
4706 }
4707 }
4708
4709 public String getPackageForIntentSender(IIntentSender pendingResult) {
4710 if (!(pendingResult instanceof PendingIntentRecord)) {
4711 return null;
4712 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004713 try {
4714 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4715 return res.key.packageName;
4716 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 }
4718 return null;
4719 }
4720
Christopher Tatec4a07d12012-04-06 14:19:13 -07004721 public int getUidForIntentSender(IIntentSender sender) {
4722 if (sender instanceof PendingIntentRecord) {
4723 try {
4724 PendingIntentRecord res = (PendingIntentRecord)sender;
4725 return res.uid;
4726 } catch (ClassCastException e) {
4727 }
4728 }
4729 return -1;
4730 }
4731
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004732 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4733 if (!(pendingResult instanceof PendingIntentRecord)) {
4734 return false;
4735 }
4736 try {
4737 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4738 if (res.key.allIntents == null) {
4739 return false;
4740 }
4741 for (int i=0; i<res.key.allIntents.length; i++) {
4742 Intent intent = res.key.allIntents[i];
4743 if (intent.getPackage() != null && intent.getComponent() != null) {
4744 return false;
4745 }
4746 }
4747 return true;
4748 } catch (ClassCastException e) {
4749 }
4750 return false;
4751 }
4752
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004753 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4754 if (!(pendingResult instanceof PendingIntentRecord)) {
4755 return false;
4756 }
4757 try {
4758 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4759 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4760 return true;
4761 }
4762 return false;
4763 } catch (ClassCastException e) {
4764 }
4765 return false;
4766 }
4767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004768 public void setProcessLimit(int max) {
4769 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4770 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004771 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004772 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004773 mProcessLimitOverride = max;
4774 }
4775 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777
4778 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004779 synchronized (this) {
4780 return mProcessLimitOverride;
4781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004782 }
4783
4784 void foregroundTokenDied(ForegroundToken token) {
4785 synchronized (ActivityManagerService.this) {
4786 synchronized (mPidsSelfLocked) {
4787 ForegroundToken cur
4788 = mForegroundProcesses.get(token.pid);
4789 if (cur != token) {
4790 return;
4791 }
4792 mForegroundProcesses.remove(token.pid);
4793 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4794 if (pr == null) {
4795 return;
4796 }
4797 pr.forcingToForeground = null;
4798 pr.foregroundServices = false;
4799 }
4800 updateOomAdjLocked();
4801 }
4802 }
4803
4804 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4805 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4806 "setProcessForeground()");
4807 synchronized(this) {
4808 boolean changed = false;
4809
4810 synchronized (mPidsSelfLocked) {
4811 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004812 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004813 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 return;
4815 }
4816 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4817 if (oldToken != null) {
4818 oldToken.token.unlinkToDeath(oldToken, 0);
4819 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004820 if (pr != null) {
4821 pr.forcingToForeground = null;
4822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 changed = true;
4824 }
4825 if (isForeground && token != null) {
4826 ForegroundToken newToken = new ForegroundToken() {
4827 public void binderDied() {
4828 foregroundTokenDied(this);
4829 }
4830 };
4831 newToken.pid = pid;
4832 newToken.token = token;
4833 try {
4834 token.linkToDeath(newToken, 0);
4835 mForegroundProcesses.put(pid, newToken);
4836 pr.forcingToForeground = token;
4837 changed = true;
4838 } catch (RemoteException e) {
4839 // If the process died while doing this, we will later
4840 // do the cleanup with the process death link.
4841 }
4842 }
4843 }
4844
4845 if (changed) {
4846 updateOomAdjLocked();
4847 }
4848 }
4849 }
4850
4851 // =========================================================
4852 // PERMISSIONS
4853 // =========================================================
4854
4855 static class PermissionController extends IPermissionController.Stub {
4856 ActivityManagerService mActivityManagerService;
4857 PermissionController(ActivityManagerService activityManagerService) {
4858 mActivityManagerService = activityManagerService;
4859 }
4860
4861 public boolean checkPermission(String permission, int pid, int uid) {
4862 return mActivityManagerService.checkPermission(permission, pid,
4863 uid) == PackageManager.PERMISSION_GRANTED;
4864 }
4865 }
4866
4867 /**
4868 * This can be called with or without the global lock held.
4869 */
4870 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004871 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 // We might be performing an operation on behalf of an indirect binder
4873 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4874 // client identity accordingly before proceeding.
4875 Identity tlsIdentity = sCallerIdentity.get();
4876 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004877 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4879 uid = tlsIdentity.uid;
4880 pid = tlsIdentity.pid;
4881 }
4882
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004883 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 return PackageManager.PERMISSION_GRANTED;
4885 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004886
4887 return ActivityManager.checkComponentPermission(permission, uid,
4888 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 }
4890
4891 /**
4892 * As the only public entry point for permissions checking, this method
4893 * can enforce the semantic that requesting a check on a null global
4894 * permission is automatically denied. (Internally a null permission
4895 * string is used when calling {@link #checkComponentPermission} in cases
4896 * when only uid-based security is needed.)
4897 *
4898 * This can be called with or without the global lock held.
4899 */
4900 public int checkPermission(String permission, int pid, int uid) {
4901 if (permission == null) {
4902 return PackageManager.PERMISSION_DENIED;
4903 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004904 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 }
4906
4907 /**
4908 * Binder IPC calls go through the public entry point.
4909 * This can be called with or without the global lock held.
4910 */
4911 int checkCallingPermission(String permission) {
4912 return checkPermission(permission,
4913 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004914 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 }
4916
4917 /**
4918 * This can be called with or without the global lock held.
4919 */
4920 void enforceCallingPermission(String permission, String func) {
4921 if (checkCallingPermission(permission)
4922 == PackageManager.PERMISSION_GRANTED) {
4923 return;
4924 }
4925
4926 String msg = "Permission Denial: " + func + " from pid="
4927 + Binder.getCallingPid()
4928 + ", uid=" + Binder.getCallingUid()
4929 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004930 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 throw new SecurityException(msg);
4932 }
4933
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004934 /**
4935 * Determine if UID is holding permissions required to access {@link Uri} in
4936 * the given {@link ProviderInfo}. Final permission checking is always done
4937 * in {@link ContentProvider}.
4938 */
4939 private final boolean checkHoldingPermissionsLocked(
4940 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004941 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4942 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004943
4944 if (pi.applicationInfo.uid == uid) {
4945 return true;
4946 } else if (!pi.exported) {
4947 return false;
4948 }
4949
4950 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4951 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004953 // check if target holds top-level <provider> permissions
4954 if (!readMet && pi.readPermission != null
4955 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4956 readMet = true;
4957 }
4958 if (!writeMet && pi.writePermission != null
4959 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4960 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004961 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004962
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004963 // track if unprotected read/write is allowed; any denied
4964 // <path-permission> below removes this ability
4965 boolean allowDefaultRead = pi.readPermission == null;
4966 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004967
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004968 // check if target holds any <path-permission> that match uri
4969 final PathPermission[] pps = pi.pathPermissions;
4970 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004971 final String path = uri.getPath();
4972 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004973 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004974 i--;
4975 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004976 if (pp.match(path)) {
4977 if (!readMet) {
4978 final String pprperm = pp.getReadPermission();
4979 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4980 + pprperm + " for " + pp.getPath()
4981 + ": match=" + pp.match(path)
4982 + " check=" + pm.checkUidPermission(pprperm, uid));
4983 if (pprperm != null) {
4984 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4985 readMet = true;
4986 } else {
4987 allowDefaultRead = false;
4988 }
4989 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004990 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004991 if (!writeMet) {
4992 final String ppwperm = pp.getWritePermission();
4993 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4994 + ppwperm + " for " + pp.getPath()
4995 + ": match=" + pp.match(path)
4996 + " check=" + pm.checkUidPermission(ppwperm, uid));
4997 if (ppwperm != null) {
4998 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4999 writeMet = true;
5000 } else {
5001 allowDefaultWrite = false;
5002 }
5003 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005004 }
5005 }
5006 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005007 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005008
5009 // grant unprotected <provider> read/write, if not blocked by
5010 // <path-permission> above
5011 if (allowDefaultRead) readMet = true;
5012 if (allowDefaultWrite) writeMet = true;
5013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005014 } catch (RemoteException e) {
5015 return false;
5016 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005017
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005018 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 }
5020
5021 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5022 int modeFlags) {
5023 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005024 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 return true;
5026 }
5027 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5028 if (perms == null) return false;
5029 UriPermission perm = perms.get(uri);
5030 if (perm == null) return false;
5031 return (modeFlags&perm.modeFlags) == modeFlags;
5032 }
5033
5034 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005035 enforceNotIsolatedCaller("checkUriPermission");
5036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 // Another redirected-binder-call permissions check as in
5038 // {@link checkComponentPermission}.
5039 Identity tlsIdentity = sCallerIdentity.get();
5040 if (tlsIdentity != null) {
5041 uid = tlsIdentity.uid;
5042 pid = tlsIdentity.pid;
5043 }
5044
5045 // Our own process gets to do everything.
5046 if (pid == MY_PID) {
5047 return PackageManager.PERMISSION_GRANTED;
5048 }
5049 synchronized(this) {
5050 return checkUriPermissionLocked(uri, uid, modeFlags)
5051 ? PackageManager.PERMISSION_GRANTED
5052 : PackageManager.PERMISSION_DENIED;
5053 }
5054 }
5055
Dianne Hackborn39792d22010-08-19 18:01:52 -07005056 /**
5057 * Check if the targetPkg can be granted permission to access uri by
5058 * the callingUid using the given modeFlags. Throws a security exception
5059 * if callingUid is not allowed to do this. Returns the uid of the target
5060 * if the URI permission grant should be performed; returns -1 if it is not
5061 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005062 * If you already know the uid of the target, you can supply it in
5063 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005064 */
5065 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005066 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5068 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5069 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005070 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 }
5072
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005073 if (targetPkg != null) {
5074 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5075 "Checking grant " + targetPkg + " permission to " + uri);
5076 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005077
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005078 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079
5080 // If this is not a content: uri, we can't do anything with it.
5081 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005082 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005083 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005084 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 }
5086
5087 String name = uri.getAuthority();
5088 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005089 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005090 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 if (cpr != null) {
5092 pi = cpr.info;
5093 } else {
5094 try {
5095 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005096 PackageManager.GET_URI_PERMISSION_PATTERNS,
5097 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 } catch (RemoteException ex) {
5099 }
5100 }
5101 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005102 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005103 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 }
5105
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005106 int targetUid = lastTargetUid;
5107 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005108 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005109 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005110 if (targetUid < 0) {
5111 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5112 "Can't grant URI permission no uid for: " + targetPkg);
5113 return -1;
5114 }
5115 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005116 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 }
5119
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005120 if (targetUid >= 0) {
5121 // First... does the target actually need this permission?
5122 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5123 // No need to grant the target this permission.
5124 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5125 "Target " + targetPkg + " already has full permission to " + uri);
5126 return -1;
5127 }
5128 } else {
5129 // First... there is no target package, so can anyone access it?
5130 boolean allowed = pi.exported;
5131 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5132 if (pi.readPermission != null) {
5133 allowed = false;
5134 }
5135 }
5136 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5137 if (pi.writePermission != null) {
5138 allowed = false;
5139 }
5140 }
5141 if (allowed) {
5142 return -1;
5143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005146 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147 if (!pi.grantUriPermissions) {
5148 throw new SecurityException("Provider " + pi.packageName
5149 + "/" + pi.name
5150 + " does not allow granting of Uri permissions (uri "
5151 + uri + ")");
5152 }
5153 if (pi.uriPermissionPatterns != null) {
5154 final int N = pi.uriPermissionPatterns.length;
5155 boolean allowed = false;
5156 for (int i=0; i<N; i++) {
5157 if (pi.uriPermissionPatterns[i] != null
5158 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5159 allowed = true;
5160 break;
5161 }
5162 }
5163 if (!allowed) {
5164 throw new SecurityException("Provider " + pi.packageName
5165 + "/" + pi.name
5166 + " does not allow granting of permission to path of Uri "
5167 + uri);
5168 }
5169 }
5170
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005171 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005173 if (callingUid != Process.myUid()) {
5174 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5175 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5176 throw new SecurityException("Uid " + callingUid
5177 + " does not have permission to uri " + uri);
5178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 }
5180 }
5181
Dianne Hackborn39792d22010-08-19 18:01:52 -07005182 return targetUid;
5183 }
5184
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005185 public int checkGrantUriPermission(int callingUid, String targetPkg,
5186 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005187 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005188 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005189 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005190 }
5191 }
5192
Dianne Hackborn39792d22010-08-19 18:01:52 -07005193 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5194 Uri uri, int modeFlags, UriPermissionOwner owner) {
5195 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5196 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5197 if (modeFlags == 0) {
5198 return;
5199 }
5200
5201 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 // to the uri, and the target doesn't. Let's now give this to
5203 // the target.
5204
Joe Onorato8a9b2202010-02-26 18:56:32 -08005205 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005206 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005208 HashMap<Uri, UriPermission> targetUris
5209 = mGrantedUriPermissions.get(targetUid);
5210 if (targetUris == null) {
5211 targetUris = new HashMap<Uri, UriPermission>();
5212 mGrantedUriPermissions.put(targetUid, targetUris);
5213 }
5214
5215 UriPermission perm = targetUris.get(uri);
5216 if (perm == null) {
5217 perm = new UriPermission(targetUid, uri);
5218 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005221 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005222 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005224 } else {
5225 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5226 perm.readOwners.add(owner);
5227 owner.addReadPermission(perm);
5228 }
5229 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5230 perm.writeOwners.add(owner);
5231 owner.addWritePermission(perm);
5232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 }
5234 }
5235
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005236 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5237 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005238 if (targetPkg == null) {
5239 throw new NullPointerException("targetPkg");
5240 }
5241
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005242 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005243 if (targetUid < 0) {
5244 return;
5245 }
5246
5247 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5248 }
5249
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005250 static class NeededUriGrants extends ArrayList<Uri> {
5251 final String targetPkg;
5252 final int targetUid;
5253 final int flags;
5254
5255 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5256 targetPkg = _targetPkg;
5257 targetUid = _targetUid;
5258 flags = _flags;
5259 }
5260 }
5261
Dianne Hackborn39792d22010-08-19 18:01:52 -07005262 /**
5263 * Like checkGrantUriPermissionLocked, but takes an Intent.
5264 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005265 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5266 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005267 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005268 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5269 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005270 + " from " + intent + "; flags=0x"
5271 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5272
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005273 if (targetPkg == null) {
5274 throw new NullPointerException("targetPkg");
5275 }
5276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005278 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 }
5280 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005281 ClipData clip = intent.getClipData();
5282 if (data == null && clip == null) {
5283 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005284 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005285 if (data != null) {
5286 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5287 mode, needed != null ? needed.targetUid : -1);
5288 if (target > 0) {
5289 if (needed == null) {
5290 needed = new NeededUriGrants(targetPkg, target, mode);
5291 }
5292 needed.add(data);
5293 }
5294 }
5295 if (clip != null) {
5296 for (int i=0; i<clip.getItemCount(); i++) {
5297 Uri uri = clip.getItemAt(i).getUri();
5298 if (uri != null) {
5299 int target = -1;
5300 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5301 mode, needed != null ? needed.targetUid : -1);
5302 if (target > 0) {
5303 if (needed == null) {
5304 needed = new NeededUriGrants(targetPkg, target, mode);
5305 }
5306 needed.add(uri);
5307 }
5308 } else {
5309 Intent clipIntent = clip.getItemAt(i).getIntent();
5310 if (clipIntent != null) {
5311 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5312 callingUid, targetPkg, clipIntent, mode, needed);
5313 if (newNeeded != null) {
5314 needed = newNeeded;
5315 }
5316 }
5317 }
5318 }
5319 }
5320
5321 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005322 }
5323
5324 /**
5325 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5326 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005327 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5328 UriPermissionOwner owner) {
5329 if (needed != null) {
5330 for (int i=0; i<needed.size(); i++) {
5331 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5332 needed.get(i), needed.flags, owner);
5333 }
5334 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005335 }
5336
5337 void grantUriPermissionFromIntentLocked(int callingUid,
5338 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005339 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005340 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005341 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 return;
5343 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005344
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005345 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 }
5347
5348 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5349 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005350 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 synchronized(this) {
5352 final ProcessRecord r = getRecordForAppLocked(caller);
5353 if (r == null) {
5354 throw new SecurityException("Unable to find app for caller "
5355 + caller
5356 + " when granting permission to uri " + uri);
5357 }
5358 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005359 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 }
5361 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005362 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 }
5364
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005365 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 null);
5367 }
5368 }
5369
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005370 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5372 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5373 HashMap<Uri, UriPermission> perms
5374 = mGrantedUriPermissions.get(perm.uid);
5375 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005376 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005377 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 perms.remove(perm.uri);
5379 if (perms.size() == 0) {
5380 mGrantedUriPermissions.remove(perm.uid);
5381 }
5382 }
5383 }
5384 }
5385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5387 int modeFlags) {
5388 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5389 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5390 if (modeFlags == 0) {
5391 return;
5392 }
5393
Joe Onorato8a9b2202010-02-26 18:56:32 -08005394 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005395 "Revoking all granted permissions to " + uri);
5396
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005397 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398
5399 final String authority = uri.getAuthority();
5400 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005401 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005402 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 if (cpr != null) {
5404 pi = cpr.info;
5405 } else {
5406 try {
5407 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005408 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 } catch (RemoteException ex) {
5410 }
5411 }
5412 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005413 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 return;
5415 }
5416
5417 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005418 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 // Right now, if you are not the original owner of the permission,
5420 // you are not allowed to revoke it.
5421 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5422 throw new SecurityException("Uid " + callingUid
5423 + " does not have permission to uri " + uri);
5424 //}
5425 }
5426
5427 // Go through all of the permissions and remove any that match.
5428 final List<String> SEGMENTS = uri.getPathSegments();
5429 if (SEGMENTS != null) {
5430 final int NS = SEGMENTS.size();
5431 int N = mGrantedUriPermissions.size();
5432 for (int i=0; i<N; i++) {
5433 HashMap<Uri, UriPermission> perms
5434 = mGrantedUriPermissions.valueAt(i);
5435 Iterator<UriPermission> it = perms.values().iterator();
5436 toploop:
5437 while (it.hasNext()) {
5438 UriPermission perm = it.next();
5439 Uri targetUri = perm.uri;
5440 if (!authority.equals(targetUri.getAuthority())) {
5441 continue;
5442 }
5443 List<String> targetSegments = targetUri.getPathSegments();
5444 if (targetSegments == null) {
5445 continue;
5446 }
5447 if (targetSegments.size() < NS) {
5448 continue;
5449 }
5450 for (int j=0; j<NS; j++) {
5451 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5452 continue toploop;
5453 }
5454 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005455 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005456 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 perm.clearModes(modeFlags);
5458 if (perm.modeFlags == 0) {
5459 it.remove();
5460 }
5461 }
5462 if (perms.size() == 0) {
5463 mGrantedUriPermissions.remove(
5464 mGrantedUriPermissions.keyAt(i));
5465 N--;
5466 i--;
5467 }
5468 }
5469 }
5470 }
5471
5472 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5473 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005474 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 synchronized(this) {
5476 final ProcessRecord r = getRecordForAppLocked(caller);
5477 if (r == null) {
5478 throw new SecurityException("Unable to find app for caller "
5479 + caller
5480 + " when revoking permission to uri " + uri);
5481 }
5482 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005483 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 return;
5485 }
5486
5487 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5488 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5489 if (modeFlags == 0) {
5490 return;
5491 }
5492
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005493 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494
5495 final String authority = uri.getAuthority();
5496 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005497 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 if (cpr != null) {
5499 pi = cpr.info;
5500 } else {
5501 try {
5502 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005503 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 } catch (RemoteException ex) {
5505 }
5506 }
5507 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005508 Slog.w(TAG, "No content provider found for permission revoke: "
5509 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 return;
5511 }
5512
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005513 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 }
5515 }
5516
Dianne Hackborn7e269642010-08-25 19:50:20 -07005517 @Override
5518 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005519 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005520 synchronized(this) {
5521 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5522 return owner.getExternalTokenLocked();
5523 }
5524 }
5525
5526 @Override
5527 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5528 Uri uri, int modeFlags) {
5529 synchronized(this) {
5530 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5531 if (owner == null) {
5532 throw new IllegalArgumentException("Unknown owner: " + token);
5533 }
5534 if (fromUid != Binder.getCallingUid()) {
5535 if (Binder.getCallingUid() != Process.myUid()) {
5536 // Only system code can grant URI permissions on behalf
5537 // of other users.
5538 throw new SecurityException("nice try");
5539 }
5540 }
5541 if (targetPkg == null) {
5542 throw new IllegalArgumentException("null target");
5543 }
5544 if (uri == null) {
5545 throw new IllegalArgumentException("null uri");
5546 }
5547
5548 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5549 }
5550 }
5551
5552 @Override
5553 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5554 synchronized(this) {
5555 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5556 if (owner == null) {
5557 throw new IllegalArgumentException("Unknown owner: " + token);
5558 }
5559
5560 if (uri == null) {
5561 owner.removeUriPermissionsLocked(mode);
5562 } else {
5563 owner.removeUriPermissionLocked(uri, mode);
5564 }
5565 }
5566 }
5567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5569 synchronized (this) {
5570 ProcessRecord app =
5571 who != null ? getRecordForAppLocked(who) : null;
5572 if (app == null) return;
5573
5574 Message msg = Message.obtain();
5575 msg.what = WAIT_FOR_DEBUGGER_MSG;
5576 msg.obj = app;
5577 msg.arg1 = waiting ? 1 : 0;
5578 mHandler.sendMessage(msg);
5579 }
5580 }
5581
5582 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005583 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5584 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005586 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005587 outInfo.threshold = homeAppMem;
5588 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5589 outInfo.hiddenAppThreshold = hiddenAppMem;
5590 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005591 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005592 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5593 ProcessList.VISIBLE_APP_ADJ);
5594 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5595 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 }
5597
5598 // =========================================================
5599 // TASK MANAGEMENT
5600 // =========================================================
5601
5602 public List getTasks(int maxNum, int flags,
5603 IThumbnailReceiver receiver) {
5604 ArrayList list = new ArrayList();
5605
5606 PendingThumbnailsRecord pending = null;
5607 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005608 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609
5610 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005611 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5613 + ", receiver=" + receiver);
5614
5615 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5616 != PackageManager.PERMISSION_GRANTED) {
5617 if (receiver != null) {
5618 // If the caller wants to wait for pending thumbnails,
5619 // it ain't gonna get them.
5620 try {
5621 receiver.finished();
5622 } catch (RemoteException ex) {
5623 }
5624 }
5625 String msg = "Permission Denial: getTasks() from pid="
5626 + Binder.getCallingPid()
5627 + ", uid=" + Binder.getCallingUid()
5628 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005629 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 throw new SecurityException(msg);
5631 }
5632
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005633 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005634 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005635 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005636 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 TaskRecord curTask = null;
5638 int numActivities = 0;
5639 int numRunning = 0;
5640 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005641 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005643 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644
5645 // Initialize state for next task if needed.
5646 if (top == null ||
5647 (top.state == ActivityState.INITIALIZING
5648 && top.task == r.task)) {
5649 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 curTask = r.task;
5651 numActivities = numRunning = 0;
5652 }
5653
5654 // Add 'r' into the current task.
5655 numActivities++;
5656 if (r.app != null && r.app.thread != null) {
5657 numRunning++;
5658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659
Joe Onorato8a9b2202010-02-26 18:56:32 -08005660 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 TAG, r.intent.getComponent().flattenToShortString()
5662 + ": task=" + r.task);
5663
5664 // If the next one is a different task, generate a new
5665 // TaskInfo entry for what we have.
5666 if (next == null || next.task != curTask) {
5667 ActivityManager.RunningTaskInfo ci
5668 = new ActivityManager.RunningTaskInfo();
5669 ci.id = curTask.taskId;
5670 ci.baseActivity = r.intent.getComponent();
5671 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005672 if (top.thumbHolder != null) {
5673 ci.description = top.thumbHolder.lastDescription;
5674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 ci.numActivities = numActivities;
5676 ci.numRunning = numRunning;
5677 //System.out.println(
5678 // "#" + maxNum + ": " + " descr=" + ci.description);
5679 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005680 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 TAG, "State=" + top.state + "Idle=" + top.idle
5682 + " app=" + top.app
5683 + " thr=" + (top.app != null ? top.app.thread : null));
5684 if (top.state == ActivityState.RESUMED
5685 || top.state == ActivityState.PAUSING) {
5686 if (top.idle && top.app != null
5687 && top.app.thread != null) {
5688 topRecord = top;
5689 topThumbnail = top.app.thread;
5690 } else {
5691 top.thumbnailNeeded = true;
5692 }
5693 }
5694 if (pending == null) {
5695 pending = new PendingThumbnailsRecord(receiver);
5696 }
5697 pending.pendingRecords.add(top);
5698 }
5699 list.add(ci);
5700 maxNum--;
5701 top = null;
5702 }
5703 }
5704
5705 if (pending != null) {
5706 mPendingThumbnails.add(pending);
5707 }
5708 }
5709
Joe Onorato8a9b2202010-02-26 18:56:32 -08005710 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711
5712 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005713 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005715 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005717 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005718 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 }
5720 }
5721
5722 if (pending == null && receiver != null) {
5723 // In this case all thumbnails were available and the client
5724 // is being asked to be told when the remaining ones come in...
5725 // which is unusually, since the top-most currently running
5726 // activity should never have a canned thumbnail! Oh well.
5727 try {
5728 receiver.finished();
5729 } catch (RemoteException ex) {
5730 }
5731 }
5732
5733 return list;
5734 }
5735
5736 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005737 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005738 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005739 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005740 // Check if the caller is holding permissions for cross-user requests.
5741 if (checkComponentPermission(
5742 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5743 Binder.getCallingPid(), callingUid, -1, true)
5744 != PackageManager.PERMISSION_GRANTED) {
5745 String msg = "Permission Denial: "
5746 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005747 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005748 + "; this requires "
5749 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5750 Slog.w(TAG, msg);
5751 throw new SecurityException(msg);
5752 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005753 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005754 userId = mCurrentUserId;
5755 }
5756 }
5757 }
5758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 synchronized (this) {
5760 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5761 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005762 final boolean detailed = checkCallingPermission(
5763 android.Manifest.permission.GET_DETAILED_TASKS)
5764 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005766 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 final int N = mRecentTasks.size();
5769 ArrayList<ActivityManager.RecentTaskInfo> res
5770 = new ArrayList<ActivityManager.RecentTaskInfo>(
5771 maxNum < N ? maxNum : N);
5772 for (int i=0; i<N && maxNum > 0; i++) {
5773 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005774 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005775 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005776 // Return the entry if desired by the caller. We always return
5777 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005778 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005779 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5780 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005781
Dianne Hackborn905577f2011-09-07 18:31:28 -07005782 if (i == 0
5783 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 || (tr.intent == null)
5785 || ((tr.intent.getFlags()
5786 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5787 ActivityManager.RecentTaskInfo rti
5788 = new ActivityManager.RecentTaskInfo();
5789 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005790 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 rti.baseIntent = new Intent(
5792 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005793 if (!detailed) {
5794 rti.baseIntent.replaceExtras((Bundle)null);
5795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005796 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005797 rti.description = tr.lastDescription;
5798
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005799 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5800 // Check whether this activity is currently available.
5801 try {
5802 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005803 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005804 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005805 continue;
5806 }
5807 } else if (rti.baseIntent != null) {
5808 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005809 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005810 continue;
5811 }
5812 }
5813 } catch (RemoteException e) {
5814 // Will never happen.
5815 }
5816 }
5817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 res.add(rti);
5819 maxNum--;
5820 }
5821 }
5822 return res;
5823 }
5824 }
5825
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005826 private TaskRecord taskForIdLocked(int id) {
5827 final int N = mRecentTasks.size();
5828 for (int i=0; i<N; i++) {
5829 TaskRecord tr = mRecentTasks.get(i);
5830 if (tr.taskId == id) {
5831 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005832 }
5833 }
5834 return null;
5835 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005836
5837 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5838 synchronized (this) {
5839 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5840 "getTaskThumbnails()");
5841 TaskRecord tr = taskForIdLocked(id);
5842 if (tr != null) {
5843 return mMainStack.getTaskThumbnailsLocked(tr);
5844 }
5845 }
5846 return null;
5847 }
5848
5849 public boolean removeSubTask(int taskId, int subTaskIndex) {
5850 synchronized (this) {
5851 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5852 "removeSubTask()");
5853 long ident = Binder.clearCallingIdentity();
5854 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005855 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5856 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005857 } finally {
5858 Binder.restoreCallingIdentity(ident);
5859 }
5860 }
5861 }
5862
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005863 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5864 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005865 Intent baseIntent = new Intent(
5866 tr.intent != null ? tr.intent : tr.affinityIntent);
5867 ComponentName component = baseIntent.getComponent();
5868 if (component == null) {
5869 Slog.w(TAG, "Now component for base intent of task: " + tr);
5870 return;
5871 }
5872
5873 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005874 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005875
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005876 if (killProcesses) {
5877 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005878 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005879 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005880 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5881 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5882 for (int i=0; i<uids.size(); i++) {
5883 ProcessRecord proc = uids.valueAt(i);
5884 if (proc.userId != tr.userId) {
5885 continue;
5886 }
5887 if (!proc.pkgList.contains(pkg)) {
5888 continue;
5889 }
5890 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005891 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005892 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005893
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005894 // Kill the running processes.
5895 for (int i=0; i<procs.size(); i++) {
5896 ProcessRecord pr = procs.get(i);
5897 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5898 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5899 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5900 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005901 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005902 Process.killProcessQuiet(pr.pid);
5903 } else {
5904 pr.waitingToKill = "remove task";
5905 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005906 }
5907 }
5908 }
5909
5910 public boolean removeTask(int taskId, int flags) {
5911 synchronized (this) {
5912 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5913 "removeTask()");
5914 long ident = Binder.clearCallingIdentity();
5915 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005916 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5917 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005918 if (r != null) {
5919 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005920 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005921 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005922 } else {
5923 TaskRecord tr = null;
5924 int i=0;
5925 while (i < mRecentTasks.size()) {
5926 TaskRecord t = mRecentTasks.get(i);
5927 if (t.taskId == taskId) {
5928 tr = t;
5929 break;
5930 }
5931 i++;
5932 }
5933 if (tr != null) {
5934 if (tr.numActivities <= 0) {
5935 // Caller is just removing a recent task that is
5936 // not actively running. That is easy!
5937 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005938 cleanUpRemovedTaskLocked(tr, flags);
5939 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005940 } else {
5941 Slog.w(TAG, "removeTask: task " + taskId
5942 + " does not have activities to remove, "
5943 + " but numActivities=" + tr.numActivities
5944 + ": " + tr);
5945 }
5946 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005947 }
5948 } finally {
5949 Binder.restoreCallingIdentity(ident);
5950 }
5951 }
5952 return false;
5953 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5956 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005957 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 TaskRecord jt = startTask;
5959
5960 // First look backwards
5961 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005962 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 if (r.task != jt) {
5964 jt = r.task;
5965 if (affinity.equals(jt.affinity)) {
5966 return j;
5967 }
5968 }
5969 }
5970
5971 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005972 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 jt = startTask;
5974 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005975 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 if (r.task != jt) {
5977 if (affinity.equals(jt.affinity)) {
5978 return j;
5979 }
5980 jt = r.task;
5981 }
5982 }
5983
5984 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005985 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 return N-1;
5987 }
5988
5989 return -1;
5990 }
5991
5992 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005993 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005995 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5997 "moveTaskToFront()");
5998
5999 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006000 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6001 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006002 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006003 return;
6004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 final long origId = Binder.clearCallingIdentity();
6006 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006007 TaskRecord tr = taskForIdLocked(task);
6008 if (tr != null) {
6009 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6010 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006012 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6013 // Caller wants the home activity moved with it. To accomplish this,
6014 // we'll just move the home task to the top first.
6015 mMainStack.moveHomeToFrontLocked();
6016 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006017 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006018 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006020 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6021 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006023 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6024 mMainStack.mUserLeaving = true;
6025 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006026 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6027 // Caller wants the home activity moved with it. To accomplish this,
6028 // we'll just move the home task to the top first.
6029 mMainStack.moveHomeToFrontLocked();
6030 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006031 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 return;
6033 }
6034 }
6035 } finally {
6036 Binder.restoreCallingIdentity(origId);
6037 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006038 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 }
6040 }
6041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 public void moveTaskToBack(int task) {
6043 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6044 "moveTaskToBack()");
6045
6046 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006047 if (mMainStack.mResumedActivity != null
6048 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006049 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6050 Binder.getCallingUid(), "Task to back")) {
6051 return;
6052 }
6053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006055 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 Binder.restoreCallingIdentity(origId);
6057 }
6058 }
6059
6060 /**
6061 * Moves an activity, and all of the other activities within the same task, to the bottom
6062 * of the history stack. The activity's order within the task is unchanged.
6063 *
6064 * @param token A reference to the activity we wish to move
6065 * @param nonRoot If false then this only works if the activity is the root
6066 * of a task; if true it will work for any activity in a task.
6067 * @return Returns true if the move completed, false if not.
6068 */
6069 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006070 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 synchronized(this) {
6072 final long origId = Binder.clearCallingIdentity();
6073 int taskId = getTaskForActivityLocked(token, !nonRoot);
6074 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006075 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 }
6077 Binder.restoreCallingIdentity(origId);
6078 }
6079 return false;
6080 }
6081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 public void moveTaskBackwards(int task) {
6083 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6084 "moveTaskBackwards()");
6085
6086 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006087 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6088 Binder.getCallingUid(), "Task backwards")) {
6089 return;
6090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 final long origId = Binder.clearCallingIdentity();
6092 moveTaskBackwardsLocked(task);
6093 Binder.restoreCallingIdentity(origId);
6094 }
6095 }
6096
6097 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006098 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 }
6100
6101 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6102 synchronized(this) {
6103 return getTaskForActivityLocked(token, onlyRoot);
6104 }
6105 }
6106
6107 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006108 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 TaskRecord lastTask = null;
6110 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006111 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006112 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 if (!onlyRoot || lastTask != r.task) {
6114 return r.task.taskId;
6115 }
6116 return -1;
6117 }
6118 lastTask = r.task;
6119 }
6120
6121 return -1;
6122 }
6123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 // =========================================================
6125 // THUMBNAILS
6126 // =========================================================
6127
6128 public void reportThumbnail(IBinder token,
6129 Bitmap thumbnail, CharSequence description) {
6130 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6131 final long origId = Binder.clearCallingIdentity();
6132 sendPendingThumbnail(null, token, thumbnail, description, true);
6133 Binder.restoreCallingIdentity(origId);
6134 }
6135
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006136 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 Bitmap thumbnail, CharSequence description, boolean always) {
6138 TaskRecord task = null;
6139 ArrayList receivers = null;
6140
6141 //System.out.println("Send pending thumbnail: " + r);
6142
6143 synchronized(this) {
6144 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006145 r = mMainStack.isInStackLocked(token);
6146 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 return;
6148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006150 if (thumbnail == null && r.thumbHolder != null) {
6151 thumbnail = r.thumbHolder.lastThumbnail;
6152 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 }
6154 if (thumbnail == null && !always) {
6155 // If there is no thumbnail, and this entry is not actually
6156 // going away, then abort for now and pick up the next
6157 // thumbnail we get.
6158 return;
6159 }
6160 task = r.task;
6161
6162 int N = mPendingThumbnails.size();
6163 int i=0;
6164 while (i<N) {
6165 PendingThumbnailsRecord pr =
6166 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6167 //System.out.println("Looking in " + pr.pendingRecords);
6168 if (pr.pendingRecords.remove(r)) {
6169 if (receivers == null) {
6170 receivers = new ArrayList();
6171 }
6172 receivers.add(pr);
6173 if (pr.pendingRecords.size() == 0) {
6174 pr.finished = true;
6175 mPendingThumbnails.remove(i);
6176 N--;
6177 continue;
6178 }
6179 }
6180 i++;
6181 }
6182 }
6183
6184 if (receivers != null) {
6185 final int N = receivers.size();
6186 for (int i=0; i<N; i++) {
6187 try {
6188 PendingThumbnailsRecord pr =
6189 (PendingThumbnailsRecord)receivers.get(i);
6190 pr.receiver.newThumbnail(
6191 task != null ? task.taskId : -1, thumbnail, description);
6192 if (pr.finished) {
6193 pr.receiver.finished();
6194 }
6195 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006196 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
6198 }
6199 }
6200 }
6201
6202 // =========================================================
6203 // CONTENT PROVIDERS
6204 // =========================================================
6205
Jeff Brown10e89712011-07-08 18:52:57 -07006206 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6207 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006209 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006210 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006211 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 } catch (RemoteException ex) {
6213 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006214 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006215 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6216 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006218 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 for (int i=0; i<N; i++) {
6220 ProviderInfo cpi =
6221 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006222 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6223 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006224 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006225 // This is a singleton provider, but a user besides the
6226 // default user is asking to initialize a process it runs
6227 // in... well, no, it doesn't actually run in this process,
6228 // it runs in the process of the default user. Get rid of it.
6229 providers.remove(i);
6230 N--;
6231 continue;
6232 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006233
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006234 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006235 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006237 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006238 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006240 if (DEBUG_MU)
6241 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 app.pubProviders.put(cpi.name, cpr);
6243 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006244 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 }
6246 }
6247 return providers;
6248 }
6249
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006250 /**
6251 * Check if {@link ProcessRecord} has a possible chance at accessing the
6252 * given {@link ProviderInfo}. Final permission checking is always done
6253 * in {@link ContentProvider}.
6254 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006256 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006258 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006260 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006261 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 return null;
6263 }
6264 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006265 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 == PackageManager.PERMISSION_GRANTED) {
6267 return null;
6268 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006269
6270 PathPermission[] pps = cpi.pathPermissions;
6271 if (pps != null) {
6272 int i = pps.length;
6273 while (i > 0) {
6274 i--;
6275 PathPermission pp = pps[i];
6276 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006277 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006278 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006279 return null;
6280 }
6281 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006282 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006283 == PackageManager.PERMISSION_GRANTED) {
6284 return null;
6285 }
6286 }
6287 }
6288
Dianne Hackbornb424b632010-08-18 15:59:05 -07006289 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6290 if (perms != null) {
6291 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6292 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6293 return null;
6294 }
6295 }
6296 }
6297
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006298 String msg;
6299 if (!cpi.exported) {
6300 msg = "Permission Denial: opening provider " + cpi.name
6301 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6302 + ", uid=" + callingUid + ") that is not exported from uid "
6303 + cpi.applicationInfo.uid;
6304 } else {
6305 msg = "Permission Denial: opening provider " + cpi.name
6306 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6307 + ", uid=" + callingUid + ") requires "
6308 + cpi.readPermission + " or " + cpi.writePermission;
6309 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006310 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 return msg;
6312 }
6313
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006314 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6315 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006316 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006317 for (int i=0; i<r.conProviders.size(); i++) {
6318 ContentProviderConnection conn = r.conProviders.get(i);
6319 if (conn.provider == cpr) {
6320 if (DEBUG_PROVIDER) Slog.v(TAG,
6321 "Adding provider requested by "
6322 + r.processName + " from process "
6323 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6324 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6325 if (stable) {
6326 conn.stableCount++;
6327 conn.numStableIncs++;
6328 } else {
6329 conn.unstableCount++;
6330 conn.numUnstableIncs++;
6331 }
6332 return conn;
6333 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006334 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006335 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6336 if (stable) {
6337 conn.stableCount = 1;
6338 conn.numStableIncs = 1;
6339 } else {
6340 conn.unstableCount = 1;
6341 conn.numUnstableIncs = 1;
6342 }
6343 cpr.connections.add(conn);
6344 r.conProviders.add(conn);
6345 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006346 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006347 cpr.addExternalProcessHandleLocked(externalProcessToken);
6348 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006349 }
6350
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006351 boolean decProviderCountLocked(ContentProviderConnection conn,
6352 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6353 if (conn != null) {
6354 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006355 if (DEBUG_PROVIDER) Slog.v(TAG,
6356 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006357 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006358 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006359 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6360 if (stable) {
6361 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006362 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006363 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006364 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006365 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6366 cpr.connections.remove(conn);
6367 conn.client.conProviders.remove(conn);
6368 return true;
6369 }
6370 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006371 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006372 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006373 return false;
6374 }
6375
Amith Yamasani742a6712011-05-04 14:49:28 -07006376 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006377 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006379 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 ProviderInfo cpi = null;
6381
6382 synchronized(this) {
6383 ProcessRecord r = null;
6384 if (caller != null) {
6385 r = getRecordForAppLocked(caller);
6386 if (r == null) {
6387 throw new SecurityException(
6388 "Unable to find app for caller " + caller
6389 + " (pid=" + Binder.getCallingPid()
6390 + ") when getting content provider " + name);
6391 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006392 if (r.userId != userId) {
6393 throw new SecurityException("Calling requested user " + userId
6394 + " but app is user " + r.userId);
6395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 }
6397
6398 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006399 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006400 boolean providerRunning = cpr != null;
6401 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006403 String msg;
6404 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6405 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 }
6407
6408 if (r != null && cpr.canRunHere(r)) {
6409 // This provider has been published or is in the process
6410 // of being published... but it is also allowed to run
6411 // in the caller's process, so don't make a connection
6412 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006413 ContentProviderHolder holder = cpr.newHolder(null);
6414 // don't give caller the provider object, it needs
6415 // to make its own.
6416 holder.provider = null;
6417 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 }
6419
6420 final long origId = Binder.clearCallingIdentity();
6421
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006422 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006424 conn = incProviderCountLocked(r, cpr, token, stable);
6425 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006426 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006427 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006428 // make sure to count it as being accessed and thus
6429 // back up on the LRU list. This is good because
6430 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006431 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006432 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006433 }
6434
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006435 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006436 if (false) {
6437 if (cpr.name.flattenToShortString().equals(
6438 "com.android.providers.calendar/.CalendarProvider2")) {
6439 Slog.v(TAG, "****************** KILLING "
6440 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006441 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006442 }
6443 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006444 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006445 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6446 // NOTE: there is still a race here where a signal could be
6447 // pending on the process even though we managed to update its
6448 // adj level. Not sure what to do about this, but at least
6449 // the race is now smaller.
6450 if (!success) {
6451 // Uh oh... it looks like the provider's process
6452 // has been killed on us. We need to wait for a new
6453 // process to be started, and make sure its death
6454 // doesn't kill our process.
6455 Slog.i(TAG,
6456 "Existing provider " + cpr.name.flattenToShortString()
6457 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006458 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006459 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006460 if (!lastRef) {
6461 // This wasn't the last ref our process had on
6462 // the provider... we have now been killed, bail.
6463 return null;
6464 }
6465 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006466 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 }
6469
6470 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006473 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006474 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006476 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006477 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006478 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 } catch (RemoteException ex) {
6480 }
6481 if (cpi == null) {
6482 return null;
6483 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006484 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6485 cpi.name, cpi.flags);
6486 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006487 userId = 0;
6488 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006489 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006490
Dianne Hackbornb424b632010-08-18 15:59:05 -07006491 String msg;
6492 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6493 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 }
6495
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006496 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006497 && !cpi.processName.equals("system")) {
6498 // If this content provider does not run in the system
6499 // process, and the system is not yet ready to run other
6500 // processes, then fail fast instead of hanging.
6501 throw new IllegalArgumentException(
6502 "Attempt to launch content provider before system ready");
6503 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006504
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006505 // Make sure that the user who owns this provider is started. If not,
6506 // we don't want to allow it to run.
6507 if (mStartedUsers.get(userId) == null) {
6508 Slog.w(TAG, "Unable to launch app "
6509 + cpi.applicationInfo.packageName + "/"
6510 + cpi.applicationInfo.uid + " for provider "
6511 + name + ": user " + userId + " is stopped");
6512 return null;
6513 }
6514
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006515 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006516 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517 final boolean firstClass = cpr == null;
6518 if (firstClass) {
6519 try {
6520 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006521 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 getApplicationInfo(
6523 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006524 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006526 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 + cpi.name);
6528 return null;
6529 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006530 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006531 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 } catch (RemoteException ex) {
6533 // pm is in same process, this will never happen.
6534 }
6535 }
6536
6537 if (r != null && cpr.canRunHere(r)) {
6538 // If this is a multiprocess provider, then just return its
6539 // info and allow the caller to instantiate it. Only do
6540 // this if the provider is the same user as the caller's
6541 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006542 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 }
6544
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006545 if (DEBUG_PROVIDER) {
6546 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006547 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006548 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 }
6550
6551 // This is single process, and our app is now connecting to it.
6552 // See if we are already in the process of launching this
6553 // provider.
6554 final int N = mLaunchingProviders.size();
6555 int i;
6556 for (i=0; i<N; i++) {
6557 if (mLaunchingProviders.get(i) == cpr) {
6558 break;
6559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 }
6561
6562 // If the provider is not already being launched, then get it
6563 // started.
6564 if (i >= N) {
6565 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006566
6567 try {
6568 // Content provider is now in use, its package can't be stopped.
6569 try {
6570 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006571 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006572 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006573 } catch (IllegalArgumentException e) {
6574 Slog.w(TAG, "Failed trying to unstop package "
6575 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006576 }
6577
6578 ProcessRecord proc = startProcessLocked(cpi.processName,
6579 cpr.appInfo, false, 0, "content provider",
6580 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006581 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006582 if (proc == null) {
6583 Slog.w(TAG, "Unable to launch app "
6584 + cpi.applicationInfo.packageName + "/"
6585 + cpi.applicationInfo.uid + " for provider "
6586 + name + ": process is bad");
6587 return null;
6588 }
6589 cpr.launchingApp = proc;
6590 mLaunchingProviders.add(cpr);
6591 } finally {
6592 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 }
6595
6596 // Make sure the provider is published (the same provider class
6597 // may be published under multiple names).
6598 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006599 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006601
Amith Yamasani742a6712011-05-04 14:49:28 -07006602 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006603 conn = incProviderCountLocked(r, cpr, token, stable);
6604 if (conn != null) {
6605 conn.waiting = true;
6606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 }
6608 }
6609
6610 // Wait for the provider to be published...
6611 synchronized (cpr) {
6612 while (cpr.provider == null) {
6613 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006614 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 + cpi.applicationInfo.packageName + "/"
6616 + cpi.applicationInfo.uid + " for provider "
6617 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006618 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619 cpi.applicationInfo.packageName,
6620 cpi.applicationInfo.uid, name);
6621 return null;
6622 }
6623 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006624 if (DEBUG_MU) {
6625 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6626 + cpr.launchingApp);
6627 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006628 if (conn != null) {
6629 conn.waiting = true;
6630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 cpr.wait();
6632 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006633 } finally {
6634 if (conn != null) {
6635 conn.waiting = false;
6636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 }
6638 }
6639 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006640 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 }
6642
6643 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006644 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006645 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 if (caller == null) {
6647 String msg = "null IApplicationThread when getting content provider "
6648 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006649 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 throw new SecurityException(msg);
6651 }
6652
Dianne Hackborn41203752012-08-31 14:05:51 -07006653 return getContentProviderImpl(caller, name, null, stable,
6654 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 }
6656
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006657 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6658 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6659 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006660 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006661 }
6662
Dianne Hackborn41203752012-08-31 14:05:51 -07006663 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6664 IBinder token, int userId) {
6665 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 }
6667
6668 /**
6669 * Drop a content provider from a ProcessRecord's bookkeeping
6670 * @param cpr
6671 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006672 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006673 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006675 ContentProviderConnection conn;
6676 try {
6677 conn = (ContentProviderConnection)connection;
6678 } catch (ClassCastException e) {
6679 String msg ="removeContentProvider: " + connection
6680 + " not a ContentProviderConnection";
6681 Slog.w(TAG, msg);
6682 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006684 if (conn == null) {
6685 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006687 if (decProviderCountLocked(conn, null, null, stable)) {
6688 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 }
6691 }
6692
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006693 public void removeContentProviderExternal(String name, IBinder token) {
6694 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6695 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006696 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006697 }
6698
Dianne Hackborn41203752012-08-31 14:05:51 -07006699 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006701 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 if(cpr == null) {
6703 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006704 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 return;
6706 }
6707
6708 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006709 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006710 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006711 if (localCpr.hasExternalProcessHandles()) {
6712 if (localCpr.removeExternalProcessHandleLocked(token)) {
6713 updateOomAdjLocked();
6714 } else {
6715 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6716 + " with no external reference for token: "
6717 + token + ".");
6718 }
6719 } else {
6720 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6721 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 }
6724 }
6725
6726 public final void publishContentProviders(IApplicationThread caller,
6727 List<ContentProviderHolder> providers) {
6728 if (providers == null) {
6729 return;
6730 }
6731
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006732 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006733 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006735 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006736 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 if (r == null) {
6738 throw new SecurityException(
6739 "Unable to find app for caller " + caller
6740 + " (pid=" + Binder.getCallingPid()
6741 + ") when publishing content providers");
6742 }
6743
6744 final long origId = Binder.clearCallingIdentity();
6745
6746 final int N = providers.size();
6747 for (int i=0; i<N; i++) {
6748 ContentProviderHolder src = providers.get(i);
6749 if (src == null || src.info == null || src.provider == null) {
6750 continue;
6751 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006752 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006753 if (DEBUG_MU)
6754 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006756 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006757 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 String names[] = dst.info.authority.split(";");
6759 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006760 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 }
6762
6763 int NL = mLaunchingProviders.size();
6764 int j;
6765 for (j=0; j<NL; j++) {
6766 if (mLaunchingProviders.get(j) == dst) {
6767 mLaunchingProviders.remove(j);
6768 j--;
6769 NL--;
6770 }
6771 }
6772 synchronized (dst) {
6773 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006774 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 dst.notifyAll();
6776 }
6777 updateOomAdjLocked(r);
6778 }
6779 }
6780
6781 Binder.restoreCallingIdentity(origId);
6782 }
6783 }
6784
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006785 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6786 ContentProviderConnection conn;
6787 try {
6788 conn = (ContentProviderConnection)connection;
6789 } catch (ClassCastException e) {
6790 String msg ="refContentProvider: " + connection
6791 + " not a ContentProviderConnection";
6792 Slog.w(TAG, msg);
6793 throw new IllegalArgumentException(msg);
6794 }
6795 if (conn == null) {
6796 throw new NullPointerException("connection is null");
6797 }
6798
6799 synchronized (this) {
6800 if (stable > 0) {
6801 conn.numStableIncs += stable;
6802 }
6803 stable = conn.stableCount + stable;
6804 if (stable < 0) {
6805 throw new IllegalStateException("stableCount < 0: " + stable);
6806 }
6807
6808 if (unstable > 0) {
6809 conn.numUnstableIncs += unstable;
6810 }
6811 unstable = conn.unstableCount + unstable;
6812 if (unstable < 0) {
6813 throw new IllegalStateException("unstableCount < 0: " + unstable);
6814 }
6815
6816 if ((stable+unstable) <= 0) {
6817 throw new IllegalStateException("ref counts can't go to zero here: stable="
6818 + stable + " unstable=" + unstable);
6819 }
6820 conn.stableCount = stable;
6821 conn.unstableCount = unstable;
6822 return !conn.dead;
6823 }
6824 }
6825
6826 public void unstableProviderDied(IBinder connection) {
6827 ContentProviderConnection conn;
6828 try {
6829 conn = (ContentProviderConnection)connection;
6830 } catch (ClassCastException e) {
6831 String msg ="refContentProvider: " + connection
6832 + " not a ContentProviderConnection";
6833 Slog.w(TAG, msg);
6834 throw new IllegalArgumentException(msg);
6835 }
6836 if (conn == null) {
6837 throw new NullPointerException("connection is null");
6838 }
6839
6840 // Safely retrieve the content provider associated with the connection.
6841 IContentProvider provider;
6842 synchronized (this) {
6843 provider = conn.provider.provider;
6844 }
6845
6846 if (provider == null) {
6847 // Um, yeah, we're way ahead of you.
6848 return;
6849 }
6850
6851 // Make sure the caller is being honest with us.
6852 if (provider.asBinder().pingBinder()) {
6853 // Er, no, still looks good to us.
6854 synchronized (this) {
6855 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6856 + " says " + conn + " died, but we don't agree");
6857 return;
6858 }
6859 }
6860
6861 // Well look at that! It's dead!
6862 synchronized (this) {
6863 if (conn.provider.provider != provider) {
6864 // But something changed... good enough.
6865 return;
6866 }
6867
6868 ProcessRecord proc = conn.provider.proc;
6869 if (proc == null || proc.thread == null) {
6870 // Seems like the process is already cleaned up.
6871 return;
6872 }
6873
6874 // As far as we're concerned, this is just like receiving a
6875 // death notification... just a bit prematurely.
6876 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6877 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006878 final long ident = Binder.clearCallingIdentity();
6879 try {
6880 appDiedLocked(proc, proc.pid, proc.thread);
6881 } finally {
6882 Binder.restoreCallingIdentity(ident);
6883 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006884 }
6885 }
6886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006888 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006889 synchronized (mSelf) {
6890 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6891 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006892 if (providers != null) {
6893 for (int i=providers.size()-1; i>=0; i--) {
6894 ProviderInfo pi = (ProviderInfo)providers.get(i);
6895 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6896 Slog.w(TAG, "Not installing system proc provider " + pi.name
6897 + ": not system .apk");
6898 providers.remove(i);
6899 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006900 }
6901 }
6902 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006903 if (providers != null) {
6904 mSystemThread.installSystemProviders(providers);
6905 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006906
6907 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006908
6909 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006910 }
6911
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006912 /**
6913 * Allows app to retrieve the MIME type of a URI without having permission
6914 * to access its content provider.
6915 *
6916 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6917 *
6918 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6919 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6920 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006921 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006922 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006923 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
6924 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006925 final String name = uri.getAuthority();
6926 final long ident = Binder.clearCallingIdentity();
6927 ContentProviderHolder holder = null;
6928
6929 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006930 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006931 if (holder != null) {
6932 return holder.provider.getType(uri);
6933 }
6934 } catch (RemoteException e) {
6935 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6936 return null;
6937 } finally {
6938 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006939 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006940 }
6941 Binder.restoreCallingIdentity(ident);
6942 }
6943
6944 return null;
6945 }
6946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 // =========================================================
6948 // GLOBAL MANAGEMENT
6949 // =========================================================
6950
6951 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006952 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006953 String proc = customProcess != null ? customProcess : info.processName;
6954 BatteryStatsImpl.Uid.Proc ps = null;
6955 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006956 int uid = info.uid;
6957 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006958 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006959 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6960 uid = 0;
6961 while (true) {
6962 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6963 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6964 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6965 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006966 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006967 mNextIsolatedProcessUid++;
6968 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6969 // No process for this uid, use it.
6970 break;
6971 }
6972 stepsLeft--;
6973 if (stepsLeft <= 0) {
6974 return null;
6975 }
6976 }
6977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 synchronized (stats) {
6979 ps = stats.getProcessStatsLocked(info.uid, proc);
6980 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006981 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006982 }
6983
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006984 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6985 ProcessRecord app;
6986 if (!isolated) {
6987 app = getProcessRecordLocked(info.processName, info.uid);
6988 } else {
6989 app = null;
6990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991
6992 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006993 app = newProcessRecordLocked(null, info, null, isolated);
6994 mProcessNames.put(info.processName, app.uid, app);
6995 if (isolated) {
6996 mIsolatedProcesses.put(app.uid, app);
6997 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006998 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006999 }
7000
Dianne Hackborne7f97212011-02-24 14:40:20 -08007001 // This package really, really can not be stopped.
7002 try {
7003 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007004 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007005 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007006 } catch (IllegalArgumentException e) {
7007 Slog.w(TAG, "Failed trying to unstop package "
7008 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007009 }
7010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7012 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7013 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007014 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 }
7016 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7017 mPersistentStartingProcesses.add(app);
7018 startProcessLocked(app, "added application", app.processName);
7019 }
7020
7021 return app;
7022 }
7023
7024 public void unhandledBack() {
7025 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7026 "unhandledBack()");
7027
7028 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007029 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007030 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 TAG, "Performing unhandledBack(): stack size = " + count);
7032 if (count > 1) {
7033 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007034 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007035 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 Binder.restoreCallingIdentity(origId);
7037 }
7038 }
7039 }
7040
7041 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007042 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007043 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007045 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 ParcelFileDescriptor pfd = null;
7047 if (cph != null) {
7048 // We record the binder invoker's uid in thread-local storage before
7049 // going to the content provider to open the file. Later, in the code
7050 // that handles all permissions checks, we look for this uid and use
7051 // that rather than the Activity Manager's own uid. The effect is that
7052 // we do the check against the caller's permissions even though it looks
7053 // to the content provider like the Activity Manager itself is making
7054 // the request.
7055 sCallerIdentity.set(new Identity(
7056 Binder.getCallingPid(), Binder.getCallingUid()));
7057 try {
7058 pfd = cph.provider.openFile(uri, "r");
7059 } catch (FileNotFoundException e) {
7060 // do nothing; pfd will be returned null
7061 } finally {
7062 // Ensure that whatever happens, we clean up the identity state
7063 sCallerIdentity.remove();
7064 }
7065
7066 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007067 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007069 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 }
7071 return pfd;
7072 }
7073
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007074 // Actually is sleeping or shutting down or whatever else in the future
7075 // is an inactive state.
7076 public boolean isSleeping() {
7077 return mSleeping || mShuttingDown;
7078 }
7079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007081 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7082 != PackageManager.PERMISSION_GRANTED) {
7083 throw new SecurityException("Requires permission "
7084 + android.Manifest.permission.DEVICE_POWER);
7085 }
7086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007088 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007089 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007091 if (!mSleeping) {
7092 mSleeping = true;
7093 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007094
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007095 // Initialize the wake times of all processes.
7096 checkExcessivePowerUsageLocked(false);
7097 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7098 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7099 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 }
7102 }
7103
Dianne Hackborn55280a92009-05-07 15:53:46 -07007104 public boolean shutdown(int timeout) {
7105 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7106 != PackageManager.PERMISSION_GRANTED) {
7107 throw new SecurityException("Requires permission "
7108 + android.Manifest.permission.SHUTDOWN);
7109 }
7110
7111 boolean timedout = false;
7112
7113 synchronized(this) {
7114 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007115 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007116
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007117 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007118 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007119 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007120 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007121 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007122 long delay = endTime - System.currentTimeMillis();
7123 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007124 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007125 timedout = true;
7126 break;
7127 }
7128 try {
7129 this.wait();
7130 } catch (InterruptedException e) {
7131 }
7132 }
7133 }
7134 }
7135
7136 mUsageStatsService.shutdown();
7137 mBatteryStatsService.shutdown();
7138
7139 return timedout;
7140 }
7141
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007142 public final void activitySlept(IBinder token) {
7143 if (localLOGV) Slog.v(
7144 TAG, "Activity slept: token=" + token);
7145
7146 ActivityRecord r = null;
7147
7148 final long origId = Binder.clearCallingIdentity();
7149
7150 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007151 r = mMainStack.isInStackLocked(token);
7152 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007153 mMainStack.activitySleptLocked(r);
7154 }
7155 }
7156
7157 Binder.restoreCallingIdentity(origId);
7158 }
7159
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007160 private void comeOutOfSleepIfNeededLocked() {
7161 if (!mWentToSleep && !mLockScreenShown) {
7162 if (mSleeping) {
7163 mSleeping = false;
7164 mMainStack.awakeFromSleepingLocked();
7165 mMainStack.resumeTopActivityLocked(null);
7166 }
7167 }
7168 }
7169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007171 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7172 != PackageManager.PERMISSION_GRANTED) {
7173 throw new SecurityException("Requires permission "
7174 + android.Manifest.permission.DEVICE_POWER);
7175 }
7176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007178 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007179 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007180 comeOutOfSleepIfNeededLocked();
7181 }
7182 }
7183
Jeff Brownc042ee22012-05-08 13:03:42 -07007184 private void updateEventDispatchingLocked() {
7185 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7186 }
7187
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007188 public void setLockScreenShown(boolean shown) {
7189 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7190 != PackageManager.PERMISSION_GRANTED) {
7191 throw new SecurityException("Requires permission "
7192 + android.Manifest.permission.DEVICE_POWER);
7193 }
7194
7195 synchronized(this) {
7196 mLockScreenShown = shown;
7197 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198 }
7199 }
7200
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007201 public void stopAppSwitches() {
7202 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7203 != PackageManager.PERMISSION_GRANTED) {
7204 throw new SecurityException("Requires permission "
7205 + android.Manifest.permission.STOP_APP_SWITCHES);
7206 }
7207
7208 synchronized(this) {
7209 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7210 + APP_SWITCH_DELAY_TIME;
7211 mDidAppSwitch = false;
7212 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7213 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7214 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7215 }
7216 }
7217
7218 public void resumeAppSwitches() {
7219 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7220 != PackageManager.PERMISSION_GRANTED) {
7221 throw new SecurityException("Requires permission "
7222 + android.Manifest.permission.STOP_APP_SWITCHES);
7223 }
7224
7225 synchronized(this) {
7226 // Note that we don't execute any pending app switches... we will
7227 // let those wait until either the timeout, or the next start
7228 // activity request.
7229 mAppSwitchesAllowedTime = 0;
7230 }
7231 }
7232
7233 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7234 String name) {
7235 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7236 return true;
7237 }
7238
7239 final int perm = checkComponentPermission(
7240 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007241 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007242 if (perm == PackageManager.PERMISSION_GRANTED) {
7243 return true;
7244 }
7245
Joe Onorato8a9b2202010-02-26 18:56:32 -08007246 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007247 return false;
7248 }
7249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 public void setDebugApp(String packageName, boolean waitForDebugger,
7251 boolean persistent) {
7252 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7253 "setDebugApp()");
7254
7255 // Note that this is not really thread safe if there are multiple
7256 // callers into it at the same time, but that's not a situation we
7257 // care about.
7258 if (persistent) {
7259 final ContentResolver resolver = mContext.getContentResolver();
7260 Settings.System.putString(
7261 resolver, Settings.System.DEBUG_APP,
7262 packageName);
7263 Settings.System.putInt(
7264 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7265 waitForDebugger ? 1 : 0);
7266 }
7267
7268 synchronized (this) {
7269 if (!persistent) {
7270 mOrigDebugApp = mDebugApp;
7271 mOrigWaitForDebugger = mWaitForDebugger;
7272 }
7273 mDebugApp = packageName;
7274 mWaitForDebugger = waitForDebugger;
7275 mDebugTransient = !persistent;
7276 if (packageName != null) {
7277 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007278 forceStopPackageLocked(packageName, -1, false, false, true, true,
7279 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 Binder.restoreCallingIdentity(origId);
7281 }
7282 }
7283 }
7284
Siva Velusamy92a8b222012-03-09 16:24:04 -08007285 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7286 synchronized (this) {
7287 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7288 if (!isDebuggable) {
7289 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7290 throw new SecurityException("Process not debuggable: " + app.packageName);
7291 }
7292 }
7293
7294 mOpenGlTraceApp = processName;
7295 }
7296 }
7297
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007298 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7299 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7300 synchronized (this) {
7301 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7302 if (!isDebuggable) {
7303 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7304 throw new SecurityException("Process not debuggable: " + app.packageName);
7305 }
7306 }
7307 mProfileApp = processName;
7308 mProfileFile = profileFile;
7309 if (mProfileFd != null) {
7310 try {
7311 mProfileFd.close();
7312 } catch (IOException e) {
7313 }
7314 mProfileFd = null;
7315 }
7316 mProfileFd = profileFd;
7317 mProfileType = 0;
7318 mAutoStopProfiler = autoStopProfiler;
7319 }
7320 }
7321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 public void setAlwaysFinish(boolean enabled) {
7323 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7324 "setAlwaysFinish()");
7325
7326 Settings.System.putInt(
7327 mContext.getContentResolver(),
7328 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7329
7330 synchronized (this) {
7331 mAlwaysFinishActivities = enabled;
7332 }
7333 }
7334
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007335 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007337 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007339 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 }
7341 }
7342
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007343 public boolean isUserAMonkey() {
7344 // For now the fact that there is a controller implies
7345 // we have a monkey.
7346 synchronized (this) {
7347 return mController != null;
7348 }
7349 }
7350
Jeff Sharkeya4620792011-05-20 15:29:23 -07007351 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007352 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7353 "registerProcessObserver()");
7354 synchronized (this) {
7355 mProcessObservers.register(observer);
7356 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007357 }
7358
7359 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007360 synchronized (this) {
7361 mProcessObservers.unregister(observer);
7362 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007363 }
7364
Daniel Sandler69a48172010-06-23 16:29:36 -04007365 public void setImmersive(IBinder token, boolean immersive) {
7366 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007367 ActivityRecord r = mMainStack.isInStackLocked(token);
7368 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007369 throw new IllegalArgumentException();
7370 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007371 r.immersive = immersive;
7372 }
7373 }
7374
7375 public boolean isImmersive(IBinder token) {
7376 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007377 ActivityRecord r = mMainStack.isInStackLocked(token);
7378 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007379 throw new IllegalArgumentException();
7380 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007381 return r.immersive;
7382 }
7383 }
7384
7385 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007386 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007387 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007388 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007389 return (r != null) ? r.immersive : false;
7390 }
7391 }
7392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 public final void enterSafeMode() {
7394 synchronized(this) {
7395 // It only makes sense to do this before the system is ready
7396 // and started launching other packages.
7397 if (!mSystemReady) {
7398 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007399 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 } catch (RemoteException e) {
7401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 }
7403 }
7404 }
7405
Jeff Brownb09abc12011-01-13 21:08:27 -08007406 public final void showSafeModeOverlay() {
7407 View v = LayoutInflater.from(mContext).inflate(
7408 com.android.internal.R.layout.safe_mode, null);
7409 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7410 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7411 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7412 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007413 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007414 lp.format = v.getBackground().getOpacity();
7415 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7416 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7417 ((WindowManager)mContext.getSystemService(
7418 Context.WINDOW_SERVICE)).addView(v, lp);
7419 }
7420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 public void noteWakeupAlarm(IIntentSender sender) {
7422 if (!(sender instanceof PendingIntentRecord)) {
7423 return;
7424 }
7425 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7426 synchronized (stats) {
7427 if (mBatteryStatsService.isOnBattery()) {
7428 mBatteryStatsService.enforceCallingPermission();
7429 PendingIntentRecord rec = (PendingIntentRecord)sender;
7430 int MY_UID = Binder.getCallingUid();
7431 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7432 BatteryStatsImpl.Uid.Pkg pkg =
7433 stats.getPackageStatsLocked(uid, rec.key.packageName);
7434 pkg.incWakeupsLocked();
7435 }
7436 }
7437 }
7438
Dianne Hackborn64825172011-03-02 21:32:58 -08007439 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007441 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007443 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 // XXX Note: don't acquire main activity lock here, because the window
7445 // manager calls in with its locks held.
7446
7447 boolean killed = false;
7448 synchronized (mPidsSelfLocked) {
7449 int[] types = new int[pids.length];
7450 int worstType = 0;
7451 for (int i=0; i<pids.length; i++) {
7452 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7453 if (proc != null) {
7454 int type = proc.setAdj;
7455 types[i] = type;
7456 if (type > worstType) {
7457 worstType = type;
7458 }
7459 }
7460 }
7461
Dianne Hackborn64825172011-03-02 21:32:58 -08007462 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007464 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7465 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007466 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007468
7469 // If this is not a secure call, don't let it kill processes that
7470 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007471 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7472 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007473 }
7474
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007475 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 for (int i=0; i<pids.length; i++) {
7477 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7478 if (proc == null) {
7479 continue;
7480 }
7481 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007482 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007483 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007484 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7485 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007487 proc.killedBackground = true;
7488 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 }
7490 }
7491 }
7492 return killed;
7493 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007494
7495 @Override
7496 public boolean killProcessesBelowForeground(String reason) {
7497 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7498 throw new SecurityException("killProcessesBelowForeground() only available to system");
7499 }
7500
7501 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7502 }
7503
7504 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7505 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7506 throw new SecurityException("killProcessesBelowAdj() only available to system");
7507 }
7508
7509 boolean killed = false;
7510 synchronized (mPidsSelfLocked) {
7511 final int size = mPidsSelfLocked.size();
7512 for (int i = 0; i < size; i++) {
7513 final int pid = mPidsSelfLocked.keyAt(i);
7514 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7515 if (proc == null) continue;
7516
7517 final int adj = proc.setAdj;
7518 if (adj > belowAdj && !proc.killedBackground) {
7519 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7520 EventLog.writeEvent(
7521 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7522 killed = true;
7523 proc.killedBackground = true;
7524 Process.killProcessQuiet(pid);
7525 }
7526 }
7527 }
7528 return killed;
7529 }
7530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 public final void startRunning(String pkg, String cls, String action,
7532 String data) {
7533 synchronized(this) {
7534 if (mStartRunning) {
7535 return;
7536 }
7537 mStartRunning = true;
7538 mTopComponent = pkg != null && cls != null
7539 ? new ComponentName(pkg, cls) : null;
7540 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7541 mTopData = data;
7542 if (!mSystemReady) {
7543 return;
7544 }
7545 }
7546
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007547 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 }
7549
7550 private void retrieveSettings() {
7551 final ContentResolver resolver = mContext.getContentResolver();
7552 String debugApp = Settings.System.getString(
7553 resolver, Settings.System.DEBUG_APP);
7554 boolean waitForDebugger = Settings.System.getInt(
7555 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7556 boolean alwaysFinishActivities = Settings.System.getInt(
7557 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7558
7559 Configuration configuration = new Configuration();
7560 Settings.System.getConfiguration(resolver, configuration);
7561
7562 synchronized (this) {
7563 mDebugApp = mOrigDebugApp = debugApp;
7564 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7565 mAlwaysFinishActivities = alwaysFinishActivities;
7566 // This happens before any activities are started, so we can
7567 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007568 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007569 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 }
7571 }
7572
7573 public boolean testIsSystemReady() {
7574 // no need to synchronize(this) just to read & return the value
7575 return mSystemReady;
7576 }
7577
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007578 private static File getCalledPreBootReceiversFile() {
7579 File dataDir = Environment.getDataDirectory();
7580 File systemDir = new File(dataDir, "system");
7581 File fname = new File(systemDir, "called_pre_boots.dat");
7582 return fname;
7583 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007584
7585 static final int LAST_DONE_VERSION = 10000;
7586
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007587 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7588 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7589 File file = getCalledPreBootReceiversFile();
7590 FileInputStream fis = null;
7591 try {
7592 fis = new FileInputStream(file);
7593 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007594 int fvers = dis.readInt();
7595 if (fvers == LAST_DONE_VERSION) {
7596 String vers = dis.readUTF();
7597 String codename = dis.readUTF();
7598 String build = dis.readUTF();
7599 if (android.os.Build.VERSION.RELEASE.equals(vers)
7600 && android.os.Build.VERSION.CODENAME.equals(codename)
7601 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7602 int num = dis.readInt();
7603 while (num > 0) {
7604 num--;
7605 String pkg = dis.readUTF();
7606 String cls = dis.readUTF();
7607 lastDoneReceivers.add(new ComponentName(pkg, cls));
7608 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007609 }
7610 }
7611 } catch (FileNotFoundException e) {
7612 } catch (IOException e) {
7613 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7614 } finally {
7615 if (fis != null) {
7616 try {
7617 fis.close();
7618 } catch (IOException e) {
7619 }
7620 }
7621 }
7622 return lastDoneReceivers;
7623 }
7624
7625 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7626 File file = getCalledPreBootReceiversFile();
7627 FileOutputStream fos = null;
7628 DataOutputStream dos = null;
7629 try {
7630 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7631 fos = new FileOutputStream(file);
7632 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007633 dos.writeInt(LAST_DONE_VERSION);
7634 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007635 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007636 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007637 dos.writeInt(list.size());
7638 for (int i=0; i<list.size(); i++) {
7639 dos.writeUTF(list.get(i).getPackageName());
7640 dos.writeUTF(list.get(i).getClassName());
7641 }
7642 } catch (IOException e) {
7643 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7644 file.delete();
7645 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007646 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007647 if (dos != null) {
7648 try {
7649 dos.close();
7650 } catch (IOException e) {
7651 // TODO Auto-generated catch block
7652 e.printStackTrace();
7653 }
7654 }
7655 }
7656 }
7657
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007658 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 synchronized(this) {
7660 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007661 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 return;
7663 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007664
7665 // Check to see if there are any update receivers to run.
7666 if (!mDidUpdate) {
7667 if (mWaitingUpdate) {
7668 return;
7669 }
7670 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7671 List<ResolveInfo> ris = null;
7672 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007673 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007674 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007675 } catch (RemoteException e) {
7676 }
7677 if (ris != null) {
7678 for (int i=ris.size()-1; i>=0; i--) {
7679 if ((ris.get(i).activityInfo.applicationInfo.flags
7680 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7681 ris.remove(i);
7682 }
7683 }
7684 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007685
7686 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7687
7688 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007689 for (int i=0; i<ris.size(); i++) {
7690 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007691 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7692 if (lastDoneReceivers.contains(comp)) {
7693 ris.remove(i);
7694 i--;
7695 }
7696 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007697
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007698 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007699 for (int i=0; i<ris.size(); i++) {
7700 ActivityInfo ai = ris.get(i).activityInfo;
7701 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7702 doneReceivers.add(comp);
7703 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007704 for (int j=0; j<users.length; j++) {
7705 IIntentReceiver finisher = null;
7706 if (i == ris.size()-1 && j == users.length-1) {
7707 finisher = new IIntentReceiver.Stub() {
7708 public void performReceive(Intent intent, int resultCode,
7709 String data, Bundle extras, boolean ordered,
7710 boolean sticky, int sendingUser) {
7711 // The raw IIntentReceiver interface is called
7712 // with the AM lock held, so redispatch to
7713 // execute our code without the lock.
7714 mHandler.post(new Runnable() {
7715 public void run() {
7716 synchronized (ActivityManagerService.this) {
7717 mDidUpdate = true;
7718 }
7719 writeLastDonePreBootReceivers(doneReceivers);
7720 showBootMessage(mContext.getText(
7721 R.string.android_upgrading_complete),
7722 false);
7723 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007724 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007725 });
7726 }
7727 };
7728 }
7729 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7730 + " for user " + users[j]);
7731 broadcastIntentLocked(null, null, intent, null, finisher,
7732 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7733 users[j]);
7734 if (finisher != null) {
7735 mWaitingUpdate = true;
7736 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007737 }
7738 }
7739 }
7740 if (mWaitingUpdate) {
7741 return;
7742 }
7743 mDidUpdate = true;
7744 }
7745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007746 mSystemReady = true;
7747 if (!mStartRunning) {
7748 return;
7749 }
7750 }
7751
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007752 ArrayList<ProcessRecord> procsToKill = null;
7753 synchronized(mPidsSelfLocked) {
7754 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7755 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7756 if (!isAllowedWhileBooting(proc.info)){
7757 if (procsToKill == null) {
7758 procsToKill = new ArrayList<ProcessRecord>();
7759 }
7760 procsToKill.add(proc);
7761 }
7762 }
7763 }
7764
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007765 synchronized(this) {
7766 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007767 for (int i=procsToKill.size()-1; i>=0; i--) {
7768 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007769 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007770 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007771 }
7772 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007773
7774 // Now that we have cleaned up any update processes, we
7775 // are ready to start launching real processes and know that
7776 // we won't trample on them any more.
7777 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007778 }
7779
Joe Onorato8a9b2202010-02-26 18:56:32 -08007780 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007781 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 SystemClock.uptimeMillis());
7783
7784 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007785 // Make sure we have no pre-ready processes sitting around.
7786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7788 ResolveInfo ri = mContext.getPackageManager()
7789 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007790 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 CharSequence errorMsg = null;
7792 if (ri != null) {
7793 ActivityInfo ai = ri.activityInfo;
7794 ApplicationInfo app = ai.applicationInfo;
7795 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7796 mTopAction = Intent.ACTION_FACTORY_TEST;
7797 mTopData = null;
7798 mTopComponent = new ComponentName(app.packageName,
7799 ai.name);
7800 } else {
7801 errorMsg = mContext.getResources().getText(
7802 com.android.internal.R.string.factorytest_not_system);
7803 }
7804 } else {
7805 errorMsg = mContext.getResources().getText(
7806 com.android.internal.R.string.factorytest_no_action);
7807 }
7808 if (errorMsg != null) {
7809 mTopAction = null;
7810 mTopData = null;
7811 mTopComponent = null;
7812 Message msg = Message.obtain();
7813 msg.what = SHOW_FACTORY_ERROR_MSG;
7814 msg.getData().putCharSequence("msg", errorMsg);
7815 mHandler.sendMessage(msg);
7816 }
7817 }
7818 }
7819
7820 retrieveSettings();
7821
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007822 if (goingCallback != null) goingCallback.run();
7823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 synchronized (this) {
7825 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7826 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007827 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007828 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 if (apps != null) {
7830 int N = apps.size();
7831 int i;
7832 for (i=0; i<N; i++) {
7833 ApplicationInfo info
7834 = (ApplicationInfo)apps.get(i);
7835 if (info != null &&
7836 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007837 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 }
7839 }
7840 }
7841 } catch (RemoteException ex) {
7842 // pm is in same process, this will never happen.
7843 }
7844 }
7845
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007846 // Start up initial activity.
7847 mBooting = true;
7848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007850 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 Message msg = Message.obtain();
7852 msg.what = SHOW_UID_ERROR_MSG;
7853 mHandler.sendMessage(msg);
7854 }
7855 } catch (RemoteException e) {
7856 }
7857
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007858 long ident = Binder.clearCallingIdentity();
7859 try {
7860 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7861 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7862 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7863 broadcastIntentLocked(null, null, intent,
7864 null, null, 0, null, null, null,
7865 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
7866 } finally {
7867 Binder.restoreCallingIdentity(ident);
7868 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007869 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007870 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 }
7872 }
7873
Dan Egnorb7f03672009-12-09 16:22:32 -08007874 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007875 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007876 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007877 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007878 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 startAppProblemLocked(app);
7880 app.stopFreezingAllLocked();
7881 return handleAppCrashLocked(app);
7882 }
7883
Dan Egnorb7f03672009-12-09 16:22:32 -08007884 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007885 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007887 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007888 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7889 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 startAppProblemLocked(app);
7891 app.stopFreezingAllLocked();
7892 }
7893
7894 /**
7895 * Generate a process error record, suitable for attachment to a ProcessRecord.
7896 *
7897 * @param app The ProcessRecord in which the error occurred.
7898 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7899 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007900 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 * @param shortMsg Short message describing the crash.
7902 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007903 * @param stackTrace Full crash stack trace, may be null.
7904 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 * @return Returns a fully-formed AppErrorStateInfo record.
7906 */
7907 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007908 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 report.condition = condition;
7912 report.processName = app.processName;
7913 report.pid = app.pid;
7914 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007915 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 report.shortMsg = shortMsg;
7917 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007918 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919
7920 return report;
7921 }
7922
Dan Egnor42471dd2010-01-07 17:25:22 -08007923 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 synchronized (this) {
7925 app.crashing = false;
7926 app.crashingReport = null;
7927 app.notResponding = false;
7928 app.notRespondingReport = null;
7929 if (app.anrDialog == fromDialog) {
7930 app.anrDialog = null;
7931 }
7932 if (app.waitDialog == fromDialog) {
7933 app.waitDialog = null;
7934 }
7935 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007936 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007937 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007938 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7939 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007940 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007942 }
7943 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007944
Dan Egnorb7f03672009-12-09 16:22:32 -08007945 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007946 if (mHeadless) {
7947 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7948 return false;
7949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 long now = SystemClock.uptimeMillis();
7951
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007952 Long crashTime;
7953 if (!app.isolated) {
7954 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7955 } else {
7956 crashTime = null;
7957 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007958 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007960 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007962 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007963 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007964 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7965 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007967 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007969 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7970 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 }
7972 }
7973 if (!app.persistent) {
7974 // We don't want to start this process again until the user
7975 // explicitly does so... but for persistent process, we really
7976 // need to keep it running. If a persistent process is actually
7977 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007978 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007980 if (!app.isolated) {
7981 // XXX We don't have a way to mark isolated processes
7982 // as bad, since they don't have a peristent identity.
7983 mBadProcesses.put(app.info.processName, app.uid, now);
7984 mProcessCrashTimes.remove(app.info.processName, app.uid);
7985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007988 // Don't let services in this process be restarted and potentially
7989 // annoy the user repeatedly. Unless it is persistent, since those
7990 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007991 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007992 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007993 return false;
7994 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007995 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007996 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007997 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007998 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007999 // If the top running activity is from this crashing
8000 // process, then terminate it to avoid getting in a loop.
8001 Slog.w(TAG, " Force finishing activity "
8002 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008003 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008004 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008005 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008006 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008007 // stopped, to avoid a situation where one will get
8008 // re-start our crashing activity once it gets resumed again.
8009 index--;
8010 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008011 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008012 if (r.state == ActivityState.RESUMED
8013 || r.state == ActivityState.PAUSING
8014 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008015 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008016 Slog.w(TAG, " Force finishing activity "
8017 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008018 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008019 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008020 }
8021 }
8022 }
8023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 }
8025
8026 // Bump up the crash count of any services currently running in the proc.
8027 if (app.services.size() != 0) {
8028 // Any services running in the application need to be placed
8029 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008030 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008032 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 sr.crashCount++;
8034 }
8035 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008036
8037 // If the crashing process is what we consider to be the "home process" and it has been
8038 // replaced by a third-party app, clear the package preferred activities from packages
8039 // with a home activity running in the process to prevent a repeatedly crashing app
8040 // from blocking the user to manually clear the list.
8041 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8042 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8043 Iterator it = mHomeProcess.activities.iterator();
8044 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008045 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008046 if (r.isHomeActivity) {
8047 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8048 try {
8049 ActivityThread.getPackageManager()
8050 .clearPackagePreferredActivities(r.packageName);
8051 } catch (RemoteException c) {
8052 // pm is in same process, this will never happen.
8053 }
8054 }
8055 }
8056 }
8057
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008058 if (!app.isolated) {
8059 // XXX Can't keep track of crash times for isolated processes,
8060 // because they don't have a perisistent identity.
8061 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8062 }
8063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 return true;
8065 }
8066
8067 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008068 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8069 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 skipCurrentReceiverLocked(app);
8071 }
8072
8073 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008074 for (BroadcastQueue queue : mBroadcastQueues) {
8075 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 }
8077 }
8078
Dan Egnor60d87622009-12-16 16:32:58 -08008079 /**
8080 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8081 * The application process will exit immediately after this call returns.
8082 * @param app object of the crashing app, null for the system server
8083 * @param crashInfo describing the exception
8084 */
8085 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008086 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008087 final String processName = app == null ? "system_server"
8088 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008089
8090 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008091 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008092 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008093 crashInfo.exceptionClassName,
8094 crashInfo.exceptionMessage,
8095 crashInfo.throwFileName,
8096 crashInfo.throwLineNumber);
8097
Jeff Sharkeya353d262011-10-28 11:12:06 -07008098 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008099
8100 crashApplication(r, crashInfo);
8101 }
8102
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008103 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008104 IBinder app,
8105 int violationMask,
8106 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008107 ProcessRecord r = findAppProcess(app, "StrictMode");
8108 if (r == null) {
8109 return;
8110 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008111
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008112 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008113 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008114 boolean logIt = true;
8115 synchronized (mAlreadyLoggedViolatedStacks) {
8116 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8117 logIt = false;
8118 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008119 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008120 // the relative pain numbers, without logging all
8121 // the stack traces repeatedly. We'd want to do
8122 // likewise in the client code, which also does
8123 // dup suppression, before the Binder call.
8124 } else {
8125 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8126 mAlreadyLoggedViolatedStacks.clear();
8127 }
8128 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8129 }
8130 }
8131 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008132 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008133 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008134 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008135
8136 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8137 AppErrorResult result = new AppErrorResult();
8138 synchronized (this) {
8139 final long origId = Binder.clearCallingIdentity();
8140
8141 Message msg = Message.obtain();
8142 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8143 HashMap<String, Object> data = new HashMap<String, Object>();
8144 data.put("result", result);
8145 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008146 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008147 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008148 msg.obj = data;
8149 mHandler.sendMessage(msg);
8150
8151 Binder.restoreCallingIdentity(origId);
8152 }
8153 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008154 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008155 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008156 }
8157
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008158 // Depending on the policy in effect, there could be a bunch of
8159 // these in quick succession so we try to batch these together to
8160 // minimize disk writes, number of dropbox entries, and maximize
8161 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008162 private void logStrictModeViolationToDropBox(
8163 ProcessRecord process,
8164 StrictMode.ViolationInfo info) {
8165 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008166 return;
8167 }
8168 final boolean isSystemApp = process == null ||
8169 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8170 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008171 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008172 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8173 final DropBoxManager dbox = (DropBoxManager)
8174 mContext.getSystemService(Context.DROPBOX_SERVICE);
8175
8176 // Exit early if the dropbox isn't configured to accept this report type.
8177 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8178
8179 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008180 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008181 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8182 synchronized (sb) {
8183 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008184 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008185 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8186 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008187 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8188 if (info.violationNumThisLoop != 0) {
8189 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8190 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008191 if (info.numAnimationsRunning != 0) {
8192 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8193 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008194 if (info.broadcastIntentAction != null) {
8195 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8196 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008197 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008198 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008199 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008200 if (info.numInstances != -1) {
8201 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8202 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008203 if (info.tags != null) {
8204 for (String tag : info.tags) {
8205 sb.append("Span-Tag: ").append(tag).append("\n");
8206 }
8207 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008208 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008209 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8210 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008211 }
8212 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008213
8214 // Only buffer up to ~64k. Various logging bits truncate
8215 // things at 128k.
8216 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008217 }
8218
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008219 // Flush immediately if the buffer's grown too large, or this
8220 // is a non-system app. Non-system apps are isolated with a
8221 // different tag & policy and not batched.
8222 //
8223 // Batching is useful during internal testing with
8224 // StrictMode settings turned up high. Without batching,
8225 // thousands of separate files could be created on boot.
8226 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008227 new Thread("Error dump: " + dropboxTag) {
8228 @Override
8229 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008230 String report;
8231 synchronized (sb) {
8232 report = sb.toString();
8233 sb.delete(0, sb.length());
8234 sb.trimToSize();
8235 }
8236 if (report.length() != 0) {
8237 dbox.addText(dropboxTag, report);
8238 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008239 }
8240 }.start();
8241 return;
8242 }
8243
8244 // System app batching:
8245 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008246 // An existing dropbox-writing thread is outstanding, so
8247 // we don't need to start it up. The existing thread will
8248 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008249 return;
8250 }
8251
8252 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8253 // (After this point, we shouldn't access AMS internal data structures.)
8254 new Thread("Error dump: " + dropboxTag) {
8255 @Override
8256 public void run() {
8257 // 5 second sleep to let stacks arrive and be batched together
8258 try {
8259 Thread.sleep(5000); // 5 seconds
8260 } catch (InterruptedException e) {}
8261
8262 String errorReport;
8263 synchronized (mStrictModeBuffer) {
8264 errorReport = mStrictModeBuffer.toString();
8265 if (errorReport.length() == 0) {
8266 return;
8267 }
8268 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8269 mStrictModeBuffer.trimToSize();
8270 }
8271 dbox.addText(dropboxTag, errorReport);
8272 }
8273 }.start();
8274 }
8275
Dan Egnor60d87622009-12-16 16:32:58 -08008276 /**
8277 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8278 * @param app object of the crashing app, null for the system server
8279 * @param tag reported by the caller
8280 * @param crashInfo describing the context of the error
8281 * @return true if the process should exit immediately (WTF is fatal)
8282 */
8283 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008284 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008285 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008286 final String processName = app == null ? "system_server"
8287 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008288
8289 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008290 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008291 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008292 tag, crashInfo.exceptionMessage);
8293
Jeff Sharkeya353d262011-10-28 11:12:06 -07008294 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008295
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008296 if (r != null && r.pid != Process.myPid() &&
8297 Settings.Secure.getInt(mContext.getContentResolver(),
8298 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008299 crashApplication(r, crashInfo);
8300 return true;
8301 } else {
8302 return false;
8303 }
8304 }
8305
8306 /**
8307 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8308 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8309 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008310 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008311 if (app == null) {
8312 return null;
8313 }
8314
8315 synchronized (this) {
8316 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8317 final int NA = apps.size();
8318 for (int ia=0; ia<NA; ia++) {
8319 ProcessRecord p = apps.valueAt(ia);
8320 if (p.thread != null && p.thread.asBinder() == app) {
8321 return p;
8322 }
8323 }
8324 }
8325
Dianne Hackborncb44d962011-03-10 17:02:27 -08008326 Slog.w(TAG, "Can't find mystery application for " + reason
8327 + " from pid=" + Binder.getCallingPid()
8328 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008329 return null;
8330 }
8331 }
8332
8333 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008334 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8335 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008336 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008337 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8338 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008339 // Watchdog thread ends up invoking this function (with
8340 // a null ProcessRecord) to add the stack file to dropbox.
8341 // Do not acquire a lock on this (am) in such cases, as it
8342 // could cause a potential deadlock, if and when watchdog
8343 // is invoked due to unavailability of lock on am and it
8344 // would prevent watchdog from killing system_server.
8345 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008346 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008347 return;
8348 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008349 // Note: ProcessRecord 'process' is guarded by the service
8350 // instance. (notably process.pkgList, which could otherwise change
8351 // concurrently during execution of this method)
8352 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008353 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008354 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008355 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008356 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8357 for (String pkg : process.pkgList) {
8358 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008359 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008360 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008361 if (pi != null) {
8362 sb.append(" v").append(pi.versionCode);
8363 if (pi.versionName != null) {
8364 sb.append(" (").append(pi.versionName).append(")");
8365 }
8366 }
8367 } catch (RemoteException e) {
8368 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008369 }
Dan Egnora455d192010-03-12 08:52:28 -08008370 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008371 }
Dan Egnora455d192010-03-12 08:52:28 -08008372 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008373 }
8374
8375 private static String processClass(ProcessRecord process) {
8376 if (process == null || process.pid == MY_PID) {
8377 return "system_server";
8378 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8379 return "system_app";
8380 } else {
8381 return "data_app";
8382 }
8383 }
8384
8385 /**
8386 * Write a description of an error (crash, WTF, ANR) to the drop box.
8387 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8388 * @param process which caused the error, null means the system server
8389 * @param activity which triggered the error, null if unknown
8390 * @param parent activity related to the error, null if unknown
8391 * @param subject line related to the error, null if absent
8392 * @param report in long form describing the error, null if absent
8393 * @param logFile to include in the report, null if none
8394 * @param crashInfo giving an application stack trace, null if absent
8395 */
8396 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008397 ProcessRecord process, String processName, ActivityRecord activity,
8398 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008399 final String report, final File logFile,
8400 final ApplicationErrorReport.CrashInfo crashInfo) {
8401 // NOTE -- this must never acquire the ActivityManagerService lock,
8402 // otherwise the watchdog may be prevented from resetting the system.
8403
8404 final String dropboxTag = processClass(process) + "_" + eventType;
8405 final DropBoxManager dbox = (DropBoxManager)
8406 mContext.getSystemService(Context.DROPBOX_SERVICE);
8407
8408 // Exit early if the dropbox isn't configured to accept this report type.
8409 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8410
8411 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008412 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008413 if (activity != null) {
8414 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8415 }
8416 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8417 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8418 }
8419 if (parent != null && parent != activity) {
8420 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8421 }
8422 if (subject != null) {
8423 sb.append("Subject: ").append(subject).append("\n");
8424 }
8425 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008426 if (Debug.isDebuggerConnected()) {
8427 sb.append("Debugger: Connected\n");
8428 }
Dan Egnora455d192010-03-12 08:52:28 -08008429 sb.append("\n");
8430
8431 // Do the rest in a worker thread to avoid blocking the caller on I/O
8432 // (After this point, we shouldn't access AMS internal data structures.)
8433 Thread worker = new Thread("Error dump: " + dropboxTag) {
8434 @Override
8435 public void run() {
8436 if (report != null) {
8437 sb.append(report);
8438 }
8439 if (logFile != null) {
8440 try {
8441 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8442 } catch (IOException e) {
8443 Slog.e(TAG, "Error reading " + logFile, e);
8444 }
8445 }
8446 if (crashInfo != null && crashInfo.stackTrace != null) {
8447 sb.append(crashInfo.stackTrace);
8448 }
8449
8450 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8451 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8452 if (lines > 0) {
8453 sb.append("\n");
8454
8455 // Merge several logcat streams, and take the last N lines
8456 InputStreamReader input = null;
8457 try {
8458 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8459 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8460 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8461
8462 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8463 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8464 input = new InputStreamReader(logcat.getInputStream());
8465
8466 int num;
8467 char[] buf = new char[8192];
8468 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8469 } catch (IOException e) {
8470 Slog.e(TAG, "Error running logcat", e);
8471 } finally {
8472 if (input != null) try { input.close(); } catch (IOException e) {}
8473 }
8474 }
8475
8476 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008477 }
Dan Egnora455d192010-03-12 08:52:28 -08008478 };
8479
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008480 if (process == null) {
8481 // If process is null, we are being called from some internal code
8482 // and may be about to die -- run this synchronously.
8483 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008484 } else {
8485 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008486 }
8487 }
8488
8489 /**
8490 * Bring up the "unexpected error" dialog box for a crashing app.
8491 * Deal with edge cases (intercepts from instrumented applications,
8492 * ActivityController, error intent receivers, that sort of thing).
8493 * @param r the application crashing
8494 * @param crashInfo describing the failure
8495 */
8496 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008497 long timeMillis = System.currentTimeMillis();
8498 String shortMsg = crashInfo.exceptionClassName;
8499 String longMsg = crashInfo.exceptionMessage;
8500 String stackTrace = crashInfo.stackTrace;
8501 if (shortMsg != null && longMsg != null) {
8502 longMsg = shortMsg + ": " + longMsg;
8503 } else if (shortMsg != null) {
8504 longMsg = shortMsg;
8505 }
8506
Dan Egnor60d87622009-12-16 16:32:58 -08008507 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008509 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510 try {
8511 String name = r != null ? r.processName : null;
8512 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008513 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008514 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008515 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 + " at watcher's request");
8517 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008518 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008519 }
8520 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008521 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 }
8523 }
8524
8525 final long origId = Binder.clearCallingIdentity();
8526
8527 // If this process is running instrumentation, finish it.
8528 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008529 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008531 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8532 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 Bundle info = new Bundle();
8534 info.putString("shortMsg", shortMsg);
8535 info.putString("longMsg", longMsg);
8536 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8537 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008538 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 }
8540
Dan Egnor60d87622009-12-16 16:32:58 -08008541 // If we can't identify the process or it's already exceeded its crash quota,
8542 // quit right away without showing a crash dialog.
8543 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008544 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008545 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 }
8547
8548 Message msg = Message.obtain();
8549 msg.what = SHOW_ERROR_MSG;
8550 HashMap data = new HashMap();
8551 data.put("result", result);
8552 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 msg.obj = data;
8554 mHandler.sendMessage(msg);
8555
8556 Binder.restoreCallingIdentity(origId);
8557 }
8558
8559 int res = result.get();
8560
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008561 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008563 if (r != null && !r.isolated) {
8564 // XXX Can't keep track of crash time for isolated processes,
8565 // since they don't have a persistent identity.
8566 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 SystemClock.uptimeMillis());
8568 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008569 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008570 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008571 }
8572 }
8573
8574 if (appErrorIntent != null) {
8575 try {
8576 mContext.startActivity(appErrorIntent);
8577 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008578 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008582
8583 Intent createAppErrorIntentLocked(ProcessRecord r,
8584 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8585 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008586 if (report == null) {
8587 return null;
8588 }
8589 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8590 result.setComponent(r.errorReportReceiver);
8591 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8592 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8593 return result;
8594 }
8595
Dan Egnorb7f03672009-12-09 16:22:32 -08008596 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8597 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008598 if (r.errorReportReceiver == null) {
8599 return null;
8600 }
8601
8602 if (!r.crashing && !r.notResponding) {
8603 return null;
8604 }
8605
Dan Egnorb7f03672009-12-09 16:22:32 -08008606 ApplicationErrorReport report = new ApplicationErrorReport();
8607 report.packageName = r.info.packageName;
8608 report.installerPackageName = r.errorReportReceiver.getPackageName();
8609 report.processName = r.processName;
8610 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008611 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008612
Dan Egnorb7f03672009-12-09 16:22:32 -08008613 if (r.crashing) {
8614 report.type = ApplicationErrorReport.TYPE_CRASH;
8615 report.crashInfo = crashInfo;
8616 } else if (r.notResponding) {
8617 report.type = ApplicationErrorReport.TYPE_ANR;
8618 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008619
Dan Egnorb7f03672009-12-09 16:22:32 -08008620 report.anrInfo.activity = r.notRespondingReport.tag;
8621 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8622 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008623 }
8624
Dan Egnorb7f03672009-12-09 16:22:32 -08008625 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008626 }
8627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008629 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 // assume our apps are happy - lazy create the list
8631 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8632
Dianne Hackborn0c380492012-08-20 17:23:30 -07008633 final boolean allUsers = ActivityManager.checkUidPermission(
8634 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8635 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8636 int userId = UserHandle.getUserId(Binder.getCallingUid());
8637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 synchronized (this) {
8639
8640 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008641 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8642 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008643 if (!allUsers && app.userId != userId) {
8644 continue;
8645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8647 // This one's in trouble, so we'll generate a report for it
8648 // crashes are higher priority (in case there's a crash *and* an anr)
8649 ActivityManager.ProcessErrorStateInfo report = null;
8650 if (app.crashing) {
8651 report = app.crashingReport;
8652 } else if (app.notResponding) {
8653 report = app.notRespondingReport;
8654 }
8655
8656 if (report != null) {
8657 if (errList == null) {
8658 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8659 }
8660 errList.add(report);
8661 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008662 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 " crashing = " + app.crashing +
8664 " notResponding = " + app.notResponding);
8665 }
8666 }
8667 }
8668 }
8669
8670 return errList;
8671 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008672
8673 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008674 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008675 if (currApp != null) {
8676 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8677 }
8678 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008679 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8680 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008681 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8682 if (currApp != null) {
8683 currApp.lru = 0;
8684 }
8685 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008686 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008687 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8688 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8689 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8690 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8691 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8692 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8693 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8694 } else {
8695 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8696 }
8697 }
8698
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008699 private void fillInProcMemInfo(ProcessRecord app,
8700 ActivityManager.RunningAppProcessInfo outInfo) {
8701 outInfo.pid = app.pid;
8702 outInfo.uid = app.info.uid;
8703 if (mHeavyWeightProcess == app) {
8704 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8705 }
8706 if (app.persistent) {
8707 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8708 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008709 if (app.hasActivities) {
8710 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8711 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008712 outInfo.lastTrimLevel = app.trimMemoryLevel;
8713 int adj = app.curAdj;
8714 outInfo.importance = oomAdjToImportance(adj, outInfo);
8715 outInfo.importanceReasonCode = app.adjTypeCode;
8716 }
8717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008719 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 // Lazy instantiation of list
8721 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008722 final boolean allUsers = ActivityManager.checkUidPermission(
8723 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8724 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8725 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 synchronized (this) {
8727 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008728 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8729 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008730 if (!allUsers && app.userId != userId) {
8731 continue;
8732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8734 // Generate process state info for running application
8735 ActivityManager.RunningAppProcessInfo currApp =
8736 new ActivityManager.RunningAppProcessInfo(app.processName,
8737 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008738 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008739 if (app.adjSource instanceof ProcessRecord) {
8740 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008741 currApp.importanceReasonImportance = oomAdjToImportance(
8742 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008743 } else if (app.adjSource instanceof ActivityRecord) {
8744 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008745 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8746 }
8747 if (app.adjTarget instanceof ComponentName) {
8748 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8749 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008750 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751 // + " lru=" + currApp.lru);
8752 if (runList == null) {
8753 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8754 }
8755 runList.add(currApp);
8756 }
8757 }
8758 }
8759 return runList;
8760 }
8761
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008762 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008763 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008764 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8765 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8766 if (runningApps != null && runningApps.size() > 0) {
8767 Set<String> extList = new HashSet<String>();
8768 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8769 if (app.pkgList != null) {
8770 for (String pkg : app.pkgList) {
8771 extList.add(pkg);
8772 }
8773 }
8774 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008775 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008776 for (String pkg : extList) {
8777 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008778 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008779 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8780 retList.add(info);
8781 }
8782 } catch (RemoteException e) {
8783 }
8784 }
8785 }
8786 return retList;
8787 }
8788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008790 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8791 enforceNotIsolatedCaller("getMyMemoryState");
8792 synchronized (this) {
8793 ProcessRecord proc;
8794 synchronized (mPidsSelfLocked) {
8795 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8796 }
8797 fillInProcMemInfo(proc, outInfo);
8798 }
8799 }
8800
8801 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008803 if (checkCallingPermission(android.Manifest.permission.DUMP)
8804 != PackageManager.PERMISSION_GRANTED) {
8805 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8806 + Binder.getCallingPid()
8807 + ", uid=" + Binder.getCallingUid()
8808 + " without permission "
8809 + android.Manifest.permission.DUMP);
8810 return;
8811 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008812
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008813 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008814 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008815 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008816
8817 int opti = 0;
8818 while (opti < args.length) {
8819 String opt = args[opti];
8820 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8821 break;
8822 }
8823 opti++;
8824 if ("-a".equals(opt)) {
8825 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008826 } else if ("-c".equals(opt)) {
8827 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008828 } else if ("-h".equals(opt)) {
8829 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008830 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008831 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008832 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008833 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8834 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8835 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008836 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008837 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008838 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008839 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008840 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008841 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008842 pw.println(" all: dump all activities");
8843 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008844 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008845 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8846 pw.println(" a partial substring in a component name, a");
8847 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008848 pw.println(" -a: include all available server state.");
8849 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851 } else {
8852 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008854 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008855
8856 long origId = Binder.clearCallingIdentity();
8857 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008858 // Is the caller requesting to dump a particular piece of data?
8859 if (opti < args.length) {
8860 String cmd = args[opti];
8861 opti++;
8862 if ("activities".equals(cmd) || "a".equals(cmd)) {
8863 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008864 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008867 String[] newArgs;
8868 String name;
8869 if (opti >= args.length) {
8870 name = null;
8871 newArgs = EMPTY_STRING_ARRAY;
8872 } else {
8873 name = args[opti];
8874 opti++;
8875 newArgs = new String[args.length - opti];
8876 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8877 args.length - opti);
8878 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008879 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008880 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008881 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008882 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008883 String[] newArgs;
8884 String name;
8885 if (opti >= args.length) {
8886 name = null;
8887 newArgs = EMPTY_STRING_ARRAY;
8888 } else {
8889 name = args[opti];
8890 opti++;
8891 newArgs = new String[args.length - opti];
8892 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8893 args.length - opti);
8894 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008895 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008896 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008897 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008899 String[] newArgs;
8900 String name;
8901 if (opti >= args.length) {
8902 name = null;
8903 newArgs = EMPTY_STRING_ARRAY;
8904 } else {
8905 name = args[opti];
8906 opti++;
8907 newArgs = new String[args.length - opti];
8908 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8909 args.length - opti);
8910 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008911 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008912 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008913 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008914 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8915 synchronized (this) {
8916 dumpOomLocked(fd, pw, args, opti, true);
8917 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008918 } else if ("provider".equals(cmd)) {
8919 String[] newArgs;
8920 String name;
8921 if (opti >= args.length) {
8922 name = null;
8923 newArgs = EMPTY_STRING_ARRAY;
8924 } else {
8925 name = args[opti];
8926 opti++;
8927 newArgs = new String[args.length - opti];
8928 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8929 }
8930 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8931 pw.println("No providers match: " + name);
8932 pw.println("Use -h for help.");
8933 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008934 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8935 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008936 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008938 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008939 String[] newArgs;
8940 String name;
8941 if (opti >= args.length) {
8942 name = null;
8943 newArgs = EMPTY_STRING_ARRAY;
8944 } else {
8945 name = args[opti];
8946 opti++;
8947 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008948 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8949 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008950 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008951 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008952 pw.println("No services match: " + name);
8953 pw.println("Use -h for help.");
8954 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008955 } else if ("package".equals(cmd)) {
8956 String[] newArgs;
8957 if (opti >= args.length) {
8958 pw.println("package: no package name specified");
8959 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008960 } else {
8961 dumpPackage = args[opti];
8962 opti++;
8963 newArgs = new String[args.length - opti];
8964 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8965 args.length - opti);
8966 args = newArgs;
8967 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008968 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008969 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008970 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8971 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008972 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008973 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008974 } else {
8975 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008976 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8977 pw.println("Bad activity command, or no activities match: " + cmd);
8978 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008979 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008980 }
8981 if (!more) {
8982 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008983 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008986
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008987 // No piece of data specified, dump everything.
8988 synchronized (this) {
8989 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008990 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008991 if (needSep) {
8992 pw.println(" ");
8993 }
8994 if (dumpAll) {
8995 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008996 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008997 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008998 if (needSep) {
8999 pw.println(" ");
9000 }
9001 if (dumpAll) {
9002 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009003 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009004 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009005 if (needSep) {
9006 pw.println(" ");
9007 }
9008 if (dumpAll) {
9009 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009010 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009011 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009012 if (needSep) {
9013 pw.println(" ");
9014 }
9015 if (dumpAll) {
9016 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009017 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009018 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009019 if (needSep) {
9020 pw.println(" ");
9021 }
9022 if (dumpAll) {
9023 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009024 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009025 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009026 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009027 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009028 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009029
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009030 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009031 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9033 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009034 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9035 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009036 pw.println(" ");
9037 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009038 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9039 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009040 if (mMainStack.mWaitingVisibleActivities.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 for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009043 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009044 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009045 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009046 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009048 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009049 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009050 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009051 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009052 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9053 pw.println(" ");
9054 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009055 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009056 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009057 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009058 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 pw.println(" ");
9060 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009061 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009062 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009064
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009065 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009066 if (mMainStack.mPausingActivity != null) {
9067 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009068 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009069 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009070 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009071 if (dumpAll) {
9072 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9073 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009074 pw.println(" mDismissKeyguardOnNextActivity: "
9075 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009077
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009078 if (mRecentTasks.size() > 0) {
9079 pw.println();
9080 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009081
9082 final int N = mRecentTasks.size();
9083 for (int i=0; i<N; i++) {
9084 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009085 if (dumpPackage != null) {
9086 if (tr.realActivity == null ||
9087 !dumpPackage.equals(tr.realActivity)) {
9088 continue;
9089 }
9090 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009091 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9092 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009093 if (dumpAll) {
9094 mRecentTasks.get(i).dump(pw, " ");
9095 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009096 }
9097 }
9098
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009099 if (dumpAll) {
9100 pw.println(" ");
9101 pw.println(" mCurTask: " + mCurTask);
9102 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009103
9104 return true;
9105 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009106
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009107 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009108 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009109 boolean needSep = false;
9110 int numPers = 0;
9111
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009112 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9113
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009114 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9116 final int NA = procs.size();
9117 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009118 ProcessRecord r = procs.valueAt(ia);
9119 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9120 continue;
9121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122 if (!needSep) {
9123 pw.println(" All known processes:");
9124 needSep = true;
9125 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009126 pw.print(r.persistent ? " *PERS*" : " *APP*");
9127 pw.print(" UID "); pw.print(procs.keyAt(ia));
9128 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 r.dump(pw, " ");
9130 if (r.persistent) {
9131 numPers++;
9132 }
9133 }
9134 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009135 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009136
9137 if (mIsolatedProcesses.size() > 0) {
9138 if (needSep) pw.println(" ");
9139 needSep = true;
9140 pw.println(" Isolated process list (sorted by uid):");
9141 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9142 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9143 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9144 continue;
9145 }
9146 pw.println(String.format("%sIsolated #%2d: %s",
9147 " ", i, r.toString()));
9148 }
9149 }
9150
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009151 if (mLruProcesses.size() > 0) {
9152 if (needSep) pw.println(" ");
9153 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009154 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009155 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009156 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009157 needSep = true;
9158 }
9159
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009160 if (dumpAll) {
9161 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009162 boolean printed = false;
9163 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9164 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9165 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9166 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009167 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009168 if (!printed) {
9169 if (needSep) pw.println(" ");
9170 needSep = true;
9171 pw.println(" PID mappings:");
9172 printed = true;
9173 }
9174 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9175 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 }
9177 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009178 }
9179
9180 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009181 synchronized (mPidsSelfLocked) {
9182 boolean printed = false;
9183 for (int i=0; i<mForegroundProcesses.size(); i++) {
9184 ProcessRecord r = mPidsSelfLocked.get(
9185 mForegroundProcesses.valueAt(i).pid);
9186 if (dumpPackage != null && (r == null
9187 || !dumpPackage.equals(r.info.packageName))) {
9188 continue;
9189 }
9190 if (!printed) {
9191 if (needSep) pw.println(" ");
9192 needSep = true;
9193 pw.println(" Foreground Processes:");
9194 printed = true;
9195 }
9196 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9197 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009199 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009200 }
9201
9202 if (mPersistentStartingProcesses.size() > 0) {
9203 if (needSep) pw.println(" ");
9204 needSep = true;
9205 pw.println(" Persisent processes that are starting:");
9206 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009207 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009210 if (mRemovedProcesses.size() > 0) {
9211 if (needSep) pw.println(" ");
9212 needSep = true;
9213 pw.println(" Processes that are being removed:");
9214 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009215 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216 }
9217
9218 if (mProcessesOnHold.size() > 0) {
9219 if (needSep) pw.println(" ");
9220 needSep = true;
9221 pw.println(" Processes that are on old until the system is ready:");
9222 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009223 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009226 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009227
9228 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009229 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009230 long now = SystemClock.uptimeMillis();
9231 for (Map.Entry<String, SparseArray<Long>> procs
9232 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009233 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009234 SparseArray<Long> uids = procs.getValue();
9235 final int N = uids.size();
9236 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009237 int puid = uids.keyAt(i);
9238 ProcessRecord r = mProcessNames.get(pname, puid);
9239 if (dumpPackage != null && (r == null
9240 || !dumpPackage.equals(r.info.packageName))) {
9241 continue;
9242 }
9243 if (!printed) {
9244 if (needSep) pw.println(" ");
9245 needSep = true;
9246 pw.println(" Time since processes crashed:");
9247 printed = true;
9248 }
9249 pw.print(" Process "); pw.print(pname);
9250 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009251 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009252 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9253 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009254 }
9255 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009258 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009259 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009260 for (Map.Entry<String, SparseArray<Long>> procs
9261 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009262 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009263 SparseArray<Long> uids = procs.getValue();
9264 final int N = uids.size();
9265 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009266 int puid = uids.keyAt(i);
9267 ProcessRecord r = mProcessNames.get(pname, puid);
9268 if (dumpPackage != null && (r == null
9269 || !dumpPackage.equals(r.info.packageName))) {
9270 continue;
9271 }
9272 if (!printed) {
9273 if (needSep) pw.println(" ");
9274 needSep = true;
9275 pw.println(" Bad processes:");
9276 }
9277 pw.print(" Bad process "); pw.print(pname);
9278 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009279 pw.print(": crashed at time ");
9280 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 }
9282 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009285 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009286 pw.println(" mStartedUsers:");
9287 for (int i=0; i<mStartedUsers.size(); i++) {
9288 UserStartedState uss = mStartedUsers.valueAt(i);
9289 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009290 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009291 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009292 pw.print(" mUserLru: [");
9293 for (int i=0; i<mUserLru.size(); i++) {
9294 if (i > 0) pw.print(", ");
9295 pw.print(mUserLru.get(i));
9296 }
9297 pw.println("]");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009298 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009299 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009300 if (dumpAll) {
9301 StringBuilder sb = new StringBuilder(128);
9302 sb.append(" mPreviousProcessVisibleTime: ");
9303 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9304 pw.println(sb);
9305 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009306 if (mHeavyWeightProcess != null) {
9307 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9308 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009310 if (dumpAll) {
9311 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009312 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009313 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009314 for (Map.Entry<String, Integer> entry
9315 : mCompatModePackages.getPackages().entrySet()) {
9316 String pkg = entry.getKey();
9317 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009318 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9319 continue;
9320 }
9321 if (!printed) {
9322 pw.println(" mScreenCompatPackages:");
9323 printed = true;
9324 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009325 pw.print(" "); pw.print(pkg); pw.print(": ");
9326 pw.print(mode); pw.println();
9327 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009328 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009329 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009330 if (mSleeping || mWentToSleep || mLockScreenShown) {
9331 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9332 + " mLockScreenShown " + mLockScreenShown);
9333 }
9334 if (mShuttingDown) {
9335 pw.println(" mShuttingDown=" + mShuttingDown);
9336 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009337 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9338 || mOrigWaitForDebugger) {
9339 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9340 + " mDebugTransient=" + mDebugTransient
9341 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9342 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009343 if (mOpenGlTraceApp != null) {
9344 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9345 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009346 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9347 || mProfileFd != null) {
9348 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9349 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9350 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9351 + mAutoStopProfiler);
9352 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009353 if (mAlwaysFinishActivities || mController != null) {
9354 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9355 + " mController=" + mController);
9356 }
9357 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009360 + " mProcessesReady=" + mProcessesReady
9361 + " mSystemReady=" + mSystemReady);
9362 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 + " mBooted=" + mBooted
9364 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009365 pw.print(" mLastPowerCheckRealtime=");
9366 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9367 pw.println("");
9368 pw.print(" mLastPowerCheckUptime=");
9369 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9370 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009371 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9372 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009373 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009374 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9375 + " mNumHiddenProcs=" + mNumHiddenProcs
9376 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009377 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009379
9380 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 }
9382
Dianne Hackborn287952c2010-09-22 22:34:31 -07009383 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009384 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009385 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009386 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009387 long now = SystemClock.uptimeMillis();
9388 for (int i=0; i<mProcessesToGc.size(); i++) {
9389 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009390 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9391 continue;
9392 }
9393 if (!printed) {
9394 if (needSep) pw.println(" ");
9395 needSep = true;
9396 pw.println(" Processes that are waiting to GC:");
9397 printed = true;
9398 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009399 pw.print(" Process "); pw.println(proc);
9400 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9401 pw.print(", last gced=");
9402 pw.print(now-proc.lastRequestedGc);
9403 pw.print(" ms ago, last lowMem=");
9404 pw.print(now-proc.lastLowMemory);
9405 pw.println(" ms ago");
9406
9407 }
9408 }
9409 return needSep;
9410 }
9411
9412 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9413 int opti, boolean dumpAll) {
9414 boolean needSep = false;
9415
9416 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009417 if (needSep) pw.println(" ");
9418 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009419 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009420 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009421 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009422 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9423 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9424 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9425 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9426 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009427 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009428 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009429 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009430 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009431 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009432 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009433
9434 if (needSep) pw.println(" ");
9435 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009436 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009437 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009438 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009439 needSep = true;
9440 }
9441
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009442 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009443
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009444 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009445 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009446 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009447 if (mHeavyWeightProcess != null) {
9448 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9449 }
9450
9451 return true;
9452 }
9453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 /**
9455 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009456 * - no provider specified: dump all the providers
9457 * - a flattened component name that matched an existing provider was specified as the
9458 * first arg: dump that one provider
9459 * - the first arg isn't the flattened component name of an existing provider:
9460 * dump all providers whose component contains the first arg as a substring
9461 */
9462 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9463 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009464 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009465 }
9466
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009467 static class ItemMatcher {
9468 ArrayList<ComponentName> components;
9469 ArrayList<String> strings;
9470 ArrayList<Integer> objects;
9471 boolean all;
9472
9473 ItemMatcher() {
9474 all = true;
9475 }
9476
9477 void build(String name) {
9478 ComponentName componentName = ComponentName.unflattenFromString(name);
9479 if (componentName != null) {
9480 if (components == null) {
9481 components = new ArrayList<ComponentName>();
9482 }
9483 components.add(componentName);
9484 all = false;
9485 } else {
9486 int objectId = 0;
9487 // Not a '/' separated full component name; maybe an object ID?
9488 try {
9489 objectId = Integer.parseInt(name, 16);
9490 if (objects == null) {
9491 objects = new ArrayList<Integer>();
9492 }
9493 objects.add(objectId);
9494 all = false;
9495 } catch (RuntimeException e) {
9496 // Not an integer; just do string match.
9497 if (strings == null) {
9498 strings = new ArrayList<String>();
9499 }
9500 strings.add(name);
9501 all = false;
9502 }
9503 }
9504 }
9505
9506 int build(String[] args, int opti) {
9507 for (; opti<args.length; opti++) {
9508 String name = args[opti];
9509 if ("--".equals(name)) {
9510 return opti+1;
9511 }
9512 build(name);
9513 }
9514 return opti;
9515 }
9516
9517 boolean match(Object object, ComponentName comp) {
9518 if (all) {
9519 return true;
9520 }
9521 if (components != null) {
9522 for (int i=0; i<components.size(); i++) {
9523 if (components.get(i).equals(comp)) {
9524 return true;
9525 }
9526 }
9527 }
9528 if (objects != null) {
9529 for (int i=0; i<objects.size(); i++) {
9530 if (System.identityHashCode(object) == objects.get(i)) {
9531 return true;
9532 }
9533 }
9534 }
9535 if (strings != null) {
9536 String flat = comp.flattenToString();
9537 for (int i=0; i<strings.size(); i++) {
9538 if (flat.contains(strings.get(i))) {
9539 return true;
9540 }
9541 }
9542 }
9543 return false;
9544 }
9545 }
9546
Dianne Hackborn625ac272010-09-17 18:29:22 -07009547 /**
9548 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009549 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009550 * - the cmd arg isn't the flattened component name of an existing activity:
9551 * dump all activity whose component contains the cmd as a substring
9552 * - A hex number of the ActivityRecord object instance.
9553 */
9554 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9555 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009556 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009557
9558 if ("all".equals(name)) {
9559 synchronized (this) {
9560 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009561 activities.add(r1);
9562 }
9563 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009564 } else if ("top".equals(name)) {
9565 synchronized (this) {
9566 final int N = mMainStack.mHistory.size();
9567 if (N > 0) {
9568 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9569 }
9570 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009571 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009572 ItemMatcher matcher = new ItemMatcher();
9573 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009574
9575 synchronized (this) {
9576 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009577 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578 activities.add(r1);
9579 }
9580 }
9581 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009582 }
9583
9584 if (activities.size() <= 0) {
9585 return false;
9586 }
9587
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009588 String[] newArgs = new String[args.length - opti];
9589 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9590
Dianne Hackborn30d71892010-12-11 10:37:55 -08009591 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009592 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009593 for (int i=activities.size()-1; i>=0; i--) {
9594 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009595 if (needSep) {
9596 pw.println();
9597 }
9598 needSep = true;
9599 synchronized (this) {
9600 if (lastTask != r.task) {
9601 lastTask = r.task;
9602 pw.print("TASK "); pw.print(lastTask.affinity);
9603 pw.print(" id="); pw.println(lastTask.taskId);
9604 if (dumpAll) {
9605 lastTask.dump(pw, " ");
9606 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009607 }
9608 }
9609 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009610 }
9611 return true;
9612 }
9613
9614 /**
9615 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9616 * there is a thread associated with the activity.
9617 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009618 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009619 final ActivityRecord r, String[] args, boolean dumpAll) {
9620 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009621 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009622 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9623 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9624 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009625 if (r.app != null) pw.println(r.app.pid);
9626 else pw.println("(not running)");
9627 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009628 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009629 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009630 }
9631 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009632 // flush anything that is already in the PrintWriter since the thread is going
9633 // to write to the file descriptor directly
9634 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009635 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009636 TransferPipe tp = new TransferPipe();
9637 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009638 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9639 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009640 tp.go(fd);
9641 } finally {
9642 tp.kill();
9643 }
9644 } catch (IOException e) {
9645 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009646 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009647 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009648 }
9649 }
9650 }
9651
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009652 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009653 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009654 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009655 boolean onlyHistory = false;
9656
9657 if ("history".equals(dumpPackage)) {
9658 onlyHistory = true;
9659 dumpPackage = null;
9660 }
9661
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009662 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009663 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009664 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009665 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 Iterator it = mRegisteredReceivers.values().iterator();
9667 while (it.hasNext()) {
9668 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009669 if (dumpPackage != null && (r.app == null ||
9670 !dumpPackage.equals(r.app.info.packageName))) {
9671 continue;
9672 }
9673 if (!printed) {
9674 pw.println(" Registered Receivers:");
9675 needSep = true;
9676 printed = true;
9677 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009678 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 r.dump(pw, " ");
9680 }
9681 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009682
9683 if (mReceiverResolver.dump(pw, needSep ?
9684 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9685 " ", dumpPackage, false)) {
9686 needSep = true;
9687 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009688 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009689
9690 for (BroadcastQueue q : mBroadcastQueues) {
9691 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009694 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009695
Dianne Hackborn786b4402012-08-27 15:14:02 -07009696 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009697 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9698 if (needSep) {
9699 pw.println();
9700 }
9701 needSep = true;
9702 pw.print(" Sticky broadcasts for user ");
9703 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9704 StringBuilder sb = new StringBuilder(128);
9705 for (Map.Entry<String, ArrayList<Intent>> ent
9706 : mStickyBroadcasts.valueAt(user).entrySet()) {
9707 pw.print(" * Sticky action "); pw.print(ent.getKey());
9708 if (dumpAll) {
9709 pw.println(":");
9710 ArrayList<Intent> intents = ent.getValue();
9711 final int N = intents.size();
9712 for (int i=0; i<N; i++) {
9713 sb.setLength(0);
9714 sb.append(" Intent: ");
9715 intents.get(i).toShortString(sb, false, true, false, false);
9716 pw.println(sb.toString());
9717 Bundle bundle = intents.get(i).getExtras();
9718 if (bundle != null) {
9719 pw.print(" ");
9720 pw.println(bundle.toString());
9721 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009722 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009723 } else {
9724 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009725 }
9726 }
9727 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009728 }
9729
Dianne Hackborn786b4402012-08-27 15:14:02 -07009730 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009731 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009732 for (BroadcastQueue queue : mBroadcastQueues) {
9733 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9734 + queue.mBroadcastsScheduled);
9735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009736 pw.println(" mHandler:");
9737 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009738 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009740
9741 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 }
9743
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009744 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009745 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009746 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009747
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009748 ItemMatcher matcher = new ItemMatcher();
9749 matcher.build(args, opti);
9750
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009751 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009752
9753 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009754
9755 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009756 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009757 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009758 ContentProviderRecord r = mLaunchingProviders.get(i);
9759 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9760 continue;
9761 }
9762 if (!printed) {
9763 if (needSep) pw.println(" ");
9764 needSep = true;
9765 pw.println(" Launching content providers:");
9766 printed = true;
9767 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009768 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009769 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009770 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009771 }
9772
9773 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009774 if (needSep) pw.println();
9775 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009776 pw.println("Granted Uri Permissions:");
9777 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9778 int uid = mGrantedUriPermissions.keyAt(i);
9779 HashMap<Uri, UriPermission> perms
9780 = mGrantedUriPermissions.valueAt(i);
9781 pw.print(" * UID "); pw.print(uid);
9782 pw.println(" holds:");
9783 for (UriPermission perm : perms.values()) {
9784 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009785 if (dumpAll) {
9786 perm.dump(pw, " ");
9787 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009788 }
9789 }
9790 needSep = true;
9791 }
9792
9793 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009794 }
9795
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009796 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009797 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009798 boolean needSep = false;
9799
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009800 if (mIntentSenderRecords.size() > 0) {
9801 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009802 Iterator<WeakReference<PendingIntentRecord>> it
9803 = mIntentSenderRecords.values().iterator();
9804 while (it.hasNext()) {
9805 WeakReference<PendingIntentRecord> ref = it.next();
9806 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009807 if (dumpPackage != null && (rec == null
9808 || !dumpPackage.equals(rec.key.packageName))) {
9809 continue;
9810 }
9811 if (!printed) {
9812 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9813 printed = true;
9814 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009815 needSep = true;
9816 if (rec != null) {
9817 pw.print(" * "); pw.println(rec);
9818 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009819 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009820 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009821 } else {
9822 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009823 }
9824 }
9825 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009826
9827 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009828 }
9829
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009830 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009831 String prefix, String label, boolean complete, boolean brief, boolean client,
9832 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009833 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009834 boolean needNL = false;
9835 final String innerPrefix = prefix + " ";
9836 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009838 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009839 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9840 continue;
9841 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009842 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 if (needNL) {
9844 pw.println(" ");
9845 needNL = false;
9846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009847 if (lastTask != r.task) {
9848 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009849 pw.print(prefix);
9850 pw.print(full ? "* " : " ");
9851 pw.println(lastTask);
9852 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009853 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009854 } else if (complete) {
9855 // Complete + brief == give a summary. Isn't that obvious?!?
9856 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009857 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009858 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009859 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009861 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009862 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9863 pw.print(" #"); pw.print(i); pw.print(": ");
9864 pw.println(r);
9865 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009866 r.dump(pw, innerPrefix);
9867 } else if (complete) {
9868 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009869 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009870 if (r.app != null) {
9871 pw.print(innerPrefix); pw.println(r.app);
9872 }
9873 }
9874 if (client && r.app != null && r.app.thread != null) {
9875 // flush anything that is already in the PrintWriter since the thread is going
9876 // to write to the file descriptor directly
9877 pw.flush();
9878 try {
9879 TransferPipe tp = new TransferPipe();
9880 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009881 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9882 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009883 // Short timeout, since blocking here can
9884 // deadlock with the application.
9885 tp.go(fd, 2000);
9886 } finally {
9887 tp.kill();
9888 }
9889 } catch (IOException e) {
9890 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9891 } catch (RemoteException e) {
9892 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9893 }
9894 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009896 }
9897 }
9898
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009899 private static String buildOomTag(String prefix, String space, int val, int base) {
9900 if (val == base) {
9901 if (space == null) return prefix;
9902 return prefix + " ";
9903 }
9904 return prefix + "+" + Integer.toString(val-base);
9905 }
9906
9907 private static final int dumpProcessList(PrintWriter pw,
9908 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009909 String prefix, String normalLabel, String persistentLabel,
9910 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009911 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009912 final int N = list.size()-1;
9913 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009914 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009915 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9916 continue;
9917 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009918 pw.println(String.format("%s%s #%2d: %s",
9919 prefix, (r.persistent ? persistentLabel : normalLabel),
9920 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009921 if (r.persistent) {
9922 numPers++;
9923 }
9924 }
9925 return numPers;
9926 }
9927
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009928 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009929 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009930 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009931 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009932
Dianne Hackborn905577f2011-09-07 18:31:28 -07009933 ArrayList<Pair<ProcessRecord, Integer>> list
9934 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9935 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009936 ProcessRecord r = origList.get(i);
9937 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9938 continue;
9939 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009940 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9941 }
9942
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009943 if (list.size() <= 0) {
9944 return false;
9945 }
9946
Dianne Hackborn905577f2011-09-07 18:31:28 -07009947 Comparator<Pair<ProcessRecord, Integer>> comparator
9948 = new Comparator<Pair<ProcessRecord, Integer>>() {
9949 @Override
9950 public int compare(Pair<ProcessRecord, Integer> object1,
9951 Pair<ProcessRecord, Integer> object2) {
9952 if (object1.first.setAdj != object2.first.setAdj) {
9953 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9954 }
9955 if (object1.second.intValue() != object2.second.intValue()) {
9956 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9957 }
9958 return 0;
9959 }
9960 };
9961
9962 Collections.sort(list, comparator);
9963
Dianne Hackborn287952c2010-09-22 22:34:31 -07009964 final long curRealtime = SystemClock.elapsedRealtime();
9965 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9966 final long curUptime = SystemClock.uptimeMillis();
9967 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9968
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009969 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009970 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009971 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009972 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009973 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009974 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9975 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009976 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9977 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009978 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9979 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009980 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9981 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009982 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009983 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009984 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9985 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9986 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9987 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9988 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9989 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9990 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9991 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009992 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9993 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009994 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9995 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009996 } else {
9997 oomAdj = Integer.toString(r.setAdj);
9998 }
9999 String schedGroup;
10000 switch (r.setSchedGroup) {
10001 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10002 schedGroup = "B";
10003 break;
10004 case Process.THREAD_GROUP_DEFAULT:
10005 schedGroup = "F";
10006 break;
10007 default:
10008 schedGroup = Integer.toString(r.setSchedGroup);
10009 break;
10010 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010011 String foreground;
10012 if (r.foregroundActivities) {
10013 foreground = "A";
10014 } else if (r.foregroundServices) {
10015 foreground = "S";
10016 } else {
10017 foreground = " ";
10018 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010019 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010020 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010021 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10022 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010023 if (r.adjSource != null || r.adjTarget != null) {
10024 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010025 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010026 if (r.adjTarget instanceof ComponentName) {
10027 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10028 } else if (r.adjTarget != null) {
10029 pw.print(r.adjTarget.toString());
10030 } else {
10031 pw.print("{null}");
10032 }
10033 pw.print("<=");
10034 if (r.adjSource instanceof ProcessRecord) {
10035 pw.print("Proc{");
10036 pw.print(((ProcessRecord)r.adjSource).toShortString());
10037 pw.println("}");
10038 } else if (r.adjSource != null) {
10039 pw.println(r.adjSource.toString());
10040 } else {
10041 pw.println("{null}");
10042 }
10043 }
10044 if (inclDetails) {
10045 pw.print(prefix);
10046 pw.print(" ");
10047 pw.print("oom: max="); pw.print(r.maxAdj);
10048 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010049 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010050 pw.print(" curRaw="); pw.print(r.curRawAdj);
10051 pw.print(" setRaw="); pw.print(r.setRawAdj);
10052 pw.print(" cur="); pw.print(r.curAdj);
10053 pw.print(" set="); pw.println(r.setAdj);
10054 pw.print(prefix);
10055 pw.print(" ");
10056 pw.print("keeping="); pw.print(r.keeping);
10057 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010058 pw.print(" empty="); pw.print(r.empty);
10059 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010060
10061 if (!r.keeping) {
10062 if (r.lastWakeTime != 0) {
10063 long wtime;
10064 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10065 synchronized (stats) {
10066 wtime = stats.getProcessWakeTime(r.info.uid,
10067 r.pid, curRealtime);
10068 }
10069 long timeUsed = wtime - r.lastWakeTime;
10070 pw.print(prefix);
10071 pw.print(" ");
10072 pw.print("keep awake over ");
10073 TimeUtils.formatDuration(realtimeSince, pw);
10074 pw.print(" used ");
10075 TimeUtils.formatDuration(timeUsed, pw);
10076 pw.print(" (");
10077 pw.print((timeUsed*100)/realtimeSince);
10078 pw.println("%)");
10079 }
10080 if (r.lastCpuTime != 0) {
10081 long timeUsed = r.curCpuTime - r.lastCpuTime;
10082 pw.print(prefix);
10083 pw.print(" ");
10084 pw.print("run cpu over ");
10085 TimeUtils.formatDuration(uptimeSince, pw);
10086 pw.print(" used ");
10087 TimeUtils.formatDuration(timeUsed, pw);
10088 pw.print(" (");
10089 pw.print((timeUsed*100)/uptimeSince);
10090 pw.println("%)");
10091 }
10092 }
10093 }
10094 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010095 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010096 }
10097
Dianne Hackbornb437e092011-08-05 17:50:29 -070010098 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010099 ArrayList<ProcessRecord> procs;
10100 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010101 if (args != null && args.length > start
10102 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010103 procs = new ArrayList<ProcessRecord>();
10104 int pid = -1;
10105 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010106 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010107 } catch (NumberFormatException e) {
10108
10109 }
10110 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10111 ProcessRecord proc = mLruProcesses.get(i);
10112 if (proc.pid == pid) {
10113 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010114 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010115 procs.add(proc);
10116 }
10117 }
10118 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010119 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010120 return null;
10121 }
10122 } else {
10123 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10124 }
10125 }
10126 return procs;
10127 }
10128
10129 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10130 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010131 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010132 if (procs == null) {
10133 return;
10134 }
10135
10136 long uptime = SystemClock.uptimeMillis();
10137 long realtime = SystemClock.elapsedRealtime();
10138 pw.println("Applications Graphics Acceleration Info:");
10139 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10140
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010141 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10142 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010143 if (r.thread != null) {
10144 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10145 pw.flush();
10146 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010147 TransferPipe tp = new TransferPipe();
10148 try {
10149 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10150 tp.go(fd);
10151 } finally {
10152 tp.kill();
10153 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010154 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010155 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010156 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010157 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010158 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010159 pw.flush();
10160 }
10161 }
10162 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010163 }
10164
Jeff Brown6754ba22011-12-14 20:20:01 -080010165 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10166 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10167 if (procs == null) {
10168 return;
10169 }
10170
10171 pw.println("Applications Database Info:");
10172
10173 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10174 ProcessRecord r = procs.get(i);
10175 if (r.thread != null) {
10176 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10177 pw.flush();
10178 try {
10179 TransferPipe tp = new TransferPipe();
10180 try {
10181 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10182 tp.go(fd);
10183 } finally {
10184 tp.kill();
10185 }
10186 } catch (IOException e) {
10187 pw.println("Failure while dumping the app: " + r);
10188 pw.flush();
10189 } catch (RemoteException e) {
10190 pw.println("Got a RemoteException while dumping the app " + r);
10191 pw.flush();
10192 }
10193 }
10194 }
10195 }
10196
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010197 final static class MemItem {
10198 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010199 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010200 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010201 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010202 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010203
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010204 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010205 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010206 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010207 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010208 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010209 }
10210 }
10211
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010212 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010213 boolean sort) {
10214 if (sort) {
10215 Collections.sort(items, new Comparator<MemItem>() {
10216 @Override
10217 public int compare(MemItem lhs, MemItem rhs) {
10218 if (lhs.pss < rhs.pss) {
10219 return 1;
10220 } else if (lhs.pss > rhs.pss) {
10221 return -1;
10222 }
10223 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010224 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010225 });
10226 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010227
10228 for (int i=0; i<items.size(); i++) {
10229 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010230 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010231 if (mi.subitems != null) {
10232 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10233 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010234 }
10235 }
10236
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010237 // These are in KB.
10238 static final long[] DUMP_MEM_BUCKETS = new long[] {
10239 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10240 120*1024, 160*1024, 200*1024,
10241 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10242 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10243 };
10244
Dianne Hackborn672342c2011-11-29 11:29:02 -080010245 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10246 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010247 int start = label.lastIndexOf('.');
10248 if (start >= 0) start++;
10249 else start = 0;
10250 int end = label.length();
10251 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10252 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10253 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10254 out.append(bucket);
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 return;
10258 }
10259 }
10260 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010261 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010262 out.append(label, start, end);
10263 }
10264
10265 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10266 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10267 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10268 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10269 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10270 };
10271 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10272 "System", "Persistent", "Foreground",
10273 "Visible", "Perceptible", "Heavy Weight",
10274 "Backup", "A Services", "Home", "Previous",
10275 "B Services", "Background"
10276 };
10277
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010278 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010279 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010280 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010281 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010282 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010283
10284 int opti = 0;
10285 while (opti < args.length) {
10286 String opt = args[opti];
10287 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10288 break;
10289 }
10290 opti++;
10291 if ("-a".equals(opt)) {
10292 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010293 } else if ("--oom".equals(opt)) {
10294 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010295 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010296 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010297 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010298 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010299 pw.println("If [process] is specified it can be the name or ");
10300 pw.println("pid of a specific process to dump.");
10301 return;
10302 } else {
10303 pw.println("Unknown argument: " + opt + "; use -h for help");
10304 }
10305 }
10306
10307 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010308 if (procs == null) {
10309 return;
10310 }
10311
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010312 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010313 long uptime = SystemClock.uptimeMillis();
10314 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010315
10316 if (procs.size() == 1 || isCheckinRequest) {
10317 dumpAll = true;
10318 }
10319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010320 if (isCheckinRequest) {
10321 // short checkin version
10322 pw.println(uptime + "," + realtime);
10323 pw.flush();
10324 } else {
10325 pw.println("Applications Memory Usage (kB):");
10326 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10327 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010328
Dianne Hackbornb437e092011-08-05 17:50:29 -070010329 String[] innerArgs = new String[args.length-opti];
10330 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10331
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010332 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10333 long nativePss=0, dalvikPss=0, otherPss=0;
10334 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10335
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010336 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10337 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10338 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010339
10340 long totalPss = 0;
10341
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010342 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10343 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010344 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010345 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010346 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10347 pw.flush();
10348 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010349 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350 if (dumpAll) {
10351 try {
10352 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10353 } catch (RemoteException e) {
10354 if (!isCheckinRequest) {
10355 pw.println("Got RemoteException!");
10356 pw.flush();
10357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010358 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010359 } else {
10360 mi = new Debug.MemoryInfo();
10361 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010362 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010363
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010364 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010365 long myTotalPss = mi.getTotalPss();
10366 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010367 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010368 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010369 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010370
10371 nativePss += mi.nativePss;
10372 dalvikPss += mi.dalvikPss;
10373 otherPss += mi.otherPss;
10374 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10375 long mem = mi.getOtherPss(j);
10376 miscPss[j] += mem;
10377 otherPss -= mem;
10378 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010379
10380 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010381 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10382 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010383 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010384 if (oomProcs[oomIndex] == null) {
10385 oomProcs[oomIndex] = new ArrayList<MemItem>();
10386 }
10387 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010388 break;
10389 }
10390 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010392 }
10393 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010394
10395 if (!isCheckinRequest && procs.size() > 1) {
10396 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10397
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010398 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10399 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10400 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010401 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010402 String label = Debug.MemoryInfo.getOtherLabel(j);
10403 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010404 }
10405
Dianne Hackbornb437e092011-08-05 17:50:29 -070010406 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10407 for (int j=0; j<oomPss.length; j++) {
10408 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010409 String label = DUMP_MEM_OOM_LABEL[j];
10410 MemItem item = new MemItem(label, label, oomPss[j],
10411 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010412 item.subitems = oomProcs[j];
10413 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010414 }
10415 }
10416
Dianne Hackborn672342c2011-11-29 11:29:02 -080010417 if (outTag != null || outStack != null) {
10418 if (outTag != null) {
10419 appendMemBucket(outTag, totalPss, "total", false);
10420 }
10421 if (outStack != null) {
10422 appendMemBucket(outStack, totalPss, "total", true);
10423 }
10424 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010425 for (int i=0; i<oomMems.size(); i++) {
10426 MemItem miCat = oomMems.get(i);
10427 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10428 continue;
10429 }
10430 if (miCat.id < ProcessList.SERVICE_ADJ
10431 || miCat.id == ProcessList.HOME_APP_ADJ
10432 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010433 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10434 outTag.append(" / ");
10435 }
10436 if (outStack != null) {
10437 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10438 if (firstLine) {
10439 outStack.append(":");
10440 firstLine = false;
10441 }
10442 outStack.append("\n\t at ");
10443 } else {
10444 outStack.append("$");
10445 }
10446 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010447 for (int j=0; j<miCat.subitems.size(); j++) {
10448 MemItem mi = miCat.subitems.get(j);
10449 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010450 if (outTag != null) {
10451 outTag.append(" ");
10452 }
10453 if (outStack != null) {
10454 outStack.append("$");
10455 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010456 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010457 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10458 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10459 }
10460 if (outStack != null) {
10461 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10462 }
10463 }
10464 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10465 outStack.append("(");
10466 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10467 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10468 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10469 outStack.append(":");
10470 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10471 }
10472 }
10473 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010474 }
10475 }
10476 }
10477 }
10478
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010479 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010480 pw.println();
10481 pw.println("Total PSS by process:");
10482 dumpMemItems(pw, " ", procMems, true);
10483 pw.println();
10484 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010485 pw.println("Total PSS by OOM adjustment:");
10486 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010487 if (!oomOnly) {
10488 PrintWriter out = categoryPw != null ? categoryPw : pw;
10489 out.println();
10490 out.println("Total PSS by category:");
10491 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010492 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010493 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010494 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010495 final int[] SINGLE_LONG_FORMAT = new int[] {
10496 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10497 };
10498 long[] longOut = new long[1];
10499 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10500 SINGLE_LONG_FORMAT, null, longOut, null);
10501 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10502 longOut[0] = 0;
10503 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10504 SINGLE_LONG_FORMAT, null, longOut, null);
10505 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10506 longOut[0] = 0;
10507 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10508 SINGLE_LONG_FORMAT, null, longOut, null);
10509 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10510 longOut[0] = 0;
10511 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10512 SINGLE_LONG_FORMAT, null, longOut, null);
10513 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10514 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10515 pw.print(shared); pw.println(" kB");
10516 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10517 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010519 }
10520
10521 /**
10522 * Searches array of arguments for the specified string
10523 * @param args array of argument strings
10524 * @param value value to search for
10525 * @return true if the value is contained in the array
10526 */
10527 private static boolean scanArgs(String[] args, String value) {
10528 if (args != null) {
10529 for (String arg : args) {
10530 if (value.equals(arg)) {
10531 return true;
10532 }
10533 }
10534 }
10535 return false;
10536 }
10537
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010538 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10539 ContentProviderRecord cpr, boolean always) {
10540 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10541
10542 if (!inLaunching || always) {
10543 synchronized (cpr) {
10544 cpr.launchingApp = null;
10545 cpr.notifyAll();
10546 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010547 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010548 String names[] = cpr.info.authority.split(";");
10549 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010550 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 }
10552 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010553
10554 for (int i=0; i<cpr.connections.size(); i++) {
10555 ContentProviderConnection conn = cpr.connections.get(i);
10556 if (conn.waiting) {
10557 // If this connection is waiting for the provider, then we don't
10558 // need to mess with its process unless we are always removing
10559 // or for some reason the provider is not currently launching.
10560 if (inLaunching && !always) {
10561 continue;
10562 }
10563 }
10564 ProcessRecord capp = conn.client;
10565 conn.dead = true;
10566 if (conn.stableCount > 0) {
10567 if (!capp.persistent && capp.thread != null
10568 && capp.pid != 0
10569 && capp.pid != MY_PID) {
10570 Slog.i(TAG, "Kill " + capp.processName
10571 + " (pid " + capp.pid + "): provider " + cpr.info.name
10572 + " in dying process " + (proc != null ? proc.processName : "??"));
10573 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10574 capp.processName, capp.setAdj, "dying provider "
10575 + cpr.name.toShortString());
10576 Process.killProcessQuiet(capp.pid);
10577 }
10578 } else if (capp.thread != null && conn.provider.provider != null) {
10579 try {
10580 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10581 } catch (RemoteException e) {
10582 }
10583 // In the protocol here, we don't expect the client to correctly
10584 // clean up this connection, we'll just remove it.
10585 cpr.connections.remove(i);
10586 conn.client.conProviders.remove(conn);
10587 }
10588 }
10589
10590 if (inLaunching && always) {
10591 mLaunchingProviders.remove(cpr);
10592 }
10593 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010594 }
10595
10596 /**
10597 * Main code for cleaning up a process when it has gone away. This is
10598 * called both as a result of the process dying, or directly when stopping
10599 * a process when running in single process mode.
10600 */
10601 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010602 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010603 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010604 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 }
10606
Dianne Hackborn36124872009-10-08 16:22:03 -070010607 mProcessesToGc.remove(app);
10608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010609 // Dismiss any open dialogs.
10610 if (app.crashDialog != null) {
10611 app.crashDialog.dismiss();
10612 app.crashDialog = null;
10613 }
10614 if (app.anrDialog != null) {
10615 app.anrDialog.dismiss();
10616 app.anrDialog = null;
10617 }
10618 if (app.waitDialog != null) {
10619 app.waitDialog.dismiss();
10620 app.waitDialog = null;
10621 }
10622
10623 app.crashing = false;
10624 app.notResponding = false;
10625
10626 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010627 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 app.thread = null;
10629 app.forcingToForeground = null;
10630 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010631 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010632 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010633 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010634
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010635 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636
10637 boolean restart = false;
10638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 // Remove published content providers.
10640 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010641 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010642 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010643 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010644
10645 final boolean always = app.bad || !allowRestart;
10646 if (removeDyingProviderLocked(app, cpr, always) || always) {
10647 // We left the provider in the launching list, need to
10648 // restart it.
10649 restart = true;
10650 }
10651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010652 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010653 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010654 }
10655 app.pubProviders.clear();
10656 }
10657
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010658 // Take care of any launching providers waiting for this process.
10659 if (checkAppInLaunchingProvidersLocked(app, false)) {
10660 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010661 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 // Unregister from connected content providers.
10664 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010665 for (int i=0; i<app.conProviders.size(); i++) {
10666 ContentProviderConnection conn = app.conProviders.get(i);
10667 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 }
10669 app.conProviders.clear();
10670 }
10671
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010672 // At this point there may be remaining entries in mLaunchingProviders
10673 // where we were the only one waiting, so they are no longer of use.
10674 // Look for these and clean up if found.
10675 // XXX Commented out for now. Trying to figure out a way to reproduce
10676 // the actual situation to identify what is actually going on.
10677 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010678 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010679 ContentProviderRecord cpr = (ContentProviderRecord)
10680 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010681 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010682 synchronized (cpr) {
10683 cpr.launchingApp = null;
10684 cpr.notifyAll();
10685 }
10686 }
10687 }
10688 }
10689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010690 skipCurrentReceiverLocked(app);
10691
10692 // Unregister any receivers.
10693 if (app.receivers.size() > 0) {
10694 Iterator<ReceiverList> it = app.receivers.iterator();
10695 while (it.hasNext()) {
10696 removeReceiverLocked(it.next());
10697 }
10698 app.receivers.clear();
10699 }
10700
Christopher Tate181fafa2009-05-14 11:12:14 -070010701 // If the app is undergoing backup, tell the backup manager about it
10702 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010703 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010704 try {
10705 IBackupManager bm = IBackupManager.Stub.asInterface(
10706 ServiceManager.getService(Context.BACKUP_SERVICE));
10707 bm.agentDisconnected(app.info.packageName);
10708 } catch (RemoteException e) {
10709 // can't happen; backup manager is local
10710 }
10711 }
10712
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010713 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10714 ProcessChangeItem item = mPendingProcessChanges.get(i);
10715 if (item.pid == app.pid) {
10716 mPendingProcessChanges.remove(i);
10717 mAvailProcessChanges.add(item);
10718 }
10719 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010720 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010722 // If the caller is restarting this app, then leave it in its
10723 // current lists and let the caller take care of it.
10724 if (restarting) {
10725 return;
10726 }
10727
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010728 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010729 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010731 mProcessNames.remove(app.processName, app.uid);
10732 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010733 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010734 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10735 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010736 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 } else if (!app.removed) {
10739 // This app is persistent, so we need to keep its record around.
10740 // If it is not already on the pending app list, add it there
10741 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10743 mPersistentStartingProcesses.add(app);
10744 restart = true;
10745 }
10746 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010747 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10748 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 mProcessesOnHold.remove(app);
10750
The Android Open Source Project4df24232009-03-05 14:34:35 -080010751 if (app == mHomeProcess) {
10752 mHomeProcess = null;
10753 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010754 if (app == mPreviousProcess) {
10755 mPreviousProcess = null;
10756 }
10757
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010758 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010759 // We have components that still need to be running in the
10760 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010761 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 startProcessLocked(app, "restart", app.processName);
10763 } else if (app.pid > 0 && app.pid != MY_PID) {
10764 // Goodbye!
10765 synchronized (mPidsSelfLocked) {
10766 mPidsSelfLocked.remove(app.pid);
10767 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10768 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010769 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 }
10771 }
10772
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010773 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10774 // Look through the content providers we are waiting to have launched,
10775 // and if any run in this process then either schedule a restart of
10776 // the process or kill the client waiting for it if this process has
10777 // gone bad.
10778 int NL = mLaunchingProviders.size();
10779 boolean restart = false;
10780 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010781 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010782 if (cpr.launchingApp == app) {
10783 if (!alwaysBad && !app.bad) {
10784 restart = true;
10785 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010786 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010787 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010788 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010789 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010790 }
10791 }
10792 }
10793 return restart;
10794 }
10795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 // =========================================================
10797 // SERVICES
10798 // =========================================================
10799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010800 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10801 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010802 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010803 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010804 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010805 }
10806 }
10807
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010808 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010809 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010810 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010811 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010812 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010813 }
10814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010815 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010816 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010817 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 // Refuse possible leaked file descriptors
10819 if (service != null && service.hasFileDescriptors() == true) {
10820 throw new IllegalArgumentException("File descriptors passed in Intent");
10821 }
10822
Amith Yamasani742a6712011-05-04 14:49:28 -070010823 if (DEBUG_SERVICE)
10824 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 synchronized(this) {
10826 final int callingPid = Binder.getCallingPid();
10827 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010828 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010830 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010831 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 Binder.restoreCallingIdentity(origId);
10833 return res;
10834 }
10835 }
10836
10837 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010838 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010839 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010840 if (DEBUG_SERVICE)
10841 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010842 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010843 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010844 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 Binder.restoreCallingIdentity(origId);
10846 return res;
10847 }
10848 }
10849
10850 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010851 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010852 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010853 // Refuse possible leaked file descriptors
10854 if (service != null && service.hasFileDescriptors() == true) {
10855 throw new IllegalArgumentException("File descriptors passed in Intent");
10856 }
10857
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010858 checkValidCaller(Binder.getCallingUid(), userId);
10859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010861 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 }
10864
10865 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010866 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 // Refuse possible leaked file descriptors
10868 if (service != null && service.hasFileDescriptors() == true) {
10869 throw new IllegalArgumentException("File descriptors passed in Intent");
10870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010872 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874 }
10875
10876 public boolean stopServiceToken(ComponentName className, IBinder token,
10877 int startId) {
10878 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010879 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 }
10882
10883 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010884 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010885 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010886 mServices.setServiceForegroundLocked(className, token, id, notification,
10887 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 }
10889 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010890
Dianne Hackborn41203752012-08-31 14:05:51 -070010891 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10892 boolean requireFull, String name, String callerPackage) {
10893 synchronized(this) {
10894 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10895 requireFull, name, callerPackage);
10896 }
10897 }
10898
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010899 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10900 boolean requireFull, String name, String callerPackage) {
10901 final int callingUserId = UserHandle.getUserId(callingUid);
10902 if (callingUserId != userId) {
10903 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10904 if ((requireFull || checkComponentPermission(
10905 android.Manifest.permission.INTERACT_ACROSS_USERS,
10906 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10907 && checkComponentPermission(
10908 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10909 callingPid, callingUid, -1, true)
10910 != PackageManager.PERMISSION_GRANTED) {
10911 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10912 // In this case, they would like to just execute as their
10913 // owner user instead of failing.
10914 userId = callingUserId;
10915 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010916 StringBuilder builder = new StringBuilder(128);
10917 builder.append("Permission Denial: ");
10918 builder.append(name);
10919 if (callerPackage != null) {
10920 builder.append(" from ");
10921 builder.append(callerPackage);
10922 }
10923 builder.append(" asks to run as user ");
10924 builder.append(userId);
10925 builder.append(" but is calling from user ");
10926 builder.append(UserHandle.getUserId(callingUid));
10927 builder.append("; this requires ");
10928 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10929 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010930 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010931 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10932 }
10933 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010934 Slog.w(TAG, msg);
10935 throw new SecurityException(msg);
10936 }
10937 }
10938 }
10939 if (userId == UserHandle.USER_CURRENT
10940 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10941 userId = mCurrentUserId;
10942 }
10943 if (!allowAll && userId < 0) {
10944 throw new IllegalArgumentException(
10945 "Call does not support special user #" + userId);
10946 }
10947 }
10948 return userId;
10949 }
10950
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010951 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10952 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010953 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010954 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010955 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10956 if (ActivityManager.checkUidPermission(
10957 android.Manifest.permission.INTERACT_ACROSS_USERS,
10958 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10959 ComponentName comp = new ComponentName(aInfo.packageName, className);
10960 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10961 + " requests FLAG_SINGLE_USER, but app does not hold "
10962 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10963 Slog.w(TAG, msg);
10964 throw new SecurityException(msg);
10965 }
10966 result = true;
10967 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010968 } else if (componentProcessName == aInfo.packageName) {
10969 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10970 } else if ("system".equals(componentProcessName)) {
10971 result = true;
10972 }
10973 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010974 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10975 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010976 }
10977 return result;
10978 }
10979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 public int bindService(IApplicationThread caller, IBinder token,
10981 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010982 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010983 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 // Refuse possible leaked file descriptors
10985 if (service != null && service.hasFileDescriptors() == true) {
10986 throw new IllegalArgumentException("File descriptors passed in Intent");
10987 }
10988
10989 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010990 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10991 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010992 }
10993 }
10994
10995 public boolean unbindService(IServiceConnection connection) {
10996 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010997 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 }
11000
11001 public void publishService(IBinder token, Intent intent, IBinder service) {
11002 // Refuse possible leaked file descriptors
11003 if (intent != null && intent.hasFileDescriptors() == true) {
11004 throw new IllegalArgumentException("File descriptors passed in Intent");
11005 }
11006
11007 synchronized(this) {
11008 if (!(token instanceof ServiceRecord)) {
11009 throw new IllegalArgumentException("Invalid service token");
11010 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011011 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 }
11013 }
11014
11015 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11016 // Refuse possible leaked file descriptors
11017 if (intent != null && intent.hasFileDescriptors() == true) {
11018 throw new IllegalArgumentException("File descriptors passed in Intent");
11019 }
11020
11021 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011022 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 }
11024 }
11025
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011026 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 synchronized(this) {
11028 if (!(token instanceof ServiceRecord)) {
11029 throw new IllegalArgumentException("Invalid service token");
11030 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011031 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011033 }
11034
11035 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011036 // BACKUP AND RESTORE
11037 // =========================================================
11038
11039 // Cause the target app to be launched if necessary and its backup agent
11040 // instantiated. The backup agent will invoke backupAgentCreated() on the
11041 // activity manager to announce its creation.
11042 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011043 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011044 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11045
11046 synchronized(this) {
11047 // !!! TODO: currently no check here that we're already bound
11048 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11049 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11050 synchronized (stats) {
11051 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11052 }
11053
Dianne Hackborne7f97212011-02-24 14:40:20 -080011054 // Backup agent is now in use, its package can't be stopped.
11055 try {
11056 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011057 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011058 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011059 } catch (IllegalArgumentException e) {
11060 Slog.w(TAG, "Failed trying to unstop package "
11061 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011062 }
11063
Christopher Tate181fafa2009-05-14 11:12:14 -070011064 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011065 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11066 ? new ComponentName(app.packageName, app.backupAgentName)
11067 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011068 // startProcessLocked() returns existing proc's record if it's already running
11069 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011070 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011071 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011072 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011073 return false;
11074 }
11075
11076 r.app = proc;
11077 mBackupTarget = r;
11078 mBackupAppName = app.packageName;
11079
Christopher Tate6fa95972009-06-05 18:43:55 -070011080 // Try not to kill the process during backup
11081 updateOomAdjLocked(proc);
11082
Christopher Tate181fafa2009-05-14 11:12:14 -070011083 // If the process is already attached, schedule the creation of the backup agent now.
11084 // If it is not yet live, this will be done when it attaches to the framework.
11085 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011086 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011087 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011088 proc.thread.scheduleCreateBackupAgent(app,
11089 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011090 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011091 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011092 }
11093 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011094 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011095 }
11096 // Invariants: at this point, the target app process exists and the application
11097 // is either already running or in the process of coming up. mBackupTarget and
11098 // mBackupAppName describe the app, so that when it binds back to the AM we
11099 // know that it's scheduled for a backup-agent operation.
11100 }
11101
11102 return true;
11103 }
11104
11105 // A backup agent has just come up
11106 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011107 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011108 + " = " + agent);
11109
11110 synchronized(this) {
11111 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011112 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011113 return;
11114 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011115 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011116
Dianne Hackborn06740692010-09-22 22:46:21 -070011117 long oldIdent = Binder.clearCallingIdentity();
11118 try {
11119 IBackupManager bm = IBackupManager.Stub.asInterface(
11120 ServiceManager.getService(Context.BACKUP_SERVICE));
11121 bm.agentConnected(agentPackageName, agent);
11122 } catch (RemoteException e) {
11123 // can't happen; the backup manager service is local
11124 } catch (Exception e) {
11125 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11126 e.printStackTrace();
11127 } finally {
11128 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011129 }
11130 }
11131
11132 // done with this agent
11133 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011134 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011135 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011136 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011137 return;
11138 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011139
11140 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011141 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011142 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011143 return;
11144 }
11145
Christopher Tate181fafa2009-05-14 11:12:14 -070011146 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011147 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011148 return;
11149 }
11150
Christopher Tate6fa95972009-06-05 18:43:55 -070011151 ProcessRecord proc = mBackupTarget.app;
11152 mBackupTarget = null;
11153 mBackupAppName = null;
11154
11155 // Not backing this app up any more; reset its OOM adjustment
11156 updateOomAdjLocked(proc);
11157
Christopher Tatec7b31e32009-06-10 15:49:30 -070011158 // If the app crashed during backup, 'thread' will be null here
11159 if (proc.thread != null) {
11160 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011161 proc.thread.scheduleDestroyBackupAgent(appInfo,
11162 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011163 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011164 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011165 e.printStackTrace();
11166 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011167 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011168 }
11169 }
11170 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 // BROADCASTS
11172 // =========================================================
11173
Josh Bartel7f208742010-02-25 11:01:44 -060011174 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011175 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011176 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011177 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11178 if (stickies == null) {
11179 return cur;
11180 }
11181 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011182 if (list == null) {
11183 return cur;
11184 }
11185 int N = list.size();
11186 for (int i=0; i<N; i++) {
11187 Intent intent = list.get(i);
11188 if (filter.match(resolver, intent, true, TAG) >= 0) {
11189 if (cur == null) {
11190 cur = new ArrayList<Intent>();
11191 }
11192 cur.add(intent);
11193 }
11194 }
11195 return cur;
11196 }
11197
Christopher Tatef46723b2012-01-26 14:19:24 -080011198 boolean isPendingBroadcastProcessLocked(int pid) {
11199 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11200 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011202
Christopher Tatef46723b2012-01-26 14:19:24 -080011203 void skipPendingBroadcastLocked(int pid) {
11204 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11205 for (BroadcastQueue queue : mBroadcastQueues) {
11206 queue.skipPendingBroadcastLocked(pid);
11207 }
11208 }
11209
11210 // The app just attached; send any pending broadcasts that it should receive
11211 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11212 boolean didSomething = false;
11213 for (BroadcastQueue queue : mBroadcastQueues) {
11214 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011216 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217 }
11218
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011219 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011220 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011221 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011222 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011223 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 synchronized(this) {
11225 ProcessRecord callerApp = null;
11226 if (caller != null) {
11227 callerApp = getRecordForAppLocked(caller);
11228 if (callerApp == null) {
11229 throw new SecurityException(
11230 "Unable to find app for caller " + caller
11231 + " (pid=" + Binder.getCallingPid()
11232 + ") when registering receiver " + receiver);
11233 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011234 if (callerApp.info.uid != Process.SYSTEM_UID &&
11235 !callerApp.pkgList.contains(callerPackage)) {
11236 throw new SecurityException("Given caller package " + callerPackage
11237 + " is not running in process " + callerApp);
11238 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011239 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011240 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011241 } else {
11242 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011243 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011244 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 }
11246
Dianne Hackborn20e80982012-08-31 19:00:44 -070011247 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11248 true, true, "registerReceiver", callerPackage);
11249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 List allSticky = null;
11251
11252 // Look for any matching sticky broadcasts...
11253 Iterator actions = filter.actionsIterator();
11254 if (actions != null) {
11255 while (actions.hasNext()) {
11256 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011257 allSticky = getStickiesLocked(action, filter, allSticky,
11258 UserHandle.USER_ALL);
11259 allSticky = getStickiesLocked(action, filter, allSticky,
11260 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 }
11262 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011263 allSticky = getStickiesLocked(null, filter, allSticky,
11264 UserHandle.USER_ALL);
11265 allSticky = getStickiesLocked(null, filter, allSticky,
11266 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011267 }
11268
11269 // The first sticky in the list is returned directly back to
11270 // the client.
11271 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11272
Joe Onorato8a9b2202010-02-26 18:56:32 -080011273 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 + ": " + sticky);
11275
11276 if (receiver == null) {
11277 return sticky;
11278 }
11279
11280 ReceiverList rl
11281 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11282 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011283 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11284 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 if (rl.app != null) {
11286 rl.app.receivers.add(rl);
11287 } else {
11288 try {
11289 receiver.asBinder().linkToDeath(rl, 0);
11290 } catch (RemoteException e) {
11291 return sticky;
11292 }
11293 rl.linkedToDeath = true;
11294 }
11295 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011296 } else if (rl.uid != callingUid) {
11297 throw new IllegalArgumentException(
11298 "Receiver requested to register for uid " + callingUid
11299 + " was previously registered for uid " + rl.uid);
11300 } else if (rl.pid != callingPid) {
11301 throw new IllegalArgumentException(
11302 "Receiver requested to register for pid " + callingPid
11303 + " was previously registered for pid " + rl.pid);
11304 } else if (rl.userId != userId) {
11305 throw new IllegalArgumentException(
11306 "Receiver requested to register for user " + userId
11307 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011308 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011309 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011310 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 rl.add(bf);
11312 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011313 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 }
11315 mReceiverResolver.addFilter(bf);
11316
11317 // Enqueue broadcasts for all existing stickies that match
11318 // this filter.
11319 if (allSticky != null) {
11320 ArrayList receivers = new ArrayList();
11321 receivers.add(bf);
11322
11323 int N = allSticky.size();
11324 for (int i=0; i<N; i++) {
11325 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011326 BroadcastQueue queue = broadcastQueueForIntent(intent);
11327 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011329 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011330 queue.enqueueParallelBroadcastLocked(r);
11331 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011332 }
11333 }
11334
11335 return sticky;
11336 }
11337 }
11338
11339 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011340 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341
Christopher Tatef46723b2012-01-26 14:19:24 -080011342 final long origId = Binder.clearCallingIdentity();
11343 try {
11344 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345
Christopher Tatef46723b2012-01-26 14:19:24 -080011346 synchronized(this) {
11347 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011349 if (rl != null) {
11350 if (rl.curBroadcast != null) {
11351 BroadcastRecord r = rl.curBroadcast;
11352 final boolean doNext = finishReceiverLocked(
11353 receiver.asBinder(), r.resultCode, r.resultData,
11354 r.resultExtras, r.resultAbort, true);
11355 if (doNext) {
11356 doTrim = true;
11357 r.queue.processNextBroadcast(false);
11358 }
11359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360
Christopher Tatef46723b2012-01-26 14:19:24 -080011361 if (rl.app != null) {
11362 rl.app.receivers.remove(rl);
11363 }
11364 removeReceiverLocked(rl);
11365 if (rl.linkedToDeath) {
11366 rl.linkedToDeath = false;
11367 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 }
11370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011371
Christopher Tatef46723b2012-01-26 14:19:24 -080011372 // If we actually concluded any broadcasts, we might now be able
11373 // to trim the recipients' apps from our working set
11374 if (doTrim) {
11375 trimApplications();
11376 return;
11377 }
11378
11379 } finally {
11380 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 }
11383
11384 void removeReceiverLocked(ReceiverList rl) {
11385 mRegisteredReceivers.remove(rl.receiver.asBinder());
11386 int N = rl.size();
11387 for (int i=0; i<N; i++) {
11388 mReceiverResolver.removeFilter(rl.get(i));
11389 }
11390 }
11391
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011392 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011393 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11394 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011395 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011396 try {
11397 r.thread.dispatchPackageBroadcast(cmd, packages);
11398 } catch (RemoteException ex) {
11399 }
11400 }
11401 }
11402 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011403
11404 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11405 int[] users) {
11406 List<ResolveInfo> receivers = null;
11407 try {
11408 HashSet<ComponentName> singleUserReceivers = null;
11409 boolean scannedFirstReceivers = false;
11410 for (int user : users) {
11411 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11412 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11413 if (newReceivers != null && newReceivers.size() == 0) {
11414 newReceivers = null;
11415 }
11416 if (receivers == null) {
11417 receivers = newReceivers;
11418 } else if (newReceivers != null) {
11419 // We need to concatenate the additional receivers
11420 // found with what we have do far. This would be easy,
11421 // but we also need to de-dup any receivers that are
11422 // singleUser.
11423 if (!scannedFirstReceivers) {
11424 // Collect any single user receivers we had already retrieved.
11425 scannedFirstReceivers = true;
11426 for (int i=0; i<receivers.size(); i++) {
11427 ResolveInfo ri = receivers.get(i);
11428 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11429 ComponentName cn = new ComponentName(
11430 ri.activityInfo.packageName, ri.activityInfo.name);
11431 if (singleUserReceivers == null) {
11432 singleUserReceivers = new HashSet<ComponentName>();
11433 }
11434 singleUserReceivers.add(cn);
11435 }
11436 }
11437 }
11438 // Add the new results to the existing results, tracking
11439 // and de-dupping single user receivers.
11440 for (int i=0; i<newReceivers.size(); i++) {
11441 ResolveInfo ri = receivers.get(i);
11442 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11443 ComponentName cn = new ComponentName(
11444 ri.activityInfo.packageName, ri.activityInfo.name);
11445 if (singleUserReceivers == null) {
11446 singleUserReceivers = new HashSet<ComponentName>();
11447 }
11448 if (!singleUserReceivers.contains(cn)) {
11449 singleUserReceivers.add(cn);
11450 receivers.add(ri);
11451 }
11452 } else {
11453 receivers.add(ri);
11454 }
11455 }
11456 }
11457 }
11458 } catch (RemoteException ex) {
11459 // pm is in same process, this will never happen.
11460 }
11461 return receivers;
11462 }
11463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011464 private final int broadcastIntentLocked(ProcessRecord callerApp,
11465 String callerPackage, Intent intent, String resolvedType,
11466 IIntentReceiver resultTo, int resultCode, String resultData,
11467 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011468 boolean ordered, boolean sticky, int callingPid, int callingUid,
11469 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 intent = new Intent(intent);
11471
Dianne Hackborne7f97212011-02-24 14:40:20 -080011472 // By default broadcasts do not go to stopped apps.
11473 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11474
Joe Onorato8a9b2202010-02-26 18:56:32 -080011475 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011477 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011478 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011479 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011481
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011482 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11483 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011484
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011485 // Make sure that the user who is receiving this broadcast is started
11486 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011487 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011488 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11489 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11490 Slog.w(TAG, "Skipping broadcast of " + intent
11491 + ": user " + userId + " is stopped");
11492 return ActivityManager.BROADCAST_SUCCESS;
11493 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011494 }
11495
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011496 /*
11497 * Prevent non-system code (defined here to be non-persistent
11498 * processes) from sending protected broadcasts.
11499 */
11500 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11501 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11502 callingUid == 0) {
11503 // Always okay.
11504 } else if (callerApp == null || !callerApp.persistent) {
11505 try {
11506 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11507 intent.getAction())) {
11508 String msg = "Permission Denial: not allowed to send broadcast "
11509 + intent.getAction() + " from pid="
11510 + callingPid + ", uid=" + callingUid;
11511 Slog.w(TAG, msg);
11512 throw new SecurityException(msg);
11513 }
11514 } catch (RemoteException e) {
11515 Slog.w(TAG, "Remote exception", e);
11516 return ActivityManager.BROADCAST_SUCCESS;
11517 }
11518 }
11519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011520 // Handle special intents: if this broadcast is from the package
11521 // manager about a package being removed, we need to remove all of
11522 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011523 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011525 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11526 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011527 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011528 || uidRemoved) {
11529 if (checkComponentPermission(
11530 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011531 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532 == PackageManager.PERMISSION_GRANTED) {
11533 if (uidRemoved) {
11534 final Bundle intentExtras = intent.getExtras();
11535 final int uid = intentExtras != null
11536 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11537 if (uid >= 0) {
11538 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11539 synchronized (bs) {
11540 bs.removeUidStatsLocked(uid);
11541 }
11542 }
11543 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011544 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011545 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011546 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011547 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11548 if (list != null && (list.length > 0)) {
11549 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011550 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011551 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011552 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011553 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011554 }
11555 } else {
11556 Uri data = intent.getData();
11557 String ssp;
11558 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11559 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11560 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011561 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11562 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011563 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011564 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011565 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011566 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011568 }
11569 }
11570 }
11571 } else {
11572 String msg = "Permission Denial: " + intent.getAction()
11573 + " broadcast from " + callerPackage + " (pid=" + callingPid
11574 + ", uid=" + callingUid + ")"
11575 + " requires "
11576 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011577 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011578 throw new SecurityException(msg);
11579 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011580
11581 // Special case for adding a package: by default turn on compatibility
11582 // mode.
11583 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011584 Uri data = intent.getData();
11585 String ssp;
11586 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11587 mCompatModePackages.handlePackageAddedLocked(ssp,
11588 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590 }
11591
11592 /*
11593 * If this is the time zone changed action, queue up a message that will reset the timezone
11594 * of all currently running processes. This message will get queued up before the broadcast
11595 * happens.
11596 */
11597 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11598 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11599 }
11600
Robert Greenwalt03595d02010-11-02 14:08:23 -070011601 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11602 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11603 }
11604
Robert Greenwalt434203a2010-10-11 16:00:27 -070011605 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11606 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11607 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11608 }
11609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 // Add to the sticky list if requested.
11611 if (sticky) {
11612 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11613 callingPid, callingUid)
11614 != PackageManager.PERMISSION_GRANTED) {
11615 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11616 + callingPid + ", uid=" + callingUid
11617 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011618 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 throw new SecurityException(msg);
11620 }
11621 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011622 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011624 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011625 }
11626 if (intent.getComponent() != null) {
11627 throw new SecurityException(
11628 "Sticky broadcasts can't target a specific component");
11629 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011630 // We use userId directly here, since the "all" target is maintained
11631 // as a separate set of sticky broadcasts.
11632 if (userId != UserHandle.USER_ALL) {
11633 // But first, if this is not a broadcast to all users, then
11634 // make sure it doesn't conflict with an existing broadcast to
11635 // all users.
11636 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11637 UserHandle.USER_ALL);
11638 if (stickies != null) {
11639 ArrayList<Intent> list = stickies.get(intent.getAction());
11640 if (list != null) {
11641 int N = list.size();
11642 int i;
11643 for (i=0; i<N; i++) {
11644 if (intent.filterEquals(list.get(i))) {
11645 throw new IllegalArgumentException(
11646 "Sticky broadcast " + intent + " for user "
11647 + userId + " conflicts with existing global broadcast");
11648 }
11649 }
11650 }
11651 }
11652 }
11653 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11654 if (stickies == null) {
11655 stickies = new HashMap<String, ArrayList<Intent>>();
11656 mStickyBroadcasts.put(userId, stickies);
11657 }
11658 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 if (list == null) {
11660 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011661 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 }
11663 int N = list.size();
11664 int i;
11665 for (i=0; i<N; i++) {
11666 if (intent.filterEquals(list.get(i))) {
11667 // This sticky already exists, replace it.
11668 list.set(i, new Intent(intent));
11669 break;
11670 }
11671 }
11672 if (i >= N) {
11673 list.add(new Intent(intent));
11674 }
11675 }
11676
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011677 int[] users;
11678 if (userId == UserHandle.USER_ALL) {
11679 // Caller wants broadcast to go to all started users.
11680 users = new int[mStartedUsers.size()];
11681 for (int i=0; i<mStartedUsers.size(); i++) {
11682 users[i] = mStartedUsers.keyAt(i);
11683 }
11684 } else {
11685 // Caller wants broadcast to go to one specific user.
11686 users = new int[] {userId};
11687 }
11688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011689 // Figure out who all will receive this broadcast.
11690 List receivers = null;
11691 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011692 // Need to resolve the intent to interested receivers...
11693 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11694 == 0) {
11695 receivers = collectReceiverComponents(intent, resolvedType, users);
11696 }
11697 if (intent.getComponent() == null) {
11698 registeredReceivers = mReceiverResolver.queryIntent(intent,
11699 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011700 }
11701
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011702 final boolean replacePending =
11703 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11704
Joe Onorato8a9b2202010-02-26 18:56:32 -080011705 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011706 + " replacePending=" + replacePending);
11707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011708 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11709 if (!ordered && NR > 0) {
11710 // If we are not serializing this broadcast, then send the
11711 // registered receivers separately so they don't wait for the
11712 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011713 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11714 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 callerPackage, callingPid, callingUid, requiredPermission,
11716 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011717 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011718 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011719 TAG, "Enqueueing parallel broadcast " + r);
11720 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011721 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011722 queue.enqueueParallelBroadcastLocked(r);
11723 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011725 registeredReceivers = null;
11726 NR = 0;
11727 }
11728
11729 // Merge into one list.
11730 int ir = 0;
11731 if (receivers != null) {
11732 // A special case for PACKAGE_ADDED: do not allow the package
11733 // being added to see this broadcast. This prevents them from
11734 // using this as a back door to get run as soon as they are
11735 // installed. Maybe in the future we want to have a special install
11736 // broadcast or such for apps, but we'd like to deliberately make
11737 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011738 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011739 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11740 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11741 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011742 Uri data = intent.getData();
11743 if (data != null) {
11744 String pkgName = data.getSchemeSpecificPart();
11745 if (pkgName != null) {
11746 skipPackages = new String[] { pkgName };
11747 }
11748 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011749 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011750 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011751 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011752 if (skipPackages != null && (skipPackages.length > 0)) {
11753 for (String skipPackage : skipPackages) {
11754 if (skipPackage != null) {
11755 int NT = receivers.size();
11756 for (int it=0; it<NT; it++) {
11757 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11758 if (curt.activityInfo.packageName.equals(skipPackage)) {
11759 receivers.remove(it);
11760 it--;
11761 NT--;
11762 }
11763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011764 }
11765 }
11766 }
11767
11768 int NT = receivers != null ? receivers.size() : 0;
11769 int it = 0;
11770 ResolveInfo curt = null;
11771 BroadcastFilter curr = null;
11772 while (it < NT && ir < NR) {
11773 if (curt == null) {
11774 curt = (ResolveInfo)receivers.get(it);
11775 }
11776 if (curr == null) {
11777 curr = registeredReceivers.get(ir);
11778 }
11779 if (curr.getPriority() >= curt.priority) {
11780 // Insert this broadcast record into the final list.
11781 receivers.add(it, curr);
11782 ir++;
11783 curr = null;
11784 it++;
11785 NT++;
11786 } else {
11787 // Skip to the next ResolveInfo in the final list.
11788 it++;
11789 curt = null;
11790 }
11791 }
11792 }
11793 while (ir < NR) {
11794 if (receivers == null) {
11795 receivers = new ArrayList();
11796 }
11797 receivers.add(registeredReceivers.get(ir));
11798 ir++;
11799 }
11800
11801 if ((receivers != null && receivers.size() > 0)
11802 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011803 BroadcastQueue queue = broadcastQueueForIntent(intent);
11804 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011806 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011807 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011808 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011810 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011811 if (DEBUG_BROADCAST) {
11812 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011813 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011815 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011816 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011817 queue.enqueueOrderedBroadcastLocked(r);
11818 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 }
11821
Dianne Hackborna4972e92012-03-14 10:38:05 -070011822 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823 }
11824
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011825 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011826 // Refuse possible leaked file descriptors
11827 if (intent != null && intent.hasFileDescriptors() == true) {
11828 throw new IllegalArgumentException("File descriptors passed in Intent");
11829 }
11830
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011831 int flags = intent.getFlags();
11832
11833 if (!mProcessesReady) {
11834 // if the caller really truly claims to know what they're doing, go
11835 // ahead and allow the broadcast without launching any receivers
11836 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11837 intent = new Intent(intent);
11838 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11839 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11840 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11841 + " before boot completion");
11842 throw new IllegalStateException("Cannot broadcast before boot completed");
11843 }
11844 }
11845
11846 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11847 throw new IllegalArgumentException(
11848 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11849 }
11850
11851 return intent;
11852 }
11853
11854 public final int broadcastIntent(IApplicationThread caller,
11855 Intent intent, String resolvedType, IIntentReceiver resultTo,
11856 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011857 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011858 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011859 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011860 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11863 final int callingPid = Binder.getCallingPid();
11864 final int callingUid = Binder.getCallingUid();
11865 final long origId = Binder.clearCallingIdentity();
11866 int res = broadcastIntentLocked(callerApp,
11867 callerApp != null ? callerApp.info.packageName : null,
11868 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011869 resultCode, resultData, map, requiredPermission, serialized, sticky,
11870 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011871 Binder.restoreCallingIdentity(origId);
11872 return res;
11873 }
11874 }
11875
11876 int broadcastIntentInPackage(String packageName, int uid,
11877 Intent intent, String resolvedType, IIntentReceiver resultTo,
11878 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011879 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011880 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011881 intent = verifyBroadcastLocked(intent);
11882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011883 final long origId = Binder.clearCallingIdentity();
11884 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11885 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011886 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011887 Binder.restoreCallingIdentity(origId);
11888 return res;
11889 }
11890 }
11891
Amith Yamasani742a6712011-05-04 14:49:28 -070011892 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011893 // Refuse possible leaked file descriptors
11894 if (intent != null && intent.hasFileDescriptors() == true) {
11895 throw new IllegalArgumentException("File descriptors passed in Intent");
11896 }
11897
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011898 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11899 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011901 synchronized(this) {
11902 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11903 != PackageManager.PERMISSION_GRANTED) {
11904 String msg = "Permission Denial: unbroadcastIntent() from pid="
11905 + Binder.getCallingPid()
11906 + ", uid=" + Binder.getCallingUid()
11907 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011908 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011909 throw new SecurityException(msg);
11910 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011911 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11912 if (stickies != null) {
11913 ArrayList<Intent> list = stickies.get(intent.getAction());
11914 if (list != null) {
11915 int N = list.size();
11916 int i;
11917 for (i=0; i<N; i++) {
11918 if (intent.filterEquals(list.get(i))) {
11919 list.remove(i);
11920 break;
11921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011923 if (list.size() <= 0) {
11924 stickies.remove(intent.getAction());
11925 }
11926 }
11927 if (stickies.size() <= 0) {
11928 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011929 }
11930 }
11931 }
11932 }
11933
11934 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11935 String resultData, Bundle resultExtras, boolean resultAbort,
11936 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011937 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11938 if (r == null) {
11939 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 return false;
11941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011942
Christopher Tatef46723b2012-01-26 14:19:24 -080011943 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11944 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011945 }
11946
11947 public void finishReceiver(IBinder who, int resultCode, String resultData,
11948 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011949 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011950
11951 // Refuse possible leaked file descriptors
11952 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11953 throw new IllegalArgumentException("File descriptors passed in Bundle");
11954 }
11955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011957 try {
11958 boolean doNext = false;
11959 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011960
Christopher Tatef46723b2012-01-26 14:19:24 -080011961 synchronized(this) {
11962 r = broadcastRecordForReceiverLocked(who);
11963 if (r != null) {
11964 doNext = r.queue.finishReceiverLocked(r, resultCode,
11965 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011967 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011968
Christopher Tatef46723b2012-01-26 14:19:24 -080011969 if (doNext) {
11970 r.queue.processNextBroadcast(false);
11971 }
11972 trimApplications();
11973 } finally {
11974 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 // =========================================================
11979 // INSTRUMENTATION
11980 // =========================================================
11981
11982 public boolean startInstrumentation(ComponentName className,
11983 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011984 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011985 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011986 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
11987 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011988 // Refuse possible leaked file descriptors
11989 if (arguments != null && arguments.hasFileDescriptors()) {
11990 throw new IllegalArgumentException("File descriptors passed in Bundle");
11991 }
11992
11993 synchronized(this) {
11994 InstrumentationInfo ii = null;
11995 ApplicationInfo ai = null;
11996 try {
11997 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011998 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011999 ai = AppGlobals.getPackageManager().getApplicationInfo(
12000 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012002 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 }
12004 if (ii == null) {
12005 reportStartInstrumentationFailure(watcher, className,
12006 "Unable to find instrumentation info for: " + className);
12007 return false;
12008 }
12009 if (ai == null) {
12010 reportStartInstrumentationFailure(watcher, className,
12011 "Unable to find instrumentation target package: " + ii.targetPackage);
12012 return false;
12013 }
12014
12015 int match = mContext.getPackageManager().checkSignatures(
12016 ii.targetPackage, ii.packageName);
12017 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12018 String msg = "Permission Denial: starting instrumentation "
12019 + className + " from pid="
12020 + Binder.getCallingPid()
12021 + ", uid=" + Binder.getCallingPid()
12022 + " not allowed because package " + ii.packageName
12023 + " does not have a signature matching the target "
12024 + ii.targetPackage;
12025 reportStartInstrumentationFailure(watcher, className, msg);
12026 throw new SecurityException(msg);
12027 }
12028
12029 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012030 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012031 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012032 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012033 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012034 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 app.instrumentationProfileFile = profileFile;
12036 app.instrumentationArguments = arguments;
12037 app.instrumentationWatcher = watcher;
12038 app.instrumentationResultClass = className;
12039 Binder.restoreCallingIdentity(origId);
12040 }
12041
12042 return true;
12043 }
12044
12045 /**
12046 * Report errors that occur while attempting to start Instrumentation. Always writes the
12047 * error to the logs, but if somebody is watching, send the report there too. This enables
12048 * the "am" command to report errors with more information.
12049 *
12050 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12051 * @param cn The component name of the instrumentation.
12052 * @param report The error report.
12053 */
12054 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12055 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012056 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012057 try {
12058 if (watcher != null) {
12059 Bundle results = new Bundle();
12060 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12061 results.putString("Error", report);
12062 watcher.instrumentationStatus(cn, -1, results);
12063 }
12064 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012065 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012066 }
12067 }
12068
12069 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12070 if (app.instrumentationWatcher != null) {
12071 try {
12072 // NOTE: IInstrumentationWatcher *must* be oneway here
12073 app.instrumentationWatcher.instrumentationFinished(
12074 app.instrumentationClass,
12075 resultCode,
12076 results);
12077 } catch (RemoteException e) {
12078 }
12079 }
12080 app.instrumentationWatcher = null;
12081 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012082 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012083 app.instrumentationProfileFile = null;
12084 app.instrumentationArguments = null;
12085
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012086 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012087 }
12088
12089 public void finishInstrumentation(IApplicationThread target,
12090 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012091 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 // Refuse possible leaked file descriptors
12093 if (results != null && results.hasFileDescriptors()) {
12094 throw new IllegalArgumentException("File descriptors passed in Intent");
12095 }
12096
12097 synchronized(this) {
12098 ProcessRecord app = getRecordForAppLocked(target);
12099 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012100 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 return;
12102 }
12103 final long origId = Binder.clearCallingIdentity();
12104 finishInstrumentationLocked(app, resultCode, results);
12105 Binder.restoreCallingIdentity(origId);
12106 }
12107 }
12108
12109 // =========================================================
12110 // CONFIGURATION
12111 // =========================================================
12112
12113 public ConfigurationInfo getDeviceConfigurationInfo() {
12114 ConfigurationInfo config = new ConfigurationInfo();
12115 synchronized (this) {
12116 config.reqTouchScreen = mConfiguration.touchscreen;
12117 config.reqKeyboardType = mConfiguration.keyboard;
12118 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012119 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12120 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012121 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12122 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012123 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12124 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012125 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12126 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012127 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 }
12129 return config;
12130 }
12131
12132 public Configuration getConfiguration() {
12133 Configuration ci;
12134 synchronized(this) {
12135 ci = new Configuration(mConfiguration);
12136 }
12137 return ci;
12138 }
12139
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012140 public void updatePersistentConfiguration(Configuration values) {
12141 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12142 "updateConfiguration()");
12143 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12144 "updateConfiguration()");
12145 if (values == null) {
12146 throw new NullPointerException("Configuration must not be null");
12147 }
12148
12149 synchronized(this) {
12150 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012151 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012152 Binder.restoreCallingIdentity(origId);
12153 }
12154 }
12155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012156 public void updateConfiguration(Configuration values) {
12157 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12158 "updateConfiguration()");
12159
12160 synchronized(this) {
12161 if (values == null && mWindowManager != null) {
12162 // sentinel: fetch the current configuration from the window manager
12163 values = mWindowManager.computeNewConfiguration();
12164 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012165
12166 if (mWindowManager != null) {
12167 mProcessList.applyDisplaySize(mWindowManager);
12168 }
12169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012170 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012171 if (values != null) {
12172 Settings.System.clearConfiguration(values);
12173 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012174 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012175 Binder.restoreCallingIdentity(origId);
12176 }
12177 }
12178
12179 /**
12180 * Do either or both things: (1) change the current configuration, and (2)
12181 * make sure the given activity is running with the (now) current
12182 * configuration. Returns true if the activity has been left running, or
12183 * false if <var>starting</var> is being destroyed to match the new
12184 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012185 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012187 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012188 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012189 // do nothing if we are headless
12190 if (mHeadless) return true;
12191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012192 int changes = 0;
12193
12194 boolean kept = true;
12195
12196 if (values != null) {
12197 Configuration newConfig = new Configuration(mConfiguration);
12198 changes = newConfig.updateFrom(values);
12199 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012200 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012201 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202 }
12203
Doug Zongker2bec3d42009-12-04 12:52:44 -080012204 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012205
Dianne Hackborn813075a62011-11-14 17:45:19 -080012206 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012207 saveLocaleLocked(values.locale,
12208 !values.locale.equals(mConfiguration.locale),
12209 values.userSetLocale);
12210 }
12211
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012212 mConfigurationSeq++;
12213 if (mConfigurationSeq <= 0) {
12214 mConfigurationSeq = 1;
12215 }
12216 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012218 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012219
12220 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012221
12222 // TODO: If our config changes, should we auto dismiss any currently
12223 // showing dialogs?
12224 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012225
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012226 AttributeCache ac = AttributeCache.instance();
12227 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012228 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012231 // Make sure all resources in our process are updated
12232 // right now, so that anyone who is going to retrieve
12233 // resource values after we return will be sure to get
12234 // the new ones. This is especially important during
12235 // boot, where the first config change needs to guarantee
12236 // all resources have that config before following boot
12237 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012238 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012239
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012240 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012241 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012242 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012243 mHandler.sendMessage(msg);
12244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012246 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12247 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248 try {
12249 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012250 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012251 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012252 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
12254 } catch (Exception e) {
12255 }
12256 }
12257 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012258 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12259 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012260 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012261 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012262 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12263 broadcastIntentLocked(null, null,
12264 new Intent(Intent.ACTION_LOCALE_CHANGED),
12265 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012266 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012268 }
12269 }
12270
12271 if (changes != 0 && starting == null) {
12272 // If the configuration changed, and the caller is not already
12273 // in the process of starting an activity, then find the top
12274 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012275 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012276 }
12277
12278 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012279 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012280 // And we need to make sure at this point that all other activities
12281 // are made visible with the correct configuration.
12282 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 }
12284
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012285 if (values != null && mWindowManager != null) {
12286 mWindowManager.setNewConfiguration(mConfiguration);
12287 }
12288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289 return kept;
12290 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012291
12292 /**
12293 * Decide based on the configuration whether we should shouw the ANR,
12294 * crash, etc dialogs. The idea is that if there is no affordnace to
12295 * press the on-screen buttons, we shouldn't show the dialog.
12296 *
12297 * A thought: SystemUI might also want to get told about this, the Power
12298 * dialog / global actions also might want different behaviors.
12299 */
12300 private static final boolean shouldShowDialogs(Configuration config) {
12301 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12302 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012304
12305 /**
12306 * Save the locale. You must be inside a synchronized (this) block.
12307 */
12308 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12309 if(isDiff) {
12310 SystemProperties.set("user.language", l.getLanguage());
12311 SystemProperties.set("user.region", l.getCountry());
12312 }
12313
12314 if(isPersist) {
12315 SystemProperties.set("persist.sys.language", l.getLanguage());
12316 SystemProperties.set("persist.sys.country", l.getCountry());
12317 SystemProperties.set("persist.sys.localevar", l.getVariant());
12318 }
12319 }
12320
Adam Powelldd8fab22012-03-22 17:47:27 -070012321 @Override
12322 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12323 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012324 return srec != null && srec.task.affinity != null &&
12325 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012326 }
12327
12328 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12329 Intent resultData) {
12330 ComponentName dest = destIntent.getComponent();
12331
12332 synchronized (this) {
12333 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012334 if (srec == null) {
12335 return false;
12336 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012337 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12338 final int start = history.indexOf(srec);
12339 if (start < 0) {
12340 // Current activity is not in history stack; do nothing.
12341 return false;
12342 }
12343 int finishTo = start - 1;
12344 ActivityRecord parent = null;
12345 boolean foundParentInTask = false;
12346 if (dest != null) {
12347 TaskRecord tr = srec.task;
12348 for (int i = start - 1; i >= 0; i--) {
12349 ActivityRecord r = history.get(i);
12350 if (tr != r.task) {
12351 // Couldn't find parent in the same task; stop at the one above this.
12352 // (Root of current task; in-app "home" behavior)
12353 // Always at least finish the current activity.
12354 finishTo = Math.min(start - 1, i + 1);
12355 parent = history.get(finishTo);
12356 break;
12357 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12358 r.info.name.equals(dest.getClassName())) {
12359 finishTo = i;
12360 parent = r;
12361 foundParentInTask = true;
12362 break;
12363 }
12364 }
12365 }
12366
12367 if (mController != null) {
12368 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12369 if (next != null) {
12370 // ask watcher if this is allowed
12371 boolean resumeOK = true;
12372 try {
12373 resumeOK = mController.activityResuming(next.packageName);
12374 } catch (RemoteException e) {
12375 mController = null;
12376 }
12377
12378 if (!resumeOK) {
12379 return false;
12380 }
12381 }
12382 }
12383 final long origId = Binder.clearCallingIdentity();
12384 for (int i = start; i > finishTo; i--) {
12385 ActivityRecord r = history.get(i);
12386 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012387 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012388 // Only return the supplied result for the first activity finished
12389 resultCode = Activity.RESULT_CANCELED;
12390 resultData = null;
12391 }
12392
12393 if (parent != null && foundParentInTask) {
12394 final int parentLaunchMode = parent.info.launchMode;
12395 final int destIntentFlags = destIntent.getFlags();
12396 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12397 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12398 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12399 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012400 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012401 } else {
12402 try {
12403 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012404 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012405 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12406 null, aInfo, parent.appToken, null,
12407 0, -1, parent.launchedFromUid, 0, null, true, null);
12408 foundParentInTask = res == ActivityManager.START_SUCCESS;
12409 } catch (RemoteException e) {
12410 foundParentInTask = false;
12411 }
12412 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012413 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012414 }
12415 }
12416 Binder.restoreCallingIdentity(origId);
12417 return foundParentInTask;
12418 }
12419 }
12420
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012421 public int getLaunchedFromUid(IBinder activityToken) {
12422 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12423 if (srec == null) {
12424 return -1;
12425 }
12426 return srec.launchedFromUid;
12427 }
12428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 // =========================================================
12430 // LIFETIME MANAGEMENT
12431 // =========================================================
12432
Christopher Tatef46723b2012-01-26 14:19:24 -080012433 // Returns which broadcast queue the app is the current [or imminent] receiver
12434 // on, or 'null' if the app is not an active broadcast recipient.
12435 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12436 BroadcastRecord r = app.curReceiver;
12437 if (r != null) {
12438 return r.queue;
12439 }
12440
12441 // It's not the current receiver, but it might be starting up to become one
12442 synchronized (this) {
12443 for (BroadcastQueue queue : mBroadcastQueues) {
12444 r = queue.mPendingBroadcast;
12445 if (r != null && r.curApp == app) {
12446 // found it; report which queue it's in
12447 return queue;
12448 }
12449 }
12450 }
12451
12452 return null;
12453 }
12454
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012455 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012456 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012457 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012458 // This adjustment has already been computed. If we are calling
12459 // from the top, we may have already computed our adjustment with
12460 // an earlier hidden adjustment that isn't really for us... if
12461 // so, use the new hidden adjustment.
12462 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012463 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12464 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012465 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012466 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012467 }
12468
12469 if (app.thread == null) {
12470 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012471 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012472 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012473 }
12474
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012475 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12476 app.adjSource = null;
12477 app.adjTarget = null;
12478 app.empty = false;
12479 app.hidden = false;
12480
12481 final int activitiesSize = app.activities.size();
12482
Dianne Hackborn7d608422011-08-07 16:24:18 -070012483 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012484 // The max adjustment doesn't allow this app to be anything
12485 // below foreground, so it is not worth doing work for it.
12486 app.adjType = "fixed";
12487 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012488 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012489 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012490 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012491 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012492 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012493 // System process can do UI, and when they do we want to have
12494 // them trim their memory after the user leaves the UI. To
12495 // facilitate this, here we need to determine whether or not it
12496 // is currently showing UI.
12497 app.systemNoUi = true;
12498 if (app == TOP_APP) {
12499 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012500 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012501 } else if (activitiesSize > 0) {
12502 for (int j = 0; j < activitiesSize; j++) {
12503 final ActivityRecord r = app.activities.get(j);
12504 if (r.visible) {
12505 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012506 }
12507 if (r.app == app) {
12508 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012509 }
12510 }
12511 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012512 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012513 }
12514
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012515 app.keeping = false;
12516 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012517 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518
The Android Open Source Project4df24232009-03-05 14:34:35 -080012519 // Determine the importance of the process, starting with most
12520 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012522 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012523 boolean foregroundActivities = false;
12524 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012525 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012526 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012527 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012528 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012529 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012530 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012531 foregroundActivities = true;
12532 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012533 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012534 } else if (app.instrumentationClass != null) {
12535 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012536 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012537 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012538 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012539 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012540 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012541 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012542 // counts as being in the foreground for OOM killer purposes.
12543 // It's placed in a sched group based on the nature of the
12544 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012545 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012546 schedGroup = (queue == mFgBroadcastQueue)
12547 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012548 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012549 } else if (app.executingServices.size() > 0) {
12550 // An app that is currently executing a service callback also
12551 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012552 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012553 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012554 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012555 } else {
12556 // Assume process is hidden (has activities); we will correct
12557 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012558 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012559 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012560 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012561 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012563
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012564 boolean hasStoppingActivities = false;
12565
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012566 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012567 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012568 for (int j = 0; j < activitiesSize; j++) {
12569 final ActivityRecord r = app.activities.get(j);
12570 if (r.visible) {
12571 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012572 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12573 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012574 app.adjType = "visible";
12575 }
12576 schedGroup = Process.THREAD_GROUP_DEFAULT;
12577 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012578 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012579 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012580 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012581 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012582 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12583 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012584 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012585 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012586 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012587 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012588 } else if (r.state == ActivityState.STOPPING) {
12589 // We will apply the actual adjustment later, because
12590 // we want to allow this process to immediately go through
12591 // any memory trimming that is in effect.
12592 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012593 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012594 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012595 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012596 if (r.app == app) {
12597 app.hasActivities = true;
12598 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012599 }
12600 }
12601
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012602 if (adj == hiddenAdj && !app.hasActivities) {
12603 // Whoops, this process is completely empty as far as we know
12604 // at this point.
12605 adj = emptyAdj;
12606 app.empty = true;
12607 app.adjType = "bg-empty";
12608 }
12609
Dianne Hackborn7d608422011-08-07 16:24:18 -070012610 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012611 if (app.foregroundServices) {
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 = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012616 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012617 } else if (app.forcingToForeground != null) {
12618 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012619 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012620 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012621 app.adjType = "force-foreground";
12622 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012623 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012624 }
12625 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012626
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012627 if (app.foregroundServices) {
12628 interesting = true;
12629 }
12630
Dianne Hackborn7d608422011-08-07 16:24:18 -070012631 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012632 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012633 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012634 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012635 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012636 app.adjType = "heavy";
12637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638
Dianne Hackborn7d608422011-08-07 16:24:18 -070012639 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012640 // This process is hosting what we currently consider to be the
12641 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012642 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012643 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012644 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012645 app.adjType = "home";
12646 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012647
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012648 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12649 && app.activities.size() > 0) {
12650 // This was the previous process that showed UI to the user.
12651 // We want to try to keep it around more aggressively, to give
12652 // a good experience around switching between two apps.
12653 adj = ProcessList.PREVIOUS_APP_ADJ;
12654 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12655 app.hidden = false;
12656 app.adjType = "previous";
12657 }
12658
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012659 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12660 + " reason=" + app.adjType);
12661
The Android Open Source Project4df24232009-03-05 14:34:35 -080012662 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012663 // there are applications dependent on our services or providers, but
12664 // this gives us a baseline and makes sure we don't get into an
12665 // infinite recursion.
12666 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012667 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012668
Christopher Tate6fa95972009-06-05 18:43:55 -070012669 if (mBackupTarget != null && app == mBackupTarget.app) {
12670 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012671 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012672 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012673 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012674 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012675 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012676 }
12677 }
12678
Dianne Hackborn7d608422011-08-07 16:24:18 -070012679 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012680 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 final long now = SystemClock.uptimeMillis();
12682 // This process is more important if the top activity is
12683 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012684 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012685 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012686 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012688 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012689 // If this process has shown some UI, let it immediately
12690 // go to the LRU list because it may be pretty heavy with
12691 // UI stuff. We'll tag it with a label just to help
12692 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012693 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012694 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012696 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012697 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012698 // This service has seen some activity within
12699 // recent memory, so we will keep its process ahead
12700 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012701 if (adj > ProcessList.SERVICE_ADJ) {
12702 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012703 app.adjType = "started-services";
12704 app.hidden = false;
12705 }
12706 }
12707 // If we have let the service slide into the background
12708 // state, still have some text describing what it is doing
12709 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012710 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012711 app.adjType = "started-bg-services";
12712 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012713 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012714 // Don't kill this process because it is doing work; it
12715 // has said it is doing work.
12716 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012717 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012718 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012719 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012720 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012722 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012723 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012724 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012725 // XXX should compute this based on the max of
12726 // all connected clients.
12727 ConnectionRecord cr = clist.get(i);
12728 if (cr.binding.client == app) {
12729 // Binding to ourself is not interesting.
12730 continue;
12731 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012732 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012733 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012734 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012735 int myHiddenAdj = hiddenAdj;
12736 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012737 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012738 myHiddenAdj = client.hiddenAdj;
12739 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012740 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012741 }
12742 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012743 int myEmptyAdj = emptyAdj;
12744 if (myEmptyAdj > client.emptyAdj) {
12745 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12746 myEmptyAdj = client.emptyAdj;
12747 } else {
12748 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12749 }
12750 }
12751 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12752 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012753 String adjType = null;
12754 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12755 // Not doing bind OOM management, so treat
12756 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012757 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012758 // If this process has shown some UI, let it immediately
12759 // go to the LRU list because it may be pretty heavy with
12760 // UI stuff. We'll tag it with a label just to help
12761 // debug and understand what is going on.
12762 if (adj > clientAdj) {
12763 adjType = "bound-bg-ui-services";
12764 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012765 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012766 clientAdj = adj;
12767 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012768 if (now >= (s.lastActivity
12769 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012770 // This service has not seen activity within
12771 // recent memory, so allow it to drop to the
12772 // LRU list if there is no other reason to keep
12773 // it around. We'll also tag it with a label just
12774 // to help debug and undertand what is going on.
12775 if (adj > clientAdj) {
12776 adjType = "bound-bg-services";
12777 }
12778 clientAdj = adj;
12779 }
12780 }
12781 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012782 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012783 // If this process has recently shown UI, and
12784 // the process that is binding to it is less
12785 // important than being visible, then we don't
12786 // care about the binding as much as we care
12787 // about letting this process get into the LRU
12788 // list to be killed and restarted if needed for
12789 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012790 if (app.hasShownUi && app != mHomeProcess
12791 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012792 adjType = "bound-bg-ui-services";
12793 } else {
12794 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12795 |Context.BIND_IMPORTANT)) != 0) {
12796 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012797 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12798 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12799 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12800 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12801 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012802 adj = clientAdj;
12803 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012804 app.pendingUiClean = true;
12805 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12806 adj = ProcessList.VISIBLE_APP_ADJ;
12807 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012808 }
12809 if (!client.hidden) {
12810 app.hidden = false;
12811 }
12812 if (client.keeping) {
12813 app.keeping = true;
12814 }
12815 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012816 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012817 }
12818 if (adjType != null) {
12819 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012820 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12821 .REASON_SERVICE_IN_USE;
12822 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012823 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012824 app.adjTarget = s.name;
12825 }
12826 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12827 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12828 schedGroup = Process.THREAD_GROUP_DEFAULT;
12829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012830 }
12831 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012832 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12833 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012834 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012835 (a.visible || a.state == ActivityState.RESUMED
12836 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012837 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012838 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12839 schedGroup = Process.THREAD_GROUP_DEFAULT;
12840 }
12841 app.hidden = false;
12842 app.adjType = "service";
12843 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12844 .REASON_SERVICE_IN_USE;
12845 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012846 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012847 app.adjTarget = s.name;
12848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012850 }
12851 }
12852 }
12853 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012854
Dianne Hackborn287952c2010-09-22 22:34:31 -070012855 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012856 // would like to avoid killing it unless it would prevent the current
12857 // application from running. By default we put the process in
12858 // with the rest of the background processes; as we scan through
12859 // its services we may bump it up from there.
12860 if (adj > hiddenAdj) {
12861 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012862 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012863 app.adjType = "bg-services";
12864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 }
12866
Dianne Hackborn7d608422011-08-07 16:24:18 -070012867 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012868 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012869 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012870 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012871 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012872 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012873 for (int i = cpr.connections.size()-1;
12874 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12875 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12876 i--) {
12877 ContentProviderConnection conn = cpr.connections.get(i);
12878 ProcessRecord client = conn.client;
12879 if (client == app) {
12880 // Being our own client is not interesting.
12881 continue;
12882 }
12883 int myHiddenAdj = hiddenAdj;
12884 if (myHiddenAdj > client.hiddenAdj) {
12885 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12886 myHiddenAdj = client.hiddenAdj;
12887 } else {
12888 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012889 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012890 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012891 int myEmptyAdj = emptyAdj;
12892 if (myEmptyAdj > client.emptyAdj) {
12893 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12894 myEmptyAdj = client.emptyAdj;
12895 } else {
12896 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12897 }
12898 }
12899 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12900 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012901 if (adj > clientAdj) {
12902 if (app.hasShownUi && app != mHomeProcess
12903 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12904 app.adjType = "bg-ui-provider";
12905 } else {
12906 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12907 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12908 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012909 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012910 if (!client.hidden) {
12911 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012912 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012913 if (client.keeping) {
12914 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012915 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012916 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12917 .REASON_PROVIDER_IN_USE;
12918 app.adjSource = client;
12919 app.adjSourceOom = clientAdj;
12920 app.adjTarget = cpr.name;
12921 }
12922 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12923 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924 }
12925 }
12926 // If the provider has external (non-framework) process
12927 // dependencies, ensure that its adjustment is at least
12928 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012929 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012930 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12931 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012932 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012933 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012934 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012935 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012936 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012937 }
12938 }
12939 }
12940 }
12941
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012942 if (adj == ProcessList.SERVICE_ADJ) {
12943 if (doingAll) {
12944 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12945 mNewNumServiceProcs++;
12946 }
12947 if (app.serviceb) {
12948 adj = ProcessList.SERVICE_B_ADJ;
12949 }
12950 } else {
12951 app.serviceb = false;
12952 }
12953
12954 app.nonStoppingAdj = adj;
12955
12956 if (hasStoppingActivities) {
12957 // Only upgrade adjustment.
12958 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12959 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12960 app.adjType = "stopping";
12961 }
12962 }
12963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 app.curRawAdj = adj;
12965
Joe Onorato8a9b2202010-02-26 18:56:32 -080012966 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12968 if (adj > app.maxAdj) {
12969 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012970 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012971 schedGroup = Process.THREAD_GROUP_DEFAULT;
12972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012973 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012974 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012975 app.keeping = true;
12976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012978 if (app.hasAboveClient) {
12979 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12980 // then we need to drop its adjustment to be lower than the service's
12981 // in order to honor the request. We want to drop it by one adjustment
12982 // level... but there is special meaning applied to various levels so
12983 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012984 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012985 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012986 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12987 adj = ProcessList.VISIBLE_APP_ADJ;
12988 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12989 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12990 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12991 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012992 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012993 adj++;
12994 }
12995 }
12996
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012997 int importance = app.memImportance;
12998 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12999 app.curAdj = adj;
13000 app.curSchedGroup = schedGroup;
13001 if (!interesting) {
13002 // For this reporting, if there is not something explicitly
13003 // interesting in this process then we will push it to the
13004 // background importance.
13005 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13006 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13007 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13008 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13009 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13010 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13011 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13012 } else if (adj >= ProcessList.SERVICE_ADJ) {
13013 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13014 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13015 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13016 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13017 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13018 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13019 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13020 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13021 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13022 } else {
13023 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13024 }
13025 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013026
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013027 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13028 if (foregroundActivities != app.foregroundActivities) {
13029 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13030 }
13031 if (changes != 0) {
13032 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13033 app.memImportance = importance;
13034 app.foregroundActivities = foregroundActivities;
13035 int i = mPendingProcessChanges.size()-1;
13036 ProcessChangeItem item = null;
13037 while (i >= 0) {
13038 item = mPendingProcessChanges.get(i);
13039 if (item.pid == app.pid) {
13040 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13041 break;
13042 }
13043 i--;
13044 }
13045 if (i < 0) {
13046 // No existing item in pending changes; need a new one.
13047 final int NA = mAvailProcessChanges.size();
13048 if (NA > 0) {
13049 item = mAvailProcessChanges.remove(NA-1);
13050 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13051 } else {
13052 item = new ProcessChangeItem();
13053 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13054 }
13055 item.changes = 0;
13056 item.pid = app.pid;
13057 item.uid = app.info.uid;
13058 if (mPendingProcessChanges.size() == 0) {
13059 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13060 "*** Enqueueing dispatch processes changed!");
13061 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13062 }
13063 mPendingProcessChanges.add(item);
13064 }
13065 item.changes |= changes;
13066 item.importance = importance;
13067 item.foregroundActivities = foregroundActivities;
13068 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13069 + Integer.toHexString(System.identityHashCode(item))
13070 + " " + app.toShortString() + ": changes=" + item.changes
13071 + " importance=" + item.importance
13072 + " foreground=" + item.foregroundActivities
13073 + " type=" + app.adjType + " source=" + app.adjSource
13074 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013075 }
13076
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013077 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078 }
13079
13080 /**
13081 * Ask a given process to GC right now.
13082 */
13083 final void performAppGcLocked(ProcessRecord app) {
13084 try {
13085 app.lastRequestedGc = SystemClock.uptimeMillis();
13086 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013087 if (app.reportLowMemory) {
13088 app.reportLowMemory = false;
13089 app.thread.scheduleLowMemory();
13090 } else {
13091 app.thread.processInBackground();
13092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013093 }
13094 } catch (Exception e) {
13095 // whatever.
13096 }
13097 }
13098
13099 /**
13100 * Returns true if things are idle enough to perform GCs.
13101 */
Josh Bartel7f208742010-02-25 11:01:44 -060013102 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013103 boolean processingBroadcasts = false;
13104 for (BroadcastQueue q : mBroadcastQueues) {
13105 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13106 processingBroadcasts = true;
13107 }
13108 }
13109 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013110 && (mSleeping || (mMainStack.mResumedActivity != null &&
13111 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013112 }
13113
13114 /**
13115 * Perform GCs on all processes that are waiting for it, but only
13116 * if things are idle.
13117 */
13118 final void performAppGcsLocked() {
13119 final int N = mProcessesToGc.size();
13120 if (N <= 0) {
13121 return;
13122 }
Josh Bartel7f208742010-02-25 11:01:44 -060013123 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124 while (mProcessesToGc.size() > 0) {
13125 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013126 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013127 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13128 <= SystemClock.uptimeMillis()) {
13129 // To avoid spamming the system, we will GC processes one
13130 // at a time, waiting a few seconds between each.
13131 performAppGcLocked(proc);
13132 scheduleAppGcsLocked();
13133 return;
13134 } else {
13135 // It hasn't been long enough since we last GCed this
13136 // process... put it in the list to wait for its time.
13137 addProcessToGcListLocked(proc);
13138 break;
13139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013140 }
13141 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013142
13143 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013144 }
13145 }
13146
13147 /**
13148 * If all looks good, perform GCs on all processes waiting for them.
13149 */
13150 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013151 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 performAppGcsLocked();
13153 return;
13154 }
13155 // Still not idle, wait some more.
13156 scheduleAppGcsLocked();
13157 }
13158
13159 /**
13160 * Schedule the execution of all pending app GCs.
13161 */
13162 final void scheduleAppGcsLocked() {
13163 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013164
13165 if (mProcessesToGc.size() > 0) {
13166 // Schedule a GC for the time to the next process.
13167 ProcessRecord proc = mProcessesToGc.get(0);
13168 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13169
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013170 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013171 long now = SystemClock.uptimeMillis();
13172 if (when < (now+GC_TIMEOUT)) {
13173 when = now + GC_TIMEOUT;
13174 }
13175 mHandler.sendMessageAtTime(msg, when);
13176 }
13177 }
13178
13179 /**
13180 * Add a process to the array of processes waiting to be GCed. Keeps the
13181 * list in sorted order by the last GC time. The process can't already be
13182 * on the list.
13183 */
13184 final void addProcessToGcListLocked(ProcessRecord proc) {
13185 boolean added = false;
13186 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13187 if (mProcessesToGc.get(i).lastRequestedGc <
13188 proc.lastRequestedGc) {
13189 added = true;
13190 mProcessesToGc.add(i+1, proc);
13191 break;
13192 }
13193 }
13194 if (!added) {
13195 mProcessesToGc.add(0, proc);
13196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013197 }
13198
13199 /**
13200 * Set up to ask a process to GC itself. This will either do it
13201 * immediately, or put it on the list of processes to gc the next
13202 * time things are idle.
13203 */
13204 final void scheduleAppGcLocked(ProcessRecord app) {
13205 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013206 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 return;
13208 }
13209 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013210 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211 scheduleAppGcsLocked();
13212 }
13213 }
13214
Dianne Hackborn287952c2010-09-22 22:34:31 -070013215 final void checkExcessivePowerUsageLocked(boolean doKills) {
13216 updateCpuStatsNow();
13217
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013218 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013219 boolean doWakeKills = doKills;
13220 boolean doCpuKills = doKills;
13221 if (mLastPowerCheckRealtime == 0) {
13222 doWakeKills = false;
13223 }
13224 if (mLastPowerCheckUptime == 0) {
13225 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013226 }
13227 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013228 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013229 }
13230 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013231 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13232 final long curUptime = SystemClock.uptimeMillis();
13233 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13234 mLastPowerCheckRealtime = curRealtime;
13235 mLastPowerCheckUptime = curUptime;
13236 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13237 doWakeKills = false;
13238 }
13239 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13240 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013241 }
13242 int i = mLruProcesses.size();
13243 while (i > 0) {
13244 i--;
13245 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013246 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013247 long wtime;
13248 synchronized (stats) {
13249 wtime = stats.getProcessWakeTime(app.info.uid,
13250 app.pid, curRealtime);
13251 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013252 long wtimeUsed = wtime - app.lastWakeTime;
13253 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13254 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013255 StringBuilder sb = new StringBuilder(128);
13256 sb.append("Wake for ");
13257 app.toShortString(sb);
13258 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013259 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013260 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013261 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013262 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013263 sb.append((wtimeUsed*100)/realtimeSince);
13264 sb.append("%)");
13265 Slog.i(TAG, sb.toString());
13266 sb.setLength(0);
13267 sb.append("CPU for ");
13268 app.toShortString(sb);
13269 sb.append(": over ");
13270 TimeUtils.formatDuration(uptimeSince, sb);
13271 sb.append(" used ");
13272 TimeUtils.formatDuration(cputimeUsed, sb);
13273 sb.append(" (");
13274 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013275 sb.append("%)");
13276 Slog.i(TAG, sb.toString());
13277 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013278 // If a process has held a wake lock for more
13279 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013280 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013281 if (doWakeKills && realtimeSince > 0
13282 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13283 synchronized (stats) {
13284 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13285 realtimeSince, wtimeUsed);
13286 }
13287 Slog.w(TAG, "Excessive wake lock in " + app.processName
13288 + " (pid " + app.pid + "): held " + wtimeUsed
13289 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013290 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13291 app.processName, app.setAdj, "excessive wake lock");
13292 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013293 } else if (doCpuKills && uptimeSince > 0
13294 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13295 synchronized (stats) {
13296 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13297 uptimeSince, cputimeUsed);
13298 }
13299 Slog.w(TAG, "Excessive CPU in " + app.processName
13300 + " (pid " + app.pid + "): used " + cputimeUsed
13301 + " during " + uptimeSince);
13302 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13303 app.processName, app.setAdj, "excessive cpu");
13304 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013305 } else {
13306 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013307 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013308 }
13309 }
13310 }
13311 }
13312
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013313 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13314 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013315 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013316 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013317
13318 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013319 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 }
13321
Dianne Hackborn287952c2010-09-22 22:34:31 -070013322 final boolean wasKeeping = app.keeping;
13323
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013324 boolean success = true;
13325
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013326 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013327
Jeff Brown10e89712011-07-08 18:52:57 -070013328 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013329 if (wasKeeping && !app.keeping) {
13330 // This app is no longer something we want to keep. Note
13331 // its current wake lock time to later know to kill it if
13332 // it is not behaving well.
13333 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13334 synchronized (stats) {
13335 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13336 app.pid, SystemClock.elapsedRealtime());
13337 }
13338 app.lastCpuTime = app.curCpuTime;
13339 }
13340
13341 app.setRawAdj = app.curRawAdj;
13342 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013343
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013344 if (app.curAdj != app.setAdj) {
13345 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013346 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013347 TAG, "Set " + app.pid + " " + app.processName +
13348 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013349 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013350 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013351 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013352 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013353 }
13354 }
13355 if (app.setSchedGroup != app.curSchedGroup) {
13356 app.setSchedGroup = app.curSchedGroup;
13357 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13358 "Setting process group of " + app.processName
13359 + " to " + app.curSchedGroup);
13360 if (app.waitingToKill != null &&
13361 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13362 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13363 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13364 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013365 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013366 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013367 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013368 } else {
13369 if (true) {
13370 long oldId = Binder.clearCallingIdentity();
13371 try {
13372 Process.setProcessGroup(app.pid, app.curSchedGroup);
13373 } catch (Exception e) {
13374 Slog.w(TAG, "Failed setting process group of " + app.pid
13375 + " to " + app.curSchedGroup);
13376 e.printStackTrace();
13377 } finally {
13378 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013379 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013380 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013381 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013382 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013383 app.thread.setSchedulingGroup(app.curSchedGroup);
13384 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013385 }
13386 }
13387 }
13388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013390 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013391 }
13392
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013393 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013394 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013395 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013396 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013397 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013398 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013399 }
13400 }
13401 return resumedActivity;
13402 }
13403
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013404 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013405 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13407 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013408 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13409 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013410
13411 mAdjSeq++;
13412
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013413 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13414 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013415 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13416 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013417 if (nowHidden != wasHidden) {
13418 // Changed to/from hidden state, so apps after it in the LRU
13419 // list may also be changed.
13420 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013421 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013422 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013423 }
13424
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013425 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013426 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013427 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13428
13429 if (false) {
13430 RuntimeException e = new RuntimeException();
13431 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013432 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013433 }
13434
13435 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013436 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013437
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013438 // Let's determine how many processes we have running vs.
13439 // how many slots we have for background processes; we may want
13440 // to put multiple processes in a slot of there are enough of
13441 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013442 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13443 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13444 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13445 if (emptyFactor < 1) emptyFactor = 1;
13446 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13447 if (hiddenFactor < 1) hiddenFactor = 1;
13448 int stepHidden = 0;
13449 int stepEmpty = 0;
13450 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13451 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013452 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013453 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013454 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013455
13456 mNumNonHiddenProcs = 0;
13457 mNumHiddenProcs = 0;
13458
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013459 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013460 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013461 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013462 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013463 int nextHiddenAdj = curHiddenAdj+1;
13464 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13465 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013466 while (i > 0) {
13467 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013468 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013469 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013470 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013471 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013472 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13473 // This process was assigned as a hidden process... step the
13474 // hidden level.
13475 mNumHiddenProcs++;
13476 if (curHiddenAdj != nextHiddenAdj) {
13477 stepHidden++;
13478 if (stepHidden >= hiddenFactor) {
13479 stepHidden = 0;
13480 curHiddenAdj = nextHiddenAdj;
13481 nextHiddenAdj += 2;
13482 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13483 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13484 }
13485 }
13486 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013487 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013488 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013489 Slog.i(TAG, "No longer want " + app.processName
13490 + " (pid " + app.pid + "): hidden #" + numHidden);
13491 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13492 app.processName, app.setAdj, "too many background");
13493 app.killedBackground = true;
13494 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013495 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013496 } else {
13497 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13498 // This process was assigned as an empty process... step the
13499 // empty level.
13500 if (curEmptyAdj != nextEmptyAdj) {
13501 stepEmpty++;
13502 if (stepEmpty >= emptyFactor) {
13503 stepEmpty = 0;
13504 curEmptyAdj = nextEmptyAdj;
13505 nextEmptyAdj += 2;
13506 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13507 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13508 }
13509 }
13510 }
13511 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13512 mNumNonHiddenProcs++;
13513 }
13514 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13515 numEmpty++;
13516 if (numEmpty > emptyProcessLimit) {
13517 Slog.i(TAG, "No longer want " + app.processName
13518 + " (pid " + app.pid + "): empty #" + numEmpty);
13519 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13520 app.processName, app.setAdj, "too many background");
13521 app.killedBackground = true;
13522 Process.killProcessQuiet(app.pid);
13523 }
13524 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013525 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013526 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013527 // If this is an isolated process, and there are no
13528 // services running in it, then the process is no longer
13529 // needed. We agressively kill these because we can by
13530 // definition not re-use the same process again, and it is
13531 // good to avoid having whatever code was running in them
13532 // left sitting around after no longer needed.
13533 Slog.i(TAG, "Isolated process " + app.processName
13534 + " (pid " + app.pid + ") no longer needed");
13535 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13536 app.processName, app.setAdj, "isolated not needed");
13537 app.killedBackground = true;
13538 Process.killProcessQuiet(app.pid);
13539 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013540 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13541 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13542 && !app.killedBackground) {
13543 numTrimming++;
13544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013545 }
13546 }
13547
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013548 mNumServiceProcs = mNewNumServiceProcs;
13549
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013550 // Now determine the memory trimming level of background processes.
13551 // Unfortunately we need to start at the back of the list to do this
13552 // properly. We only do this if the number of background apps we
13553 // are managing to keep around is less than half the maximum we desire;
13554 // if we are keeping a good number around, we'll let them use whatever
13555 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013556 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13557 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13558 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013559 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013560 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013561 int minFactor = 2;
13562 if (mHomeProcess != null) minFactor++;
13563 if (mPreviousProcess != null) minFactor++;
13564 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013565 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013566 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013567 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013568 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013569 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013570 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13571 } else {
13572 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13573 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013574 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013575 for (i=0; i<N; i++) {
13576 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013577 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13578 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013579 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013580 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13581 try {
13582 app.thread.scheduleTrimMemory(curLevel);
13583 } catch (RemoteException e) {
13584 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013585 if (false) {
13586 // For now we won't do this; our memory trimming seems
13587 // to be good enough at this point that destroying
13588 // activities causes more harm than good.
13589 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13590 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013591 // Need to do this on its own message because the stack may not
13592 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013593 // For these apps we will also finish their activities
13594 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013595 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013596 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013597 }
13598 }
13599 app.trimMemoryLevel = curLevel;
13600 step++;
13601 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013602 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013603 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013604 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13605 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013606 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013607 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13608 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013609 break;
13610 }
13611 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013612 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013613 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013614 && app.thread != null) {
13615 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013616 app.thread.scheduleTrimMemory(
13617 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013618 } catch (RemoteException e) {
13619 }
13620 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013621 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013622 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013623 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013624 && app.pendingUiClean) {
13625 // If this application is now in the background and it
13626 // had done UI, then give it the special trim level to
13627 // have it free UI resources.
13628 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13629 if (app.trimMemoryLevel < level && app.thread != null) {
13630 try {
13631 app.thread.scheduleTrimMemory(level);
13632 } catch (RemoteException e) {
13633 }
13634 }
13635 app.pendingUiClean = false;
13636 }
13637 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013638 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013639 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013640 } catch (RemoteException e) {
13641 }
13642 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013643 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013644 }
13645 }
13646 } else {
13647 final int N = mLruProcesses.size();
13648 for (i=0; i<N; i++) {
13649 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013650 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013651 && app.pendingUiClean) {
13652 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13653 && app.thread != null) {
13654 try {
13655 app.thread.scheduleTrimMemory(
13656 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13657 } catch (RemoteException e) {
13658 }
13659 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013660 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013661 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013662 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013663 }
13664 }
13665
13666 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013667 // Need to do this on its own message because the stack may not
13668 // be in a consistent state at this point.
13669 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013671 }
13672
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013673 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013674 synchronized (this) {
13675 int i;
13676
13677 // First remove any unused application processes whose package
13678 // has been removed.
13679 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13680 final ProcessRecord app = mRemovedProcesses.get(i);
13681 if (app.activities.size() == 0
13682 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013683 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013684 TAG, "Exiting empty application process "
13685 + app.processName + " ("
13686 + (app.thread != null ? app.thread.asBinder() : null)
13687 + ")\n");
13688 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013689 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13690 app.processName, app.setAdj, "empty");
13691 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013692 } else {
13693 try {
13694 app.thread.scheduleExit();
13695 } catch (Exception e) {
13696 // Ignore exceptions.
13697 }
13698 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013699 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 mRemovedProcesses.remove(i);
13701
13702 if (app.persistent) {
13703 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013704 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013705 }
13706 }
13707 }
13708 }
13709
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013710 // Now update the oom adj for all processes.
13711 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013712 }
13713 }
13714
13715 /** This method sends the specified signal to each of the persistent apps */
13716 public void signalPersistentProcesses(int sig) throws RemoteException {
13717 if (sig != Process.SIGNAL_USR1) {
13718 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13719 }
13720
13721 synchronized (this) {
13722 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13723 != PackageManager.PERMISSION_GRANTED) {
13724 throw new SecurityException("Requires permission "
13725 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13726 }
13727
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013728 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13729 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013730 if (r.thread != null && r.persistent) {
13731 Process.sendSignal(r.pid, sig);
13732 }
13733 }
13734 }
13735 }
13736
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013737 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13738 if (proc == null || proc == mProfileProc) {
13739 proc = mProfileProc;
13740 path = mProfileFile;
13741 profileType = mProfileType;
13742 clearProfilerLocked();
13743 }
13744 if (proc == null) {
13745 return;
13746 }
13747 try {
13748 proc.thread.profilerControl(false, path, null, profileType);
13749 } catch (RemoteException e) {
13750 throw new IllegalStateException("Process disappeared");
13751 }
13752 }
13753
13754 private void clearProfilerLocked() {
13755 if (mProfileFd != null) {
13756 try {
13757 mProfileFd.close();
13758 } catch (IOException e) {
13759 }
13760 }
13761 mProfileApp = null;
13762 mProfileProc = null;
13763 mProfileFile = null;
13764 mProfileType = 0;
13765 mAutoStopProfiler = false;
13766 }
13767
Dianne Hackborn1676c852012-09-10 14:52:30 -070013768 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013769 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013770
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013771 try {
13772 synchronized (this) {
13773 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13774 // its own permission.
13775 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13776 != PackageManager.PERMISSION_GRANTED) {
13777 throw new SecurityException("Requires permission "
13778 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013779 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013780
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013781 if (start && fd == null) {
13782 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013783 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013784
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013785 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013786 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013787 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013788 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013789
13790 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013791 throw new IllegalArgumentException("Unknown process: " + process);
13792 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013793
13794 if (start) {
13795 stopProfilerLocked(null, null, 0);
13796 setProfileApp(proc.info, proc.processName, path, fd, false);
13797 mProfileProc = proc;
13798 mProfileType = profileType;
13799 try {
13800 fd = fd.dup();
13801 } catch (IOException e) {
13802 fd = null;
13803 }
13804 proc.thread.profilerControl(start, path, fd, profileType);
13805 fd = null;
13806 mProfileFd = null;
13807 } else {
13808 stopProfilerLocked(proc, path, profileType);
13809 if (fd != null) {
13810 try {
13811 fd.close();
13812 } catch (IOException e) {
13813 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013814 }
13815 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013816
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013817 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013818 }
13819 } catch (RemoteException e) {
13820 throw new IllegalStateException("Process disappeared");
13821 } finally {
13822 if (fd != null) {
13823 try {
13824 fd.close();
13825 } catch (IOException e) {
13826 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013827 }
13828 }
13829 }
Andy McFadden824c5102010-07-09 16:26:57 -070013830
Dianne Hackborn1676c852012-09-10 14:52:30 -070013831 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
13832 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
13833 userId, true, true, callName, null);
13834 ProcessRecord proc = null;
13835 try {
13836 int pid = Integer.parseInt(process);
13837 synchronized (mPidsSelfLocked) {
13838 proc = mPidsSelfLocked.get(pid);
13839 }
13840 } catch (NumberFormatException e) {
13841 }
13842
13843 if (proc == null) {
13844 HashMap<String, SparseArray<ProcessRecord>> all
13845 = mProcessNames.getMap();
13846 SparseArray<ProcessRecord> procs = all.get(process);
13847 if (procs != null && procs.size() > 0) {
13848 proc = procs.valueAt(0);
13849 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13850 for (int i=1; i<procs.size(); i++) {
13851 ProcessRecord thisProc = procs.valueAt(i);
13852 if (thisProc.userId == userId) {
13853 proc = thisProc;
13854 break;
13855 }
13856 }
13857 }
13858 }
13859 }
13860
13861 return proc;
13862 }
13863
13864 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013865 String path, ParcelFileDescriptor fd) throws RemoteException {
13866
13867 try {
13868 synchronized (this) {
13869 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13870 // its own permission (same as profileControl).
13871 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13872 != PackageManager.PERMISSION_GRANTED) {
13873 throw new SecurityException("Requires permission "
13874 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13875 }
13876
13877 if (fd == null) {
13878 throw new IllegalArgumentException("null fd");
13879 }
13880
Dianne Hackborn1676c852012-09-10 14:52:30 -070013881 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013882 if (proc == null || proc.thread == null) {
13883 throw new IllegalArgumentException("Unknown process: " + process);
13884 }
13885
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013886 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13887 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013888 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13889 throw new SecurityException("Process not debuggable: " + proc);
13890 }
13891 }
13892
13893 proc.thread.dumpHeap(managed, path, fd);
13894 fd = null;
13895 return true;
13896 }
13897 } catch (RemoteException e) {
13898 throw new IllegalStateException("Process disappeared");
13899 } finally {
13900 if (fd != null) {
13901 try {
13902 fd.close();
13903 } catch (IOException e) {
13904 }
13905 }
13906 }
13907 }
13908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013909 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13910 public void monitor() {
13911 synchronized (this) { }
13912 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013913
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013914 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013915 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13916 ProcessRecord processRecord = mLruProcesses.get(i);
13917 try {
13918 if (processRecord.thread != null) {
13919 processRecord.thread.setCoreSettings(settings);
13920 }
13921 } catch (RemoteException re) {
13922 /* ignore */
13923 }
13924 }
13925 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013926
13927 // Multi-user methods
13928
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013929 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013930 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013931 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13932 != PackageManager.PERMISSION_GRANTED) {
13933 String msg = "Permission Denial: switchUser() from pid="
13934 + Binder.getCallingPid()
13935 + ", uid=" + Binder.getCallingUid()
13936 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13937 Slog.w(TAG, msg);
13938 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013939 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013940
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013941 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013942 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013943 synchronized (this) {
13944 final int oldUserId = mCurrentUserId;
13945 if (oldUserId == userId) {
13946 return true;
13947 }
13948
13949 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
13950 if (userInfo == null) {
13951 Slog.w(TAG, "No user info for user #" + userId);
13952 return false;
13953 }
13954
13955 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
13956 R.anim.screen_user_enter);
13957
13958 // If the user we are switching to is not currently started, then
13959 // we need to start it now.
13960 if (mStartedUsers.get(userId) == null) {
13961 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
13962 }
13963
13964 mCurrentUserId = userId;
13965 final Integer userIdInt = Integer.valueOf(userId);
13966 mUserLru.remove(userIdInt);
13967 mUserLru.add(userIdInt);
13968
13969 final UserStartedState uss = mStartedUsers.get(userId);
13970
13971 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
13972 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
13973 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
13974 oldUserId, userId, uss));
13975 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
13976 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
13977 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
13978 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13979 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13980 broadcastIntentLocked(null, null, intent,
13981 null, null, 0, null, null, null,
13982 false, false, MY_PID, Process.SYSTEM_UID, userId);
13983
13984 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
13985 if (userId != 0) {
13986 intent = new Intent(Intent.ACTION_USER_INITIALIZE);
13987 broadcastIntentLocked(null, null, intent, null,
13988 new IIntentReceiver.Stub() {
13989 public void performReceive(Intent intent, int resultCode,
13990 String data, Bundle extras, boolean ordered,
13991 boolean sticky, int sendingUser) {
13992 synchronized (ActivityManagerService.this) {
13993 getUserManagerLocked().makeInitialized(userInfo.id);
13994 }
13995 }
13996 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
13997 userId);
13998 } else {
13999 getUserManagerLocked().makeInitialized(userInfo.id);
14000 }
14001 }
14002
14003 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14004 if (!haveActivities) {
14005 startHomeActivityLocked(userId);
14006 }
14007
14008 sendUserSwitchBroadcastsLocked(oldUserId, userId);
14009 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014010 } finally {
14011 Binder.restoreCallingIdentity(ident);
14012 }
Amith Yamasani13593602012-03-22 16:16:17 -070014013
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014014 return true;
14015 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014016
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014017 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14018 long ident = Binder.clearCallingIdentity();
14019 try {
14020 Intent intent;
14021 if (oldUserId >= 0) {
14022 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
14023 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14024 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14025 broadcastIntentLocked(null, null, intent,
14026 null, null, 0, null, null, null,
14027 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14028 }
14029 if (newUserId >= 0) {
14030 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
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, null,
14035 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14036 intent = new Intent(Intent.ACTION_USER_SWITCHED);
14037 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14038 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14039 broadcastIntentLocked(null, null, intent,
14040 null, null, 0, null, null,
14041 android.Manifest.permission.MANAGE_USERS,
14042 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14043 }
14044 } finally {
14045 Binder.restoreCallingIdentity(ident);
14046 }
14047 }
14048
14049 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14050 final int newUserId) {
14051 final int N = mUserSwitchObservers.beginBroadcast();
14052 if (N > 0) {
14053 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14054 int mCount = 0;
14055 @Override
14056 public void sendResult(Bundle data) throws RemoteException {
14057 synchronized (ActivityManagerService.this) {
14058 if (mCurUserSwitchCallback == this) {
14059 mCount++;
14060 if (mCount == N) {
14061 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14062 }
14063 }
14064 }
14065 }
14066 };
14067 synchronized (this) {
14068 mCurUserSwitchCallback = callback;
14069 }
14070 for (int i=0; i<N; i++) {
14071 try {
14072 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14073 newUserId, callback);
14074 } catch (RemoteException e) {
14075 }
14076 }
14077 } else {
14078 synchronized (this) {
14079 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14080 }
14081 }
14082 mUserSwitchObservers.finishBroadcast();
14083 }
14084
14085 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14086 synchronized (this) {
14087 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14088 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14089 }
14090 }
14091
14092 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14093 mCurUserSwitchCallback = null;
14094 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14095 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14096 oldUserId, newUserId, uss));
14097 }
14098
14099 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14100 final int N = mUserSwitchObservers.beginBroadcast();
14101 for (int i=0; i<N; i++) {
14102 try {
14103 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14104 } catch (RemoteException e) {
14105 }
14106 }
14107 mUserSwitchObservers.finishBroadcast();
14108 synchronized (this) {
14109 mWindowManager.stopFreezingScreen();
14110 }
14111 }
14112
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014113 void finishUserSwitch(UserStartedState uss) {
14114 synchronized (this) {
14115 if (uss.mState == UserStartedState.STATE_BOOTING
14116 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14117 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014118 final int userId = uss.mHandle.getIdentifier();
14119 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14120 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14121 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014122 null, null, 0, null, null,
14123 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014124 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014125 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014126 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014127 }
14128
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014129 @Override
14130 public int stopUser(final int userId, final IStopUserCallback callback) {
14131 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14132 != PackageManager.PERMISSION_GRANTED) {
14133 String msg = "Permission Denial: switchUser() from pid="
14134 + Binder.getCallingPid()
14135 + ", uid=" + Binder.getCallingUid()
14136 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14137 Slog.w(TAG, msg);
14138 throw new SecurityException(msg);
14139 }
14140 if (userId <= 0) {
14141 throw new IllegalArgumentException("Can't stop primary user " + userId);
14142 }
Amith Yamasani13593602012-03-22 16:16:17 -070014143 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014144 if (mCurrentUserId == userId) {
14145 return ActivityManager.USER_OP_IS_CURRENT;
14146 }
14147
14148 final UserStartedState uss = mStartedUsers.get(userId);
14149 if (uss == null) {
14150 // User is not started, nothing to do... but we do need to
14151 // callback if requested.
14152 if (callback != null) {
14153 mHandler.post(new Runnable() {
14154 @Override
14155 public void run() {
14156 try {
14157 callback.userStopped(userId);
14158 } catch (RemoteException e) {
14159 }
14160 }
14161 });
14162 }
14163 return ActivityManager.USER_OP_SUCCESS;
14164 }
14165
14166 if (callback != null) {
14167 uss.mStopCallbacks.add(callback);
14168 }
14169
14170 if (uss.mState != UserStartedState.STATE_STOPPING) {
14171 uss.mState = UserStartedState.STATE_STOPPING;
14172
14173 long ident = Binder.clearCallingIdentity();
14174 try {
14175 // Inform of user switch
14176 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
14177 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
14178 @Override
14179 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070014180 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014181 finishUserStop(uss);
14182 }
14183 };
14184 broadcastIntentLocked(null, null, intent,
14185 null, resultReceiver, 0, null, null, null,
14186 true, false, MY_PID, Process.SYSTEM_UID, userId);
14187 } finally {
14188 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014189 }
14190 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014191 }
Amith Yamasani13593602012-03-22 16:16:17 -070014192
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014193 return ActivityManager.USER_OP_SUCCESS;
14194 }
14195
14196 void finishUserStop(UserStartedState uss) {
14197 final int userId = uss.mHandle.getIdentifier();
14198 boolean stopped;
14199 ArrayList<IStopUserCallback> callbacks;
14200 synchronized (this) {
14201 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
14202 if (uss.mState != UserStartedState.STATE_STOPPING
14203 || mStartedUsers.get(userId) != uss) {
14204 stopped = false;
14205 } else {
14206 stopped = true;
14207 // User can no longer run.
14208 mStartedUsers.remove(userId);
14209
14210 // Clean up all state and processes associated with the user.
14211 // Kill all the processes for the user.
14212 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014213 }
14214 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014215
14216 for (int i=0; i<callbacks.size(); i++) {
14217 try {
14218 if (stopped) callbacks.get(i).userStopped(userId);
14219 else callbacks.get(i).userStopAborted(userId);
14220 } catch (RemoteException e) {
14221 }
14222 }
14223 }
14224
14225 @Override
14226 public UserInfo getCurrentUser() {
14227 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14228 != PackageManager.PERMISSION_GRANTED) {
14229 String msg = "Permission Denial: getCurrentUser() from pid="
14230 + Binder.getCallingPid()
14231 + ", uid=" + Binder.getCallingUid()
14232 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14233 Slog.w(TAG, msg);
14234 throw new SecurityException(msg);
14235 }
14236 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014237 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014238 }
Amith Yamasani13593602012-03-22 16:16:17 -070014239 }
14240
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014241 @Override
14242 public boolean isUserRunning(int userId) {
14243 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14244 != PackageManager.PERMISSION_GRANTED) {
14245 String msg = "Permission Denial: isUserRunning() from pid="
14246 + Binder.getCallingPid()
14247 + ", uid=" + Binder.getCallingUid()
14248 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14249 Slog.w(TAG, msg);
14250 throw new SecurityException(msg);
14251 }
14252 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014253 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014254 }
14255 }
14256
Dianne Hackborn1676c852012-09-10 14:52:30 -070014257 boolean isUserRunningLocked(int userId) {
14258 UserStartedState state = mStartedUsers.get(userId);
14259 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014260 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014261
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014262 @Override
14263 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14264 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14265 != PackageManager.PERMISSION_GRANTED) {
14266 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14267 + Binder.getCallingPid()
14268 + ", uid=" + Binder.getCallingUid()
14269 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14270 Slog.w(TAG, msg);
14271 throw new SecurityException(msg);
14272 }
14273
14274 mUserSwitchObservers.register(observer);
14275 }
14276
14277 @Override
14278 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14279 mUserSwitchObservers.unregister(observer);
14280 }
14281
Dianne Hackborn1676c852012-09-10 14:52:30 -070014282 private boolean userExists(int userId) {
14283 if (userId == 0) {
14284 return true;
14285 }
14286 UserManagerService ums = getUserManagerLocked();
14287 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14288 }
14289
14290 int[] getUsersLocked() {
14291 UserManagerService ums = getUserManagerLocked();
14292 return ums != null ? ums.getUserIds() : new int[] { 0 };
14293 }
14294
14295 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014296 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014297 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14298 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014299 }
14300 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014301 }
14302
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014303 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014304 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014305
14306 throw new SecurityException("Caller uid=" + uid
14307 + " is not privileged to communicate with user=" + userId);
14308 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014309
14310 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014311 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014312 }
14313
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014314 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014315 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014316 ApplicationInfo newInfo = new ApplicationInfo(info);
14317 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014318 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14319 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014320 return newInfo;
14321 }
14322
14323 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014324 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014325 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014326 return aInfo;
14327 }
14328
14329 ActivityInfo info = new ActivityInfo(aInfo);
14330 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14331 return info;
14332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014333}