blob: 110ab50b70f047df0bfafe22ad7d984462f50244 [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;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700171 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_PAUSE = localLOGV || false;
173 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
174 static final boolean DEBUG_TRANSITION = localLOGV || false;
175 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800176 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700177 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700179 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_VISBILITY = localLOGV || false;
181 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700182 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700183 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800184 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700186 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700187 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700188 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700189 static final boolean DEBUG_POWER = localLOGV || false;
190 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700191 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 static final boolean VALIDATE_TOKENS = false;
193 static final boolean SHOW_ACTIVITY_START_TIME = true;
194
195 // Control over CPU and battery monitoring.
196 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
197 static final boolean MONITOR_CPU_USAGE = true;
198 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
199 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
200 static final boolean MONITOR_THREAD_CPU_USAGE = false;
201
Dianne Hackborn1655be42009-05-08 14:29:01 -0700202 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700203 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700204
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800205 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700207 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 // Maximum number of recent tasks that we can remember.
210 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700211
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700212 // Amount of time after a call to stopAppSwitches() during which we will
213 // prevent further untrusted switches from happening.
214 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
216 // How long we wait for a launched process to attach to the activity manager
217 // before we decide it's never going to come up for real.
218 static final int PROC_START_TIMEOUT = 10*1000;
219
Jeff Brown3f9dd282011-07-08 20:02:19 -0700220 // How long we wait for a launched process to attach to the activity manager
221 // before we decide it's never going to come up for real, when the process was
222 // started with a wrapper for instrumentation (such as Valgrind) because it
223 // could take much longer than usual.
224 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 // How long to wait after going idle before forcing apps to GC.
227 static final int GC_TIMEOUT = 5*1000;
228
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700229 // The minimum amount of time between successive GC requests for a process.
230 static final int GC_MIN_INTERVAL = 60*1000;
231
Dianne Hackborn287952c2010-09-22 22:34:31 -0700232 // The rate at which we check for apps using excessive power -- 15 mins.
233 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
234
235 // The minimum sample duration we will allow before deciding we have
236 // enough data on wake locks to start killing things.
237 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
238
239 // The minimum sample duration we will allow before deciding we have
240 // enough data on CPU usage to start killing things.
241 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800244 static final int BROADCAST_FG_TIMEOUT = 10*1000;
245 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // How long we wait until we timeout on key dispatching.
248 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // How long we wait until we timeout on key dispatching during instrumentation.
251 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
252
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700253 // Amount of time we wait for observers to handle a user switch before
254 // giving up on them and unfreezing the screen.
255 static final int USER_SWITCH_TIMEOUT = 2*1000;
256
Dan Egnor42471dd2010-01-07 17:25:22 -0800257 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
259 static final String[] EMPTY_STRING_ARRAY = new String[0];
260
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700261 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700262
263 private final boolean mHeadless;
264
Joe Onorato54a4a412011-11-02 20:50:08 -0700265 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
266 // default actuion automatically. Important for devices without direct input
267 // devices.
268 private boolean mShowDialogs = true;
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700271 * Description of a request to start a new activity, which has been held
272 * due to app switches being disabled.
273 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700274 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700275 ActivityRecord r;
276 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700277 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700278 }
279
280 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
281 = new ArrayList<PendingActivityLaunch>();
282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800284 BroadcastQueue mFgBroadcastQueue;
285 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800286 // Convenient for easy iteration over the queues. Foreground is first
287 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800288 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800289
290 BroadcastQueue broadcastQueueForIntent(Intent intent) {
291 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
292 if (DEBUG_BACKGROUND_BROADCAST) {
293 Slog.i(TAG, "Broadcast intent " + intent + " on "
294 + (isFg ? "foreground" : "background")
295 + " queue");
296 }
297 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
298 }
299
300 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
301 for (BroadcastQueue queue : mBroadcastQueues) {
302 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
303 if (r != null) {
304 return r;
305 }
306 }
307 return null;
308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309
310 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 * Activity we have told the window manager to have key focus.
312 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700313 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700314 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 * List of intents that were used to start the most recent tasks.
316 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700317 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318
319 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700320 * Process management.
321 */
322 final ProcessList mProcessList = new ProcessList();
323
324 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 * All of the applications we currently have running organized by name.
326 * The keys are strings of the application package name (as
327 * returned by the package manager), and the keys are ApplicationRecord
328 * objects.
329 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700330 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331
332 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800333 * The currently running isolated processes.
334 */
335 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
336
337 /**
338 * Counter for assigning isolated process uids, to avoid frequently reusing the
339 * same ones.
340 */
341 int mNextIsolatedProcessUid = 0;
342
343 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700344 * The currently running heavy-weight process, if any.
345 */
346 ProcessRecord mHeavyWeightProcess = null;
347
348 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 * The last time that various processes have crashed.
350 */
351 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
352
353 /**
354 * Set of applications that we consider to be bad, and will reject
355 * incoming broadcasts from (which the user has no control over).
356 * Processes are added to this set when they have crashed twice within
357 * a minimum amount of time; they are removed from it when they are
358 * later restarted (hopefully due to some user action). The value is the
359 * time it was added to the list.
360 */
361 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
362
363 /**
364 * All of the processes we currently have running organized by pid.
365 * The keys are the pid running the application.
366 *
367 * <p>NOTE: This object is protected by its own lock, NOT the global
368 * activity manager lock!
369 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700370 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371
372 /**
373 * All of the processes that have been forced to be foreground. The key
374 * is the pid of the caller who requested it (we hold a death
375 * link on it).
376 */
377 abstract class ForegroundToken implements IBinder.DeathRecipient {
378 int pid;
379 IBinder token;
380 }
381 final SparseArray<ForegroundToken> mForegroundProcesses
382 = new SparseArray<ForegroundToken>();
383
384 /**
385 * List of records for processes that someone had tried to start before the
386 * system was ready. We don't start them at that point, but ensure they
387 * are started by the time booting is complete.
388 */
389 final ArrayList<ProcessRecord> mProcessesOnHold
390 = new ArrayList<ProcessRecord>();
391
392 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 * List of persistent applications that are in the process
394 * of being started.
395 */
396 final ArrayList<ProcessRecord> mPersistentStartingProcesses
397 = new ArrayList<ProcessRecord>();
398
399 /**
400 * Processes that are being forcibly torn down.
401 */
402 final ArrayList<ProcessRecord> mRemovedProcesses
403 = new ArrayList<ProcessRecord>();
404
405 /**
406 * List of running applications, sorted by recent usage.
407 * The first entry in the list is the least recently used.
408 * It contains ApplicationRecord objects. This list does NOT include
409 * any persistent application records (since we never want to exit them).
410 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800411 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 = new ArrayList<ProcessRecord>();
413
414 /**
415 * List of processes that should gc as soon as things are idle.
416 */
417 final ArrayList<ProcessRecord> mProcessesToGc
418 = new ArrayList<ProcessRecord>();
419
420 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800421 * This is the process holding what we currently consider to be
422 * the "home" activity.
423 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700424 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800425
426 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700427 * This is the process holding the activity the user last visited that
428 * is in a different process from the one they are currently in.
429 */
430 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800431
432 /**
433 * The time at which the previous process was last visible.
434 */
435 long mPreviousProcessVisibleTime;
436
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700437 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700438 * Which uses have been started, so are allowed to run code.
439 */
440 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
441
442 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700443 * LRU list of history of current users. Most recently current is at the end.
444 */
445 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
446
447 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700448 * Registered observers of the user switching mechanics.
449 */
450 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
451 = new RemoteCallbackList<IUserSwitchObserver>();
452
453 /**
454 * Currently active user switch.
455 */
456 Object mCurUserSwitchCallback;
457
458 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400459 * Packages that the user has asked to have run in screen size
460 * compatibility mode instead of filling the screen.
461 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700462 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400463
464 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 * Set of PendingResultRecord objects that are currently active.
466 */
467 final HashSet mPendingResultRecords = new HashSet();
468
469 /**
470 * Set of IntentSenderRecord objects that are currently active.
471 */
472 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
473 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
474
475 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800476 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700477 * already logged DropBox entries for. Guarded by itself. If
478 * something (rogue user app) forces this over
479 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
480 */
481 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
482 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
483
484 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700485 * Strict Mode background batched logging state.
486 *
487 * The string buffer is guarded by itself, and its lock is also
488 * used to determine if another batched write is already
489 * in-flight.
490 */
491 private final StringBuilder mStrictModeBuffer = new StringBuilder();
492
493 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 * Keeps track of all IIntentReceivers that have been registered for
495 * broadcasts. Hash keys are the receiver IBinder, hash value is
496 * a ReceiverList.
497 */
498 final HashMap mRegisteredReceivers = new HashMap();
499
500 /**
501 * Resolver for broadcast intents to registered receivers.
502 * Holds BroadcastFilter (subclass of IntentFilter).
503 */
504 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
505 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
506 @Override
507 protected boolean allowFilterResult(
508 BroadcastFilter filter, List<BroadcastFilter> dest) {
509 IBinder target = filter.receiverList.receiver.asBinder();
510 for (int i=dest.size()-1; i>=0; i--) {
511 if (dest.get(i).receiverList.receiver.asBinder() == target) {
512 return false;
513 }
514 }
515 return true;
516 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700517
518 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700519 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700520 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
521 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700522 return super.newResult(filter, match, userId);
523 }
524 return null;
525 }
526
527 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700528 protected BroadcastFilter[] newArray(int size) {
529 return new BroadcastFilter[size];
530 }
531
532 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700533 protected String packageForFilter(BroadcastFilter filter) {
534 return filter.packageName;
535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 };
537
538 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700539 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700541 * that action (which should usually be one). The SparseArray is keyed
542 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
543 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700545 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
546 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700548 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
550 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700551 * Backup/restore process management
552 */
553 String mBackupAppName = null;
554 BackupRecord mBackupTarget = null;
555
556 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 * List of PendingThumbnailsRecord objects of clients who are still
558 * waiting to receive all of the thumbnails for a task.
559 */
560 final ArrayList mPendingThumbnails = new ArrayList();
561
562 /**
563 * List of HistoryRecord objects that have been finished and must
564 * still report back to a pending thumbnail receiver.
565 */
566 final ArrayList mCancelledThumbnails = new ArrayList();
567
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700568 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 /**
571 * List of content providers who have clients waiting for them. The
572 * application is currently being launched and the provider will be
573 * removed from this list once it is published.
574 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700575 final ArrayList<ContentProviderRecord> mLaunchingProviders
576 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577
578 /**
579 * Global set of specific Uri permissions that have been granted.
580 */
581 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
582 = new SparseArray<HashMap<Uri, UriPermission>>();
583
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800584 CoreSettingsObserver mCoreSettingsObserver;
585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 /**
587 * Thread-local storage used to carry caller permissions over through
588 * indirect content-provider access.
589 * @see #ActivityManagerService.openContentUri()
590 */
591 private class Identity {
592 public int pid;
593 public int uid;
594
595 Identity(int _pid, int _uid) {
596 pid = _pid;
597 uid = _uid;
598 }
599 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
602
603 /**
604 * All information we have collected about the runtime performance of
605 * any user id that can impact battery performance.
606 */
607 final BatteryStatsService mBatteryStatsService;
608
609 /**
610 * information about component usage
611 */
612 final UsageStatsService mUsageStatsService;
613
614 /**
615 * Current configuration information. HistoryRecord objects are given
616 * a reference to this object to indicate which configuration they are
617 * currently running in, so this object must be kept immutable.
618 */
619 Configuration mConfiguration = new Configuration();
620
621 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800622 * Current sequencing integer of the configuration, for skipping old
623 * configurations.
624 */
625 int mConfigurationSeq = 0;
626
627 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700628 * Hardware-reported OpenGLES version.
629 */
630 final int GL_ES_VERSION;
631
632 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 * List of initialization arguments to pass to all processes when binding applications to them.
634 * For example, references to the commonly used services.
635 */
636 HashMap<String, IBinder> mAppBindArgs;
637
638 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700639 * Temporary to avoid allocations. Protected by main lock.
640 */
641 final StringBuilder mStringBuilder = new StringBuilder(256);
642
643 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 * Used to control how we initialize the service.
645 */
646 boolean mStartRunning = false;
647 ComponentName mTopComponent;
648 String mTopAction;
649 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700650 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 boolean mSystemReady = false;
652 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700653 boolean mWaitingUpdate = false;
654 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700655 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700656 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657
658 Context mContext;
659
660 int mFactoryTest;
661
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700662 boolean mCheckedForSetup;
663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700665 * The time at which we will allow normal application switches again,
666 * after a call to {@link #stopAppSwitches()}.
667 */
668 long mAppSwitchesAllowedTime;
669
670 /**
671 * This is set to true after the first switch after mAppSwitchesAllowedTime
672 * is set; any switches after that will clear the time.
673 */
674 boolean mDidAppSwitch;
675
676 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700677 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700678 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700679 long mLastPowerCheckRealtime;
680
681 /**
682 * Last time (in uptime) at which we checked for power usage.
683 */
684 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685
686 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 * Set while we are wanting to sleep, to prevent any
688 * activities from being started/resumed.
689 */
690 boolean mSleeping = false;
691
692 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700693 * State of external calls telling us if the device is asleep.
694 */
695 boolean mWentToSleep = false;
696
697 /**
698 * State of external call telling us if the lock screen is shown.
699 */
700 boolean mLockScreenShown = false;
701
702 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700703 * Set if we are shutting down the system, similar to sleeping.
704 */
705 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706
707 /**
708 * Task identifier that activities are currently being started
709 * in. Incremented each time a new task is created.
710 * todo: Replace this with a TokenSpace class that generates non-repeating
711 * integers that won't wrap.
712 */
713 int mCurTask = 1;
714
715 /**
716 * Current sequence id for oom_adj computation traversal.
717 */
718 int mAdjSeq = 0;
719
720 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700721 * Current sequence id for process LRU updating.
722 */
723 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724
725 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700726 * Keep track of the non-hidden/empty process we last found, to help
727 * determine how to distribute hidden/empty processes next time.
728 */
729 int mNumNonHiddenProcs = 0;
730
731 /**
732 * Keep track of the number of hidden procs, to balance oom adj
733 * distribution between those and empty procs.
734 */
735 int mNumHiddenProcs = 0;
736
737 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700738 * Keep track of the number of service processes we last found, to
739 * determine on the next iteration which should be B services.
740 */
741 int mNumServiceProcs = 0;
742 int mNewNumServiceProcs = 0;
743
744 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 * System monitoring: number of processes that died since the last
746 * N procs were started.
747 */
748 int[] mProcDeaths = new int[20];
749
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700750 /**
751 * This is set if we had to do a delayed dexopt of an app before launching
752 * it, to increasing the ANR timeouts in that case.
753 */
754 boolean mDidDexOpt;
755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 String mDebugApp = null;
757 boolean mWaitForDebugger = false;
758 boolean mDebugTransient = false;
759 String mOrigDebugApp = null;
760 boolean mOrigWaitForDebugger = false;
761 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700762 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700763 String mProfileApp = null;
764 ProcessRecord mProfileProc = null;
765 String mProfileFile;
766 ParcelFileDescriptor mProfileFd;
767 int mProfileType = 0;
768 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800769 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700771 static class ProcessChangeItem {
772 static final int CHANGE_ACTIVITIES = 1<<0;
773 static final int CHANGE_IMPORTANCE= 1<<1;
774 int changes;
775 int uid;
776 int pid;
777 int importance;
778 boolean foregroundActivities;
779 }
780
Jeff Sharkeya4620792011-05-20 15:29:23 -0700781 final RemoteCallbackList<IProcessObserver> mProcessObservers
782 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700783 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
784
785 final ArrayList<ProcessChangeItem> mPendingProcessChanges
786 = new ArrayList<ProcessChangeItem>();
787 final ArrayList<ProcessChangeItem> mAvailProcessChanges
788 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 /**
791 * Callback of last caller to {@link #requestPss}.
792 */
793 Runnable mRequestPssCallback;
794
795 /**
796 * Remaining processes for which we are waiting results from the last
797 * call to {@link #requestPss}.
798 */
799 final ArrayList<ProcessRecord> mRequestPssList
800 = new ArrayList<ProcessRecord>();
801
802 /**
803 * Runtime statistics collection thread. This object's lock is used to
804 * protect all related state.
805 */
806 final Thread mProcessStatsThread;
807
808 /**
809 * Used to collect process stats when showing not responding dialog.
810 * Protected by mProcessStatsThread.
811 */
812 final ProcessStats mProcessStats = new ProcessStats(
813 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700814 final AtomicLong mLastCpuTime = new AtomicLong(0);
815 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 long mLastWriteTime = 0;
818
819 /**
820 * Set to true after the system has finished booting.
821 */
822 boolean mBooted = false;
823
Dianne Hackborn7d608422011-08-07 16:24:18 -0700824 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700825 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826
827 WindowManagerService mWindowManager;
828
829 static ActivityManagerService mSelf;
830 static ActivityThread mSystemThread;
831
Amith Yamasani258848d2012-08-10 17:06:33 -0700832 private int mCurrentUserId;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700833 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 private final class AppDeathRecipient implements IBinder.DeathRecipient {
836 final ProcessRecord mApp;
837 final int mPid;
838 final IApplicationThread mAppThread;
839
840 AppDeathRecipient(ProcessRecord app, int pid,
841 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800842 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 TAG, "New death recipient " + this
844 + " for thread " + thread.asBinder());
845 mApp = app;
846 mPid = pid;
847 mAppThread = thread;
848 }
849
850 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800851 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 TAG, "Death received in " + this
853 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 synchronized(ActivityManagerService.this) {
855 appDiedLocked(mApp, mPid, mAppThread);
856 }
857 }
858 }
859
860 static final int SHOW_ERROR_MSG = 1;
861 static final int SHOW_NOT_RESPONDING_MSG = 2;
862 static final int SHOW_FACTORY_ERROR_MSG = 3;
863 static final int UPDATE_CONFIGURATION_MSG = 4;
864 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
865 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 static final int SERVICE_TIMEOUT_MSG = 12;
867 static final int UPDATE_TIME_ZONE = 13;
868 static final int SHOW_UID_ERROR_MSG = 14;
869 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700871 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700872 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800873 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700874 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
875 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700876 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700877 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700878 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700879 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700880 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700881 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700882 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700883 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700884 static final int REPORT_USER_SWITCH_MSG = 34;
885 static final int CONTINUE_USER_SWITCH_MSG = 35;
886 static final int USER_SWITCH_TIMEOUT_MSG = 36;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800888 static final int FIRST_ACTIVITY_STACK_MSG = 100;
889 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
890 static final int FIRST_COMPAT_MODE_MSG = 300;
891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700893 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700894 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895
896 final Handler mHandler = new Handler() {
897 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800898 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 //}
900
901 public void handleMessage(Message msg) {
902 switch (msg.what) {
903 case SHOW_ERROR_MSG: {
904 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 synchronized (ActivityManagerService.this) {
906 ProcessRecord proc = (ProcessRecord)data.get("app");
907 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 return;
910 }
911 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700912 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800913 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 d.show();
915 proc.crashDialog = d;
916 } else {
917 // The device is asleep, so just pretend that the user
918 // saw a crash dialog and hit "force quit".
919 res.set(0);
920 }
921 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700922
923 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 } break;
925 case SHOW_NOT_RESPONDING_MSG: {
926 synchronized (ActivityManagerService.this) {
927 HashMap data = (HashMap) msg.obj;
928 ProcessRecord proc = (ProcessRecord)data.get("app");
929 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800930 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 return;
932 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800933
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700934 Intent intent = new Intent("android.intent.action.ANR");
935 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800936 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
937 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700938 }
939 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800940 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700941 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800942
Justin Kohbc52ca22012-03-29 15:11:44 -0700943 if (mShowDialogs) {
944 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700945 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700946 d.show();
947 proc.anrDialog = d;
948 } else {
949 // Just kill the app if there is no dialog to be shown.
950 killAppAtUsersRequest(proc, null);
951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700953
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700954 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700956 case SHOW_STRICT_MODE_VIOLATION_MSG: {
957 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
958 synchronized (ActivityManagerService.this) {
959 ProcessRecord proc = (ProcessRecord) data.get("app");
960 if (proc == null) {
961 Slog.e(TAG, "App not found when showing strict mode dialog.");
962 break;
963 }
964 if (proc.crashDialog != null) {
965 Slog.e(TAG, "App already has strict mode dialog: " + proc);
966 return;
967 }
968 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700969 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700970 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
971 d.show();
972 proc.crashDialog = d;
973 } else {
974 // The device is asleep, so just pretend that the user
975 // saw a crash dialog and hit "force quit".
976 res.set(0);
977 }
978 }
979 ensureBootCompleted();
980 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 case SHOW_FACTORY_ERROR_MSG: {
982 Dialog d = new FactoryErrorDialog(
983 mContext, msg.getData().getCharSequence("msg"));
984 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700985 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 } break;
987 case UPDATE_CONFIGURATION_MSG: {
988 final ContentResolver resolver = mContext.getContentResolver();
989 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
990 } break;
991 case GC_BACKGROUND_PROCESSES_MSG: {
992 synchronized (ActivityManagerService.this) {
993 performAppGcsIfAppropriateLocked();
994 }
995 } break;
996 case WAIT_FOR_DEBUGGER_MSG: {
997 synchronized (ActivityManagerService.this) {
998 ProcessRecord app = (ProcessRecord)msg.obj;
999 if (msg.arg1 != 0) {
1000 if (!app.waitedForDebugger) {
1001 Dialog d = new AppWaitingForDebuggerDialog(
1002 ActivityManagerService.this,
1003 mContext, app);
1004 app.waitDialog = d;
1005 app.waitedForDebugger = true;
1006 d.show();
1007 }
1008 } else {
1009 if (app.waitDialog != null) {
1010 app.waitDialog.dismiss();
1011 app.waitDialog = null;
1012 }
1013 }
1014 }
1015 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001017 if (mDidDexOpt) {
1018 mDidDexOpt = false;
1019 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1020 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001021 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001022 return;
1023 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001024 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 } break;
1026 case UPDATE_TIME_ZONE: {
1027 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001028 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1029 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 if (r.thread != null) {
1031 try {
1032 r.thread.updateTimeZone();
1033 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001034 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
1036 }
1037 }
1038 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001039 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001040 case CLEAR_DNS_CACHE: {
1041 synchronized (ActivityManagerService.this) {
1042 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1043 ProcessRecord r = mLruProcesses.get(i);
1044 if (r.thread != null) {
1045 try {
1046 r.thread.clearDnsCache();
1047 } catch (RemoteException ex) {
1048 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1049 }
1050 }
1051 }
1052 }
1053 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001054 case UPDATE_HTTP_PROXY: {
1055 ProxyProperties proxy = (ProxyProperties)msg.obj;
1056 String host = "";
1057 String port = "";
1058 String exclList = "";
1059 if (proxy != null) {
1060 host = proxy.getHost();
1061 port = Integer.toString(proxy.getPort());
1062 exclList = proxy.getExclusionList();
1063 }
1064 synchronized (ActivityManagerService.this) {
1065 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1066 ProcessRecord r = mLruProcesses.get(i);
1067 if (r.thread != null) {
1068 try {
1069 r.thread.setHttpProxy(host, port, exclList);
1070 } catch (RemoteException ex) {
1071 Slog.w(TAG, "Failed to update http proxy for: " +
1072 r.info.processName);
1073 }
1074 }
1075 }
1076 }
1077 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001079 String title = "System UIDs Inconsistent";
1080 String text = "UIDs on the system are inconsistent, you need to wipe your"
1081 + " data partition or your device will be unstable.";
1082 Log.e(TAG, title + ": " + text);
1083 if (mShowDialogs) {
1084 // XXX This is a temporary dialog, no need to localize.
1085 AlertDialog d = new BaseErrorDialog(mContext);
1086 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1087 d.setCancelable(false);
1088 d.setTitle(title);
1089 d.setMessage(text);
1090 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1091 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1092 mUidAlert = d;
1093 d.show();
1094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 } break;
1096 case IM_FEELING_LUCKY_MSG: {
1097 if (mUidAlert != null) {
1098 mUidAlert.dismiss();
1099 mUidAlert = null;
1100 }
1101 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001103 if (mDidDexOpt) {
1104 mDidDexOpt = false;
1105 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1106 nmsg.obj = msg.obj;
1107 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1108 return;
1109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 ProcessRecord app = (ProcessRecord)msg.obj;
1111 synchronized (ActivityManagerService.this) {
1112 processStartTimedOutLocked(app);
1113 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001114 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001115 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1116 synchronized (ActivityManagerService.this) {
1117 doPendingActivityLaunchesLocked(true);
1118 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001119 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001120 case KILL_APPLICATION_MSG: {
1121 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001122 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001123 boolean restart = (msg.arg2 == 1);
1124 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001125 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1126 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001127 }
1128 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001129 case FINALIZE_PENDING_INTENT_MSG: {
1130 ((PendingIntentRecord)msg.obj).completeFinalize();
1131 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001132 case POST_HEAVY_NOTIFICATION_MSG: {
1133 INotificationManager inm = NotificationManager.getService();
1134 if (inm == null) {
1135 return;
1136 }
1137
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001138 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001139 ProcessRecord process = root.app;
1140 if (process == null) {
1141 return;
1142 }
1143
1144 try {
1145 Context context = mContext.createPackageContext(process.info.packageName, 0);
1146 String text = mContext.getString(R.string.heavy_weight_notification,
1147 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1148 Notification notification = new Notification();
1149 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1150 notification.when = 0;
1151 notification.flags = Notification.FLAG_ONGOING_EVENT;
1152 notification.tickerText = text;
1153 notification.defaults = 0; // please be quiet
1154 notification.sound = null;
1155 notification.vibrate = null;
1156 notification.setLatestEventInfo(context, text,
1157 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001158 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1159 PendingIntent.FLAG_CANCEL_CURRENT, null,
1160 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001161
1162 try {
1163 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001164 inm.enqueueNotificationWithTag("android", null,
1165 R.string.heavy_weight_notification,
1166 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001167 } catch (RuntimeException e) {
1168 Slog.w(ActivityManagerService.TAG,
1169 "Error showing notification for heavy-weight app", e);
1170 } catch (RemoteException e) {
1171 }
1172 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001173 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001174 }
1175 } break;
1176 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1177 INotificationManager inm = NotificationManager.getService();
1178 if (inm == null) {
1179 return;
1180 }
1181 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001182 inm.cancelNotificationWithTag("android", null,
1183 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001184 } catch (RuntimeException e) {
1185 Slog.w(ActivityManagerService.TAG,
1186 "Error canceling notification for service", e);
1187 } catch (RemoteException e) {
1188 }
1189 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001190 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1191 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001192 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001193 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001194 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1195 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001196 }
1197 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001198 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1199 synchronized (ActivityManagerService.this) {
1200 ActivityRecord ar = (ActivityRecord)msg.obj;
1201 if (mCompatModeDialog != null) {
1202 if (mCompatModeDialog.mAppInfo.packageName.equals(
1203 ar.info.applicationInfo.packageName)) {
1204 return;
1205 }
1206 mCompatModeDialog.dismiss();
1207 mCompatModeDialog = null;
1208 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001209 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001210 if (mCompatModePackages.getPackageAskCompatModeLocked(
1211 ar.packageName)) {
1212 int mode = mCompatModePackages.computeCompatModeLocked(
1213 ar.info.applicationInfo);
1214 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1215 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1216 mCompatModeDialog = new CompatModeDialog(
1217 ActivityManagerService.this, mContext,
1218 ar.info.applicationInfo);
1219 mCompatModeDialog.show();
1220 }
1221 }
1222 }
1223 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001224 break;
1225 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001226 case DISPATCH_PROCESSES_CHANGED: {
1227 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001228 break;
1229 }
1230 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001231 final int pid = msg.arg1;
1232 final int uid = msg.arg2;
1233 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001234 break;
1235 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001236 case REPORT_MEM_USAGE: {
1237 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1238 if (!isDebuggable) {
1239 return;
1240 }
1241 synchronized (ActivityManagerService.this) {
1242 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001243 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1244 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 // avoid spamming.
1246 return;
1247 }
1248 mLastMemUsageReportTime = now;
1249 }
1250 Thread thread = new Thread() {
1251 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001252 StringBuilder dropBuilder = new StringBuilder(1024);
1253 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001254 StringWriter oomSw = new StringWriter();
1255 PrintWriter oomPw = new PrintWriter(oomSw);
1256 StringWriter catSw = new StringWriter();
1257 PrintWriter catPw = new PrintWriter(catSw);
1258 String[] emptyArgs = new String[] { };
1259 StringBuilder tag = new StringBuilder(128);
1260 StringBuilder stack = new StringBuilder(128);
1261 tag.append("Low on memory -- ");
1262 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1263 tag, stack);
1264 dropBuilder.append(stack);
1265 dropBuilder.append('\n');
1266 dropBuilder.append('\n');
1267 String oomString = oomSw.toString();
1268 dropBuilder.append(oomString);
1269 dropBuilder.append('\n');
1270 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001271 try {
1272 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1273 "procrank", });
1274 final InputStreamReader converter = new InputStreamReader(
1275 proc.getInputStream());
1276 BufferedReader in = new BufferedReader(converter);
1277 String line;
1278 while (true) {
1279 line = in.readLine();
1280 if (line == null) {
1281 break;
1282 }
1283 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001284 logBuilder.append(line);
1285 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001286 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001287 dropBuilder.append(line);
1288 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001289 }
1290 converter.close();
1291 } catch (IOException e) {
1292 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001293 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001294 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001295 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001296 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001297 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1298 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001299 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001300 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001301 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001302 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001303 addErrorToDropBox("lowmem", null, "system_server", null,
1304 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001305 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001306 synchronized (ActivityManagerService.this) {
1307 long now = SystemClock.uptimeMillis();
1308 if (mLastMemUsageReportTime < now) {
1309 mLastMemUsageReportTime = now;
1310 }
1311 }
1312 }
1313 };
1314 thread.start();
1315 break;
1316 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001317 case REPORT_USER_SWITCH_MSG: {
1318 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1319 break;
1320 }
1321 case CONTINUE_USER_SWITCH_MSG: {
1322 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1323 break;
1324 }
1325 case USER_SWITCH_TIMEOUT_MSG: {
1326 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1327 break;
1328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330 }
1331 };
1332
1333 public static void setSystemProcess() {
1334 try {
1335 ActivityManagerService m = mSelf;
1336
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001337 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001339 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001340 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 if (MONITOR_CPU_USAGE) {
1342 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 ServiceManager.addService("permission", new PermissionController(m));
1345
1346 ApplicationInfo info =
1347 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001348 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001349 mSystemThread.installSystemApplicationInfo(info);
1350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 synchronized (mSelf) {
1352 ProcessRecord app = mSelf.newProcessRecordLocked(
1353 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001354 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001356 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001357 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001358 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 synchronized (mSelf.mPidsSelfLocked) {
1360 mSelf.mPidsSelfLocked.put(app.pid, app);
1361 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001362 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
1364 } catch (PackageManager.NameNotFoundException e) {
1365 throw new RuntimeException(
1366 "Unable to find android system package", e);
1367 }
1368 }
1369
1370 public void setWindowManager(WindowManagerService wm) {
1371 mWindowManager = wm;
1372 }
1373
1374 public static final Context main(int factoryTest) {
1375 AThread thr = new AThread();
1376 thr.start();
1377
1378 synchronized (thr) {
1379 while (thr.mService == null) {
1380 try {
1381 thr.wait();
1382 } catch (InterruptedException e) {
1383 }
1384 }
1385 }
1386
1387 ActivityManagerService m = thr.mService;
1388 mSelf = m;
1389 ActivityThread at = ActivityThread.systemMain();
1390 mSystemThread = at;
1391 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001392 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 m.mContext = context;
1394 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001395 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396
1397 m.mBatteryStatsService.publish(context);
1398 m.mUsageStatsService.publish(context);
1399
1400 synchronized (thr) {
1401 thr.mReady = true;
1402 thr.notifyAll();
1403 }
1404
1405 m.startRunning(null, null, null, null);
1406
1407 return context;
1408 }
1409
1410 public static ActivityManagerService self() {
1411 return mSelf;
1412 }
1413
1414 static class AThread extends Thread {
1415 ActivityManagerService mService;
1416 boolean mReady = false;
1417
1418 public AThread() {
1419 super("ActivityManager");
1420 }
1421
1422 public void run() {
1423 Looper.prepare();
1424
1425 android.os.Process.setThreadPriority(
1426 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001427 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428
1429 ActivityManagerService m = new ActivityManagerService();
1430
1431 synchronized (this) {
1432 mService = m;
1433 notifyAll();
1434 }
1435
1436 synchronized (this) {
1437 while (!mReady) {
1438 try {
1439 wait();
1440 } catch (InterruptedException e) {
1441 }
1442 }
1443 }
1444
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001445 // For debug builds, log event loop stalls to dropbox for analysis.
1446 if (StrictMode.conditionallyEnableDebugLogging()) {
1447 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1448 }
1449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 Looper.loop();
1451 }
1452 }
1453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 static class MemBinder extends Binder {
1455 ActivityManagerService mActivityManagerService;
1456 MemBinder(ActivityManagerService activityManagerService) {
1457 mActivityManagerService = activityManagerService;
1458 }
1459
1460 @Override
1461 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001462 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1463 != PackageManager.PERMISSION_GRANTED) {
1464 pw.println("Permission Denial: can't dump meminfo from from pid="
1465 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1466 + " without permission " + android.Manifest.permission.DUMP);
1467 return;
1468 }
1469
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001470 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001471 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
1473 }
1474
Chet Haase9c1e23b2011-03-24 10:51:31 -07001475 static class GraphicsBinder extends Binder {
1476 ActivityManagerService mActivityManagerService;
1477 GraphicsBinder(ActivityManagerService activityManagerService) {
1478 mActivityManagerService = activityManagerService;
1479 }
1480
1481 @Override
1482 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001483 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1484 != PackageManager.PERMISSION_GRANTED) {
1485 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1486 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1487 + " without permission " + android.Manifest.permission.DUMP);
1488 return;
1489 }
1490
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001491 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001492 }
1493 }
1494
Jeff Brown6754ba22011-12-14 20:20:01 -08001495 static class DbBinder extends Binder {
1496 ActivityManagerService mActivityManagerService;
1497 DbBinder(ActivityManagerService activityManagerService) {
1498 mActivityManagerService = activityManagerService;
1499 }
1500
1501 @Override
1502 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1503 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1504 != PackageManager.PERMISSION_GRANTED) {
1505 pw.println("Permission Denial: can't dump dbinfo from from pid="
1506 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1507 + " without permission " + android.Manifest.permission.DUMP);
1508 return;
1509 }
1510
1511 mActivityManagerService.dumpDbInfo(fd, pw, args);
1512 }
1513 }
1514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 static class CpuBinder extends Binder {
1516 ActivityManagerService mActivityManagerService;
1517 CpuBinder(ActivityManagerService activityManagerService) {
1518 mActivityManagerService = activityManagerService;
1519 }
1520
1521 @Override
1522 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001523 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1524 != PackageManager.PERMISSION_GRANTED) {
1525 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1526 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1527 + " without permission " + android.Manifest.permission.DUMP);
1528 return;
1529 }
1530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001532 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1533 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1534 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
1536 }
1537 }
1538
1539 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001540 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001541
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001542 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1543 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1544 mBroadcastQueues[0] = mFgBroadcastQueue;
1545 mBroadcastQueues[1] = mBgBroadcastQueue;
1546
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001547 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001548 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 File dataDir = Environment.getDataDirectory();
1551 File systemDir = new File(dataDir, "system");
1552 systemDir.mkdirs();
1553 mBatteryStatsService = new BatteryStatsService(new File(
1554 systemDir, "batterystats.bin").toString());
1555 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001556 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001557 mOnBattery = DEBUG_POWER ? true
1558 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001559 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001561 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001562 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001563 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001565 // User 0 is the first and only user that runs at boot.
1566 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001567 mUserLru.add(Integer.valueOf(0));
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001568
Jack Palevichb90d28c2009-07-22 15:35:24 -07001569 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1570 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1571
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001572 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001573 mConfiguration.setLocale(Locale.getDefault());
1574
Dianne Hackborn813075a62011-11-14 17:45:19 -08001575 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 mProcessStats.init();
1577
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001578 mCompatModePackages = new CompatModePackages(this, systemDir);
1579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 // Add ourself to the Watchdog monitors.
1581 Watchdog.getInstance().addMonitor(this);
1582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 mProcessStatsThread = new Thread("ProcessStats") {
1584 public void run() {
1585 while (true) {
1586 try {
1587 try {
1588 synchronized(this) {
1589 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001590 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001592 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 // + ", write delay=" + nextWriteDelay);
1594 if (nextWriteDelay < nextCpuDelay) {
1595 nextCpuDelay = nextWriteDelay;
1596 }
1597 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001598 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 this.wait(nextCpuDelay);
1600 }
1601 }
1602 } catch (InterruptedException e) {
1603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 updateCpuStatsNow();
1605 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001606 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608 }
1609 }
1610 };
1611 mProcessStatsThread.start();
1612 }
1613
1614 @Override
1615 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1616 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001617 if (code == SYSPROPS_TRANSACTION) {
1618 // We need to tell all apps about the system property change.
1619 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1620 synchronized(this) {
1621 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1622 final int NA = apps.size();
1623 for (int ia=0; ia<NA; ia++) {
1624 ProcessRecord app = apps.valueAt(ia);
1625 if (app.thread != null) {
1626 procs.add(app.thread.asBinder());
1627 }
1628 }
1629 }
1630 }
1631
1632 int N = procs.size();
1633 for (int i=0; i<N; i++) {
1634 Parcel data2 = Parcel.obtain();
1635 try {
1636 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1637 } catch (RemoteException e) {
1638 }
1639 data2.recycle();
1640 }
1641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 try {
1643 return super.onTransact(code, data, reply, flags);
1644 } catch (RuntimeException e) {
1645 // The activity manager only throws security exceptions, so let's
1646 // log all others.
1647 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001648 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 throw e;
1651 }
1652 }
1653
1654 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001655 final long now = SystemClock.uptimeMillis();
1656 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1657 return;
1658 }
1659 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1660 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 mProcessStatsThread.notify();
1662 }
1663 }
1664 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 void updateCpuStatsNow() {
1667 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001668 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 final long now = SystemClock.uptimeMillis();
1670 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001673 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1674 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 haveNewCpuStats = true;
1676 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001677 //Slog.i(TAG, mProcessStats.printCurrentState());
1678 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 // + mProcessStats.getTotalCpuPercent() + "%");
1680
Joe Onorato8a9b2202010-02-26 18:56:32 -08001681 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if ("true".equals(SystemProperties.get("events.cpu"))) {
1683 int user = mProcessStats.getLastUserTime();
1684 int system = mProcessStats.getLastSystemTime();
1685 int iowait = mProcessStats.getLastIoWaitTime();
1686 int irq = mProcessStats.getLastIrqTime();
1687 int softIrq = mProcessStats.getLastSoftIrqTime();
1688 int idle = mProcessStats.getLastIdleTime();
1689
1690 int total = user + system + iowait + irq + softIrq + idle;
1691 if (total == 0) total = 1;
1692
Doug Zongker2bec3d42009-12-04 12:52:44 -08001693 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 ((user+system+iowait+irq+softIrq) * 100) / total,
1695 (user * 100) / total,
1696 (system * 100) / total,
1697 (iowait * 100) / total,
1698 (irq * 100) / total,
1699 (softIrq * 100) / total);
1700 }
1701 }
1702
Amith Yamasanie43530a2009-08-21 13:11:37 -07001703 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001704 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001705 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 synchronized(mPidsSelfLocked) {
1707 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001708 if (mOnBattery) {
1709 int perc = bstats.startAddingCpuLocked();
1710 int totalUTime = 0;
1711 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001712 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001714 ProcessStats.Stats st = mProcessStats.getStats(i);
1715 if (!st.working) {
1716 continue;
1717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001719 int otherUTime = (st.rel_utime*perc)/100;
1720 int otherSTime = (st.rel_stime*perc)/100;
1721 totalUTime += otherUTime;
1722 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 if (pr != null) {
1724 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001725 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1726 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001727 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001728 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001729 } else {
1730 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001731 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001732 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001733 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1734 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001735 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001739 bstats.finishAddingCpuLocked(perc, totalUTime,
1740 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
1742 }
1743 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1746 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001747 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
1749 }
1750 }
1751 }
1752
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001753 @Override
1754 public void batteryNeedsCpuUpdate() {
1755 updateCpuStatsNow();
1756 }
1757
1758 @Override
1759 public void batteryPowerChanged(boolean onBattery) {
1760 // When plugging in, update the CPU stats first before changing
1761 // the plug state.
1762 updateCpuStatsNow();
1763 synchronized (this) {
1764 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001765 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001766 }
1767 }
1768 }
1769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 /**
1771 * Initialize the application bind args. These are passed to each
1772 * process when the bindApplication() IPC is sent to the process. They're
1773 * lazily setup to make sure the services are running when they're asked for.
1774 */
1775 private HashMap<String, IBinder> getCommonServicesLocked() {
1776 if (mAppBindArgs == null) {
1777 mAppBindArgs = new HashMap<String, IBinder>();
1778
1779 // Setup the application init args
1780 mAppBindArgs.put("package", ServiceManager.getService("package"));
1781 mAppBindArgs.put("window", ServiceManager.getService("window"));
1782 mAppBindArgs.put(Context.ALARM_SERVICE,
1783 ServiceManager.getService(Context.ALARM_SERVICE));
1784 }
1785 return mAppBindArgs;
1786 }
1787
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 if (mFocusedActivity != r) {
1790 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001791 if (r != null) {
1792 mWindowManager.setFocusedApp(r.appToken, true);
1793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
1795 }
1796
Dianne Hackborn906497c2010-05-10 15:57:38 -07001797 private final void updateLruProcessInternalLocked(ProcessRecord app,
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001798 boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001800 int lrui = mLruProcesses.indexOf(app);
1801 if (lrui >= 0) mLruProcesses.remove(lrui);
1802
1803 int i = mLruProcesses.size()-1;
1804 int skipTop = 0;
1805
Dianne Hackborn906497c2010-05-10 15:57:38 -07001806 app.lruSeq = mLruSeq;
1807
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001808 // compute the new weight for this process.
1809 if (updateActivityTime) {
1810 app.lastActivityTime = SystemClock.uptimeMillis();
1811 }
1812 if (app.activities.size() > 0) {
1813 // If this process has activities, we more strongly want to keep
1814 // it around.
1815 app.lruWeight = app.lastActivityTime;
1816 } else if (app.pubProviders.size() > 0) {
1817 // If this process contains content providers, we want to keep
1818 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001819 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001820 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001821 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001822 } else {
1823 // If this process doesn't have activities, we less strongly
1824 // want to keep it around, and generally want to avoid getting
1825 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001826 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001827 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001828 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001829 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001830
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001831 while (i >= 0) {
1832 ProcessRecord p = mLruProcesses.get(i);
1833 // If this app shouldn't be in front of the first N background
1834 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001835 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001836 skipTop--;
1837 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001838 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001839 mLruProcesses.add(i+1, app);
1840 break;
1841 }
1842 i--;
1843 }
1844 if (i < 0) {
1845 mLruProcesses.add(0, app);
1846 }
1847
Dianne Hackborn906497c2010-05-10 15:57:38 -07001848 // If the app is currently using a content provider or service,
1849 // bump those processes as well.
1850 if (app.connections.size() > 0) {
1851 for (ConnectionRecord cr : app.connections) {
1852 if (cr.binding != null && cr.binding.service != null
1853 && cr.binding.service.app != null
1854 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001855 updateLruProcessInternalLocked(cr.binding.service.app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001856 updateActivityTime, i+1);
1857 }
1858 }
1859 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001860 for (int j=app.conProviders.size()-1; j>=0; j--) {
1861 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1862 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001863 updateLruProcessInternalLocked(cpr.proc,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001864 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001865 }
1866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001869 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001870 boolean oomAdj, boolean updateActivityTime) {
1871 mLruSeq++;
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001872 updateLruProcessInternalLocked(app, updateActivityTime, 0);
1873
1874 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1875 if (oomAdj) {
1876 updateOomAdjLocked();
1877 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001878 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001879
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001880 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001882 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001883 // The system gets to run in any process. If there are multiple
1884 // processes with the same uid, just pick the first (this
1885 // should never happen).
1886 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1887 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001888 if (procs == null) return null;
1889 final int N = procs.size();
1890 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001891 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 ProcessRecord proc = mProcessNames.get(processName, uid);
1895 return proc;
1896 }
1897
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001898 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001899 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001900 try {
1901 if (pm.performDexOpt(packageName)) {
1902 mDidDexOpt = true;
1903 }
1904 } catch (RemoteException e) {
1905 }
1906 }
1907
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001908 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 int transit = mWindowManager.getPendingAppTransition();
1910 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1911 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1912 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1913 }
1914
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001915 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001917 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1918 boolean isolated) {
1919 ProcessRecord app;
1920 if (!isolated) {
1921 app = getProcessRecordLocked(processName, info.uid);
1922 } else {
1923 // If this is an isolated process, it can't re-use an existing process.
1924 app = null;
1925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 // We don't have to do anything more if:
1927 // (1) There is an existing application record; and
1928 // (2) The caller doesn't think it is dead, OR there is no thread
1929 // object attached to it so we know it couldn't have crashed; and
1930 // (3) There is a pid assigned to it, so it is either starting or
1931 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001932 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 + " app=" + app + " knownToBeDead=" + knownToBeDead
1934 + " thread=" + (app != null ? app.thread : null)
1935 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001936 if (app != null && app.pid > 0) {
1937 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001938 // We already have the app running, or are waiting for it to
1939 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001940 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001941 // If this is a new package in the process, add the package to the list
1942 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001943 return app;
1944 } else {
1945 // An application record is attached to a previous process,
1946 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001947 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001948 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 String hostingNameStr = hostingName != null
1953 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001954
1955 if (!isolated) {
1956 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1957 // If we are in the background, then check to see if this process
1958 // is bad. If so, we will just silently fail.
1959 if (mBadProcesses.get(info.processName, info.uid) != null) {
1960 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1961 + "/" + info.processName);
1962 return null;
1963 }
1964 } else {
1965 // When the user is explicitly starting a process, then clear its
1966 // crash count so that we won't make it bad until they see at
1967 // least one crash dialog again, and make the process good again
1968 // if it had been bad.
1969 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001970 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001971 mProcessCrashTimes.remove(info.processName, info.uid);
1972 if (mBadProcesses.get(info.processName, info.uid) != null) {
1973 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1974 info.processName);
1975 mBadProcesses.remove(info.processName, info.uid);
1976 if (app != null) {
1977 app.bad = false;
1978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
1980 }
1981 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001984 app = newProcessRecordLocked(null, info, processName, isolated);
1985 if (app == null) {
1986 Slog.w(TAG, "Failed making new process record for "
1987 + processName + "/" + info.uid + " isolated=" + isolated);
1988 return null;
1989 }
1990 mProcessNames.put(processName, app.uid, app);
1991 if (isolated) {
1992 mIsolatedProcesses.put(app.uid, app);
1993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 } else {
1995 // If this is a new package in the process, add the package to the list
1996 app.addPackage(info.packageName);
1997 }
1998
1999 // If the system is not ready yet, then hold off on starting this
2000 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002001 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002002 && !isAllowedWhileBooting(info)
2003 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 if (!mProcessesOnHold.contains(app)) {
2005 mProcessesOnHold.add(app);
2006 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002007 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 return app;
2009 }
2010
2011 startProcessLocked(app, hostingType, hostingNameStr);
2012 return (app.pid != 0) ? app : null;
2013 }
2014
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002015 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2016 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2017 }
2018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 private final void startProcessLocked(ProcessRecord app,
2020 String hostingType, String hostingNameStr) {
2021 if (app.pid > 0 && app.pid != MY_PID) {
2022 synchronized (mPidsSelfLocked) {
2023 mPidsSelfLocked.remove(app.pid);
2024 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2025 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002026 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002029 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2030 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 mProcessesOnHold.remove(app);
2032
2033 updateCpuStats();
2034
2035 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2036 mProcDeaths[0] = 0;
2037
2038 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002039 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002042 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002043 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002044 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002045 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002046 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002047 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002048
2049 if (Environment.isExternalStorageEmulated()) {
2050 if (pm.checkPermission(
2051 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2052 app.info.packageName) == PERMISSION_GRANTED) {
2053 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2054 } else {
2055 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2056 }
2057 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002058 } catch (PackageManager.NameNotFoundException e) {
2059 Slog.w(TAG, "Unable to retrieve gids", e);
2060 }
Kenny Roote091f222012-09-11 15:01:26 -07002061
2062 /*
2063 * Add shared application GID so applications can share some
2064 * resources like shared libraries
2065 */
2066 if (permGids == null) {
2067 gids = new int[1];
2068 } else {
2069 gids = new int[permGids.length + 1];
2070 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2071 }
2072 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
2074 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2075 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2076 && mTopComponent != null
2077 && app.processName.equals(mTopComponent.getPackageName())) {
2078 uid = 0;
2079 }
2080 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2081 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2082 uid = 0;
2083 }
2084 }
2085 int debugFlags = 0;
2086 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2087 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002088 // Also turn on CheckJNI for debuggable apps. It's quite
2089 // awkward to turn on otherwise.
2090 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002092 // Run the app in safe mode if its manifest requests so or the
2093 // system is booted in safe mode.
2094 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2095 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002096 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2099 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2100 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002101 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2102 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 if ("1".equals(SystemProperties.get("debug.assert"))) {
2105 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2106 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002107
2108 // Start the process. It will either succeed and return a result containing
2109 // the PID of the new process, or else throw a RuntimeException.
2110 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002111 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002112 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2115 synchronized (bs) {
2116 if (bs.isOnBattery()) {
2117 app.batteryStats.incStartsLocked();
2118 }
2119 }
2120
Jeff Brown3f9dd282011-07-08 20:02:19 -07002121 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 app.processName, hostingType,
2123 hostingNameStr != null ? hostingNameStr : "");
2124
2125 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002126 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
2128
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002129 StringBuilder buf = mStringBuilder;
2130 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 buf.append("Start proc ");
2132 buf.append(app.processName);
2133 buf.append(" for ");
2134 buf.append(hostingType);
2135 if (hostingNameStr != null) {
2136 buf.append(" ");
2137 buf.append(hostingNameStr);
2138 }
2139 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002140 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 buf.append(" uid=");
2142 buf.append(uid);
2143 buf.append(" gids={");
2144 if (gids != null) {
2145 for (int gi=0; gi<gids.length; gi++) {
2146 if (gi != 0) buf.append(", ");
2147 buf.append(gids[gi]);
2148
2149 }
2150 }
2151 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002152 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002153 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002154 app.usingWrapper = startResult.usingWrapper;
2155 app.removed = false;
2156 synchronized (mPidsSelfLocked) {
2157 this.mPidsSelfLocked.put(startResult.pid, app);
2158 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2159 msg.obj = app;
2160 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2161 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163 } catch (RuntimeException e) {
2164 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002165 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002166 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
2168 }
2169
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002170 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 if (resumed) {
2172 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2173 } else {
2174 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2175 }
2176 }
2177
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002178 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002179 if (mHeadless) {
2180 // Added because none of the other calls to ensureBootCompleted seem to fire
2181 // when running headless.
2182 ensureBootCompleted();
2183 return false;
2184 }
2185
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002186 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2187 && mTopAction == null) {
2188 // We are running in factory test mode, but unable to find
2189 // the factory test app, so just sit around displaying the
2190 // error message and don't try to start anything.
2191 return false;
2192 }
2193 Intent intent = new Intent(
2194 mTopAction,
2195 mTopData != null ? Uri.parse(mTopData) : null);
2196 intent.setComponent(mTopComponent);
2197 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2198 intent.addCategory(Intent.CATEGORY_HOME);
2199 }
2200 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002201 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002202 if (aInfo != null) {
2203 intent.setComponent(new ComponentName(
2204 aInfo.applicationInfo.packageName, aInfo.name));
2205 // Don't do this if the home app is currently being
2206 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002207 aInfo = new ActivityInfo(aInfo);
2208 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002209 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2210 aInfo.applicationInfo.uid);
2211 if (app == null || app.instrumentationClass == null) {
2212 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002213 mMainStack.startActivityLocked(null, intent, null, aInfo,
2214 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002215 }
2216 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002217
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002218 return true;
2219 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002220
Amith Yamasani259d5e52012-08-31 15:11:01 -07002221 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2222 ActivityInfo ai = null;
2223 ComponentName comp = intent.getComponent();
2224 try {
2225 if (comp != null) {
2226 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2227 } else {
2228 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2229 intent,
2230 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2231 flags, userId);
2232
2233 if (info != null) {
2234 ai = info.activityInfo;
2235 }
2236 }
2237 } catch (RemoteException e) {
2238 // ignore
2239 }
2240
2241 return ai;
2242 }
2243
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002244 /**
2245 * Starts the "new version setup screen" if appropriate.
2246 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002247 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002248 // Only do this once per boot.
2249 if (mCheckedForSetup) {
2250 return;
2251 }
2252
2253 // We will show this screen if the current one is a different
2254 // version than the last one shown, and we are not running in
2255 // low-level factory test mode.
2256 final ContentResolver resolver = mContext.getContentResolver();
2257 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2258 Settings.Secure.getInt(resolver,
2259 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2260 mCheckedForSetup = true;
2261
2262 // See if we should be showing the platform update setup UI.
2263 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2264 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2265 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2266
2267 // We don't allow third party apps to replace this.
2268 ResolveInfo ri = null;
2269 for (int i=0; ris != null && i<ris.size(); i++) {
2270 if ((ris.get(i).activityInfo.applicationInfo.flags
2271 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2272 ri = ris.get(i);
2273 break;
2274 }
2275 }
2276
2277 if (ri != null) {
2278 String vers = ri.activityInfo.metaData != null
2279 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2280 : null;
2281 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2282 vers = ri.activityInfo.applicationInfo.metaData.getString(
2283 Intent.METADATA_SETUP_VERSION);
2284 }
2285 String lastVers = Settings.Secure.getString(
2286 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2287 if (vers != null && !vers.equals(lastVers)) {
2288 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2289 intent.setComponent(new ComponentName(
2290 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002291 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2292 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002293 }
2294 }
2295 }
2296 }
2297
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002298 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002299 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002300 }
2301
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002302 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002303 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002304 throw new SecurityException("Isolated process not allowed to call " + caller);
2305 }
2306 }
2307
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002308 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002309 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002310 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002311 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2312 }
2313 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002314
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002315 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002316 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2317 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002318 synchronized (this) {
2319 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2320 }
2321 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002322
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002323 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002324 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002325 synchronized (this) {
2326 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2327 }
2328 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002329
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002330 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002331 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2332 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002333 synchronized (this) {
2334 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002335 }
2336 }
2337
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002338 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002339 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002340 synchronized (this) {
2341 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2342 }
2343 }
2344
2345 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002346 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2347 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002348 synchronized (this) {
2349 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2350 }
2351 }
2352
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002353 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002354 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002355 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002358 private void dispatchProcessesChanged() {
2359 int N;
2360 synchronized (this) {
2361 N = mPendingProcessChanges.size();
2362 if (mActiveProcessChanges.length < N) {
2363 mActiveProcessChanges = new ProcessChangeItem[N];
2364 }
2365 mPendingProcessChanges.toArray(mActiveProcessChanges);
2366 mAvailProcessChanges.addAll(mPendingProcessChanges);
2367 mPendingProcessChanges.clear();
2368 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2369 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002370 int i = mProcessObservers.beginBroadcast();
2371 while (i > 0) {
2372 i--;
2373 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2374 if (observer != null) {
2375 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002376 for (int j=0; j<N; j++) {
2377 ProcessChangeItem item = mActiveProcessChanges[j];
2378 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2379 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2380 + item.pid + " uid=" + item.uid + ": "
2381 + item.foregroundActivities);
2382 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2383 item.foregroundActivities);
2384 }
2385 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2386 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2387 + item.pid + " uid=" + item.uid + ": " + item.importance);
2388 observer.onImportanceChanged(item.pid, item.uid,
2389 item.importance);
2390 }
2391 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002392 } catch (RemoteException e) {
2393 }
2394 }
2395 }
2396 mProcessObservers.finishBroadcast();
2397 }
2398
2399 private void dispatchProcessDied(int pid, int uid) {
2400 int i = mProcessObservers.beginBroadcast();
2401 while (i > 0) {
2402 i--;
2403 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2404 if (observer != null) {
2405 try {
2406 observer.onProcessDied(pid, uid);
2407 } catch (RemoteException e) {
2408 }
2409 }
2410 }
2411 mProcessObservers.finishBroadcast();
2412 }
2413
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002414 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002415 final int N = mPendingActivityLaunches.size();
2416 if (N <= 0) {
2417 return;
2418 }
2419 for (int i=0; i<N; i++) {
2420 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002421 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002422 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002423 }
2424 mPendingActivityLaunches.clear();
2425 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002426
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002427 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002428 Intent intent, String resolvedType, IBinder resultTo,
2429 String resultWho, int requestCode, int startFlags,
2430 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002431 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002432 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002433 }
2434
2435 public final int startActivityAsUser(IApplicationThread caller,
2436 Intent intent, String resolvedType, IBinder resultTo,
2437 String resultWho, int requestCode, int startFlags,
2438 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002439 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornd8883992012-09-07 15:58:52 -07002440 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2441 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002442 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002443 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2444 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002445 }
2446
2447 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002448 Intent intent, String resolvedType, IBinder resultTo,
2449 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002450 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002451 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002452 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2453 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002454 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002455 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002457 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002458 return res;
2459 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002460
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002461 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002462 Intent intent, String resolvedType, IBinder resultTo,
2463 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002464 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002465 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002466 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2467 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002468 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002469 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002470 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002471 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002472 }
2473
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002474 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002475 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002476 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002478 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002479 // Refuse possible leaked file descriptors
2480 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2481 throw new IllegalArgumentException("File descriptors passed in Intent");
2482 }
2483
2484 IIntentSender sender = intent.getTarget();
2485 if (!(sender instanceof PendingIntentRecord)) {
2486 throw new IllegalArgumentException("Bad PendingIntent object");
2487 }
2488
2489 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002490
2491 synchronized (this) {
2492 // If this is coming from the currently resumed activity, it is
2493 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002494 if (mMainStack.mResumedActivity != null
2495 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002496 Binder.getCallingUid()) {
2497 mAppSwitchesAllowedTime = 0;
2498 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002499 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002500 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2501 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002502 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002503 }
2504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002506 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 // Refuse possible leaked file descriptors
2508 if (intent != null && intent.hasFileDescriptors() == true) {
2509 throw new IllegalArgumentException("File descriptors passed in Intent");
2510 }
2511
2512 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002513 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2514 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002515 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 return false;
2517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 if (r.app == null || r.app.thread == null) {
2519 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002520 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 return false;
2522 }
2523 intent = new Intent(intent);
2524 // The caller is not allowed to change the data.
2525 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2526 // And we are resetting to find the next component...
2527 intent.setComponent(null);
2528
2529 ActivityInfo aInfo = null;
2530 try {
2531 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002532 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002534 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002535 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536
2537 // Look for the original activity in the list...
2538 final int N = resolves != null ? resolves.size() : 0;
2539 for (int i=0; i<N; i++) {
2540 ResolveInfo rInfo = resolves.get(i);
2541 if (rInfo.activityInfo.packageName.equals(r.packageName)
2542 && rInfo.activityInfo.name.equals(r.info.name)) {
2543 // We found the current one... the next matching is
2544 // after it.
2545 i++;
2546 if (i<N) {
2547 aInfo = resolves.get(i).activityInfo;
2548 }
2549 break;
2550 }
2551 }
2552 } catch (RemoteException e) {
2553 }
2554
2555 if (aInfo == null) {
2556 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002557 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 return false;
2559 }
2560
2561 intent.setComponent(new ComponentName(
2562 aInfo.applicationInfo.packageName, aInfo.name));
2563 intent.setFlags(intent.getFlags()&~(
2564 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2565 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2566 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2567 Intent.FLAG_ACTIVITY_NEW_TASK));
2568
2569 // Okay now we need to start the new activity, replacing the
2570 // currently running activity. This is a little tricky because
2571 // we want to start the new one as if the current one is finished,
2572 // but not finish the current one first so that there is no flicker.
2573 // And thus...
2574 final boolean wasFinishing = r.finishing;
2575 r.finishing = true;
2576
2577 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002578 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 final String resultWho = r.resultWho;
2580 final int requestCode = r.requestCode;
2581 r.resultTo = null;
2582 if (resultTo != null) {
2583 resultTo.removeResultsLocked(r, resultWho, requestCode);
2584 }
2585
2586 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002587 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002588 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2589 resultWho, requestCode, -1, r.launchedFromUid, 0,
2590 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 Binder.restoreCallingIdentity(origId);
2592
2593 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002594 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 return false;
2596 }
2597 return true;
2598 }
2599 }
2600
Dianne Hackborn41203752012-08-31 14:05:51 -07002601 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002603 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2604
2605 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2606 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607
Amith Yamasani742a6712011-05-04 14:49:28 -07002608 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002609 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002610 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002611 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002612 }
2613
2614 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002615 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002616 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002617 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002618 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002619 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002620 }
2621
Dianne Hackborn41203752012-08-31 14:05:51 -07002622 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002623 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002624 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002625
Dianne Hackborn41203752012-08-31 14:05:51 -07002626 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2627 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002628 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002629 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002630 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 }
2632
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002633 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002635 // Quick case: check if the top-most recent task is the same.
2636 if (N > 0 && mRecentTasks.get(0) == task) {
2637 return;
2638 }
2639 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 for (int i=0; i<N; i++) {
2641 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002642 if (task.userId == tr.userId
2643 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2644 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 mRecentTasks.remove(i);
2646 i--;
2647 N--;
2648 if (task.intent == null) {
2649 // If the new recent task we are adding is not fully
2650 // specified, then replace it with the existing recent task.
2651 task = tr;
2652 }
2653 }
2654 }
2655 if (N >= MAX_RECENT_TASKS) {
2656 mRecentTasks.remove(N-1);
2657 }
2658 mRecentTasks.add(0, task);
2659 }
2660
2661 public void setRequestedOrientation(IBinder token,
2662 int requestedOrientation) {
2663 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002664 ActivityRecord r = mMainStack.isInStackLocked(token);
2665 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 return;
2667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002669 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002671 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002672 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 if (config != null) {
2674 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002675 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002676 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678 }
2679 Binder.restoreCallingIdentity(origId);
2680 }
2681 }
2682
2683 public int getRequestedOrientation(IBinder token) {
2684 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002685 ActivityRecord r = mMainStack.isInStackLocked(token);
2686 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2688 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002689 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691 }
2692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 /**
2694 * This is the internal entry point for handling Activity.finish().
2695 *
2696 * @param token The Binder token referencing the Activity we want to finish.
2697 * @param resultCode Result code, if any, from this Activity.
2698 * @param resultData Result data (Intent), if any, from this Activity.
2699 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002700 * @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 -08002701 */
2702 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2703 // Refuse possible leaked file descriptors
2704 if (resultData != null && resultData.hasFileDescriptors() == true) {
2705 throw new IllegalArgumentException("File descriptors passed in Intent");
2706 }
2707
2708 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002709 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002711 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 if (next != null) {
2713 // ask watcher if this is allowed
2714 boolean resumeOK = true;
2715 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002716 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002718 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 }
2720
2721 if (!resumeOK) {
2722 return false;
2723 }
2724 }
2725 }
2726 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002727 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002728 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 Binder.restoreCallingIdentity(origId);
2730 return res;
2731 }
2732 }
2733
Dianne Hackborn860755f2010-06-03 18:47:52 -07002734 public final void finishHeavyWeightApp() {
2735 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2736 != PackageManager.PERMISSION_GRANTED) {
2737 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2738 + Binder.getCallingPid()
2739 + ", uid=" + Binder.getCallingUid()
2740 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2741 Slog.w(TAG, msg);
2742 throw new SecurityException(msg);
2743 }
2744
2745 synchronized(this) {
2746 if (mHeavyWeightProcess == null) {
2747 return;
2748 }
2749
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002750 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002751 mHeavyWeightProcess.activities);
2752 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002753 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002754 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002755 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002756 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002757 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002758 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002759 }
2760 }
2761 }
2762
Dianne Hackborn41203752012-08-31 14:05:51 -07002763 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2764 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002765 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002766 }
2767 }
2768
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002769 public void crashApplication(int uid, int initialPid, String packageName,
2770 String message) {
2771 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2772 != PackageManager.PERMISSION_GRANTED) {
2773 String msg = "Permission Denial: crashApplication() from pid="
2774 + Binder.getCallingPid()
2775 + ", uid=" + Binder.getCallingUid()
2776 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2777 Slog.w(TAG, msg);
2778 throw new SecurityException(msg);
2779 }
2780
2781 synchronized(this) {
2782 ProcessRecord proc = null;
2783
2784 // Figure out which process to kill. We don't trust that initialPid
2785 // still has any relation to current pids, so must scan through the
2786 // list.
2787 synchronized (mPidsSelfLocked) {
2788 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2789 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002790 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002791 continue;
2792 }
2793 if (p.pid == initialPid) {
2794 proc = p;
2795 break;
2796 }
2797 for (String str : p.pkgList) {
2798 if (str.equals(packageName)) {
2799 proc = p;
2800 }
2801 }
2802 }
2803 }
2804
2805 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002806 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002807 + " initialPid=" + initialPid
2808 + " packageName=" + packageName);
2809 return;
2810 }
2811
2812 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002813 if (proc.pid == Process.myPid()) {
2814 Log.w(TAG, "crashApplication: trying to crash self!");
2815 return;
2816 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002817 long ident = Binder.clearCallingIdentity();
2818 try {
2819 proc.thread.scheduleCrash(message);
2820 } catch (RemoteException e) {
2821 }
2822 Binder.restoreCallingIdentity(ident);
2823 }
2824 }
2825 }
2826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 public final void finishSubActivity(IBinder token, String resultWho,
2828 int requestCode) {
2829 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002831 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 Binder.restoreCallingIdentity(origId);
2833 }
2834 }
2835
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002836 public boolean finishActivityAffinity(IBinder token) {
2837 synchronized(this) {
2838 final long origId = Binder.clearCallingIdentity();
2839 boolean res = mMainStack.finishActivityAffinityLocked(token);
2840 Binder.restoreCallingIdentity(origId);
2841 return res;
2842 }
2843 }
2844
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002845 public boolean willActivityBeVisible(IBinder token) {
2846 synchronized(this) {
2847 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002848 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2849 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002850 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002851 return true;
2852 }
2853 if (r.fullscreen && !r.finishing) {
2854 return false;
2855 }
2856 }
2857 return true;
2858 }
2859 }
2860
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002861 public void overridePendingTransition(IBinder token, String packageName,
2862 int enterAnim, int exitAnim) {
2863 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002864 ActivityRecord self = mMainStack.isInStackLocked(token);
2865 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002866 return;
2867 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002868
2869 final long origId = Binder.clearCallingIdentity();
2870
2871 if (self.state == ActivityState.RESUMED
2872 || self.state == ActivityState.PAUSING) {
2873 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002874 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002875 }
2876
2877 Binder.restoreCallingIdentity(origId);
2878 }
2879 }
2880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 * Main function for removing an existing process from the activity manager
2883 * as a result of that process going away. Clears out all connections
2884 * to the process.
2885 */
2886 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002887 boolean restarting, boolean allowRestart) {
2888 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002890 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 }
2892
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002893 if (mProfileProc == app) {
2894 clearProfilerLocked();
2895 }
2896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002898 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2899 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2900 mMainStack.mPausingActivity = null;
2901 }
2902 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2903 mMainStack.mLastPausedActivity = null;
2904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905
2906 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908
2909 boolean atTop = true;
2910 boolean hasVisibleActivities = false;
2911
2912 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002913 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002914 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 TAG, "Removing app " + app + " from history with " + i + " entries");
2916 while (i > 0) {
2917 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002918 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002919 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2921 if (r.app == app) {
2922 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002923 if (ActivityStack.DEBUG_ADD_REMOVE) {
2924 RuntimeException here = new RuntimeException("here");
2925 here.fillInStackTrace();
2926 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2927 + ": haveState=" + r.haveState
2928 + " stateNotNeeded=" + r.stateNotNeeded
2929 + " finishing=" + r.finishing
2930 + " state=" + r.state, here);
2931 }
2932 if (!r.finishing) {
2933 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002934 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2935 System.identityHashCode(r),
2936 r.task.taskId, r.shortComponentName,
2937 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002938 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002939 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940
2941 } else {
2942 // We have the current state for this activity, so
2943 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002944 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 TAG, "Keeping entry, setting app to null");
2946 if (r.visible) {
2947 hasVisibleActivities = true;
2948 }
2949 r.app = null;
2950 r.nowVisible = false;
2951 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002952 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2953 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 r.icicle = null;
2955 }
2956 }
2957
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002958 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 }
2960 atTop = false;
2961 }
2962
2963 app.activities.clear();
2964
2965 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002966 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 + " running instrumentation " + app.instrumentationClass);
2968 Bundle info = new Bundle();
2969 info.putString("shortMsg", "Process crashed.");
2970 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2971 }
2972
2973 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002974 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 // If there was nothing to resume, and we are not already
2976 // restarting this process, but there is a visible activity that
2977 // is hosted by the process... then make sure all visible
2978 // activities are running, taking care of restarting this
2979 // process.
2980 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002981 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 }
2983 }
2984 }
2985 }
2986
2987 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2988 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002990 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2991 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2993 return i;
2994 }
2995 }
2996 return -1;
2997 }
2998
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002999 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 IApplicationThread thread) {
3001 if (thread == null) {
3002 return null;
3003 }
3004
3005 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003006 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 }
3008
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003009 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 IApplicationThread thread) {
3011
3012 mProcDeaths[0]++;
3013
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003014 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3015 synchronized (stats) {
3016 stats.noteProcessDiedLocked(app.info.uid, pid);
3017 }
3018
Magnus Edlund7bb25812010-02-24 15:45:06 +01003019 // Clean up already done if the process has been re-started.
3020 if (app.pid == pid && app.thread != null &&
3021 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003022 if (!app.killedBackground) {
3023 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3024 + ") has died.");
3025 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003026 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003027 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 TAG, "Dying app: " + app + ", pid: " + pid
3029 + ", thread: " + thread.asBinder());
3030 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003031 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032
3033 if (doLowMem) {
3034 // If there are no longer any background processes running,
3035 // and the app that died was not running instrumentation,
3036 // then tell everyone we are now low on memory.
3037 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003038 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3039 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003040 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 haveBg = true;
3042 break;
3043 }
3044 }
3045
3046 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003047 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003048 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003049 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3050 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003051 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003052 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3053 // The low memory report is overriding any current
3054 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003055 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003056 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003057 rec.lastRequestedGc = 0;
3058 } else {
3059 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003061 rec.reportLowMemory = true;
3062 rec.lastLowMemory = now;
3063 mProcessesToGc.remove(rec);
3064 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 }
3066 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003067 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003068 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 }
3070 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003071 } else if (app.pid != pid) {
3072 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003073 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003074 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003075 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003076 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003077 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 + thread.asBinder());
3079 }
3080 }
3081
Dan Egnor42471dd2010-01-07 17:25:22 -08003082 /**
3083 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003084 * @param clearTraces causes the dump file to be erased prior to the new
3085 * traces being written, if true; when false, the new traces will be
3086 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003087 * @param firstPids of dalvik VM processes to dump stack traces for first
3088 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003089 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003090 * @return file containing stack traces, or null if no dump file is configured
3091 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003092 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003093 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003094 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3095 if (tracesPath == null || tracesPath.length() == 0) {
3096 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003098
3099 File tracesFile = new File(tracesPath);
3100 try {
3101 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003102 if (!tracesDir.exists()) {
3103 tracesFile.mkdirs();
3104 if (!SELinux.restorecon(tracesDir)) {
3105 return null;
3106 }
3107 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003108 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3109
Christopher Tate6ee412d2010-05-28 12:01:56 -07003110 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003111 tracesFile.createNewFile();
3112 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3113 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003114 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003115 return null;
3116 }
3117
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003118 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003119 return tracesFile;
3120 }
3121
3122 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003123 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003124 // Use a FileObserver to detect when traces finish writing.
3125 // The order of traces is considered important to maintain for legibility.
3126 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3127 public synchronized void onEvent(int event, String path) { notify(); }
3128 };
3129
3130 try {
3131 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003132
3133 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003134 if (firstPids != null) {
3135 try {
3136 int num = firstPids.size();
3137 for (int i = 0; i < num; i++) {
3138 synchronized (observer) {
3139 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3140 observer.wait(200); // Wait for write-close, give up after 200msec
3141 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003142 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003143 } catch (InterruptedException e) {
3144 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003145 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003146 }
3147
3148 // Next measure CPU usage.
3149 if (processStats != null) {
3150 processStats.init();
3151 System.gc();
3152 processStats.update();
3153 try {
3154 synchronized (processStats) {
3155 processStats.wait(500); // measure over 1/2 second.
3156 }
3157 } catch (InterruptedException e) {
3158 }
3159 processStats.update();
3160
3161 // We'll take the stack crawls of just the top apps using CPU.
3162 final int N = processStats.countWorkingStats();
3163 int numProcs = 0;
3164 for (int i=0; i<N && numProcs<5; i++) {
3165 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3166 if (lastPids.indexOfKey(stats.pid) >= 0) {
3167 numProcs++;
3168 try {
3169 synchronized (observer) {
3170 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3171 observer.wait(200); // Wait for write-close, give up after 200msec
3172 }
3173 } catch (InterruptedException e) {
3174 Log.wtf(TAG, e);
3175 }
3176
3177 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003178 }
3179 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003180
Dan Egnor42471dd2010-01-07 17:25:22 -08003181 } finally {
3182 observer.stopWatching();
3183 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003184
3185 if (nativeProcs != null) {
3186 int[] pids = Process.getPidsForCommands(nativeProcs);
3187 if (pids != null) {
3188 for (int pid : pids) {
3189 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3190 }
3191 }
3192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 }
3194
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003195 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003196 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003197 return;
3198 }
3199 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3200 if (tracesPath == null || tracesPath.length() == 0) {
3201 return;
3202 }
3203
3204 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3205 StrictMode.allowThreadDiskWrites();
3206 try {
3207 final File tracesFile = new File(tracesPath);
3208 final File tracesDir = tracesFile.getParentFile();
3209 final File tracesTmp = new File(tracesDir, "__tmp__");
3210 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003211 if (!tracesDir.exists()) {
3212 tracesFile.mkdirs();
3213 if (!SELinux.restorecon(tracesDir.getPath())) {
3214 return;
3215 }
3216 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003217 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3218
3219 if (tracesFile.exists()) {
3220 tracesTmp.delete();
3221 tracesFile.renameTo(tracesTmp);
3222 }
3223 StringBuilder sb = new StringBuilder();
3224 Time tobj = new Time();
3225 tobj.set(System.currentTimeMillis());
3226 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3227 sb.append(": ");
3228 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3229 sb.append(" since ");
3230 sb.append(msg);
3231 FileOutputStream fos = new FileOutputStream(tracesFile);
3232 fos.write(sb.toString().getBytes());
3233 if (app == null) {
3234 fos.write("\n*** No application process!".getBytes());
3235 }
3236 fos.close();
3237 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3238 } catch (IOException e) {
3239 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3240 return;
3241 }
3242
3243 if (app != null) {
3244 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3245 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003246 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003247 }
3248
3249 File lastTracesFile = null;
3250 File curTracesFile = null;
3251 for (int i=9; i>=0; i--) {
3252 String name = String.format("slow%02d.txt", i);
3253 curTracesFile = new File(tracesDir, name);
3254 if (curTracesFile.exists()) {
3255 if (lastTracesFile != null) {
3256 curTracesFile.renameTo(lastTracesFile);
3257 } else {
3258 curTracesFile.delete();
3259 }
3260 }
3261 lastTracesFile = curTracesFile;
3262 }
3263 tracesFile.renameTo(curTracesFile);
3264 if (tracesTmp.exists()) {
3265 tracesTmp.renameTo(tracesFile);
3266 }
3267 } finally {
3268 StrictMode.setThreadPolicy(oldPolicy);
3269 }
3270 }
3271
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003272 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3273 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003274 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3275 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3276
Dianne Hackborn287952c2010-09-22 22:34:31 -07003277 if (mController != null) {
3278 try {
3279 // 0 == continue, -1 = kill process immediately
3280 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3281 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3282 } catch (RemoteException e) {
3283 mController = null;
3284 }
3285 }
3286
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003287 long anrTime = SystemClock.uptimeMillis();
3288 if (MONITOR_CPU_USAGE) {
3289 updateCpuStatsNow();
3290 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003291
3292 synchronized (this) {
3293 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3294 if (mShuttingDown) {
3295 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3296 return;
3297 } else if (app.notResponding) {
3298 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3299 return;
3300 } else if (app.crashing) {
3301 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3302 return;
3303 }
3304
3305 // In case we come through here for the same app before completing
3306 // this one, mark as anring now so we will bail out.
3307 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003308
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003309 // Log the ANR to the event log.
3310 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3311 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003312
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003313 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003314 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003315
3316 int parentPid = app.pid;
3317 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003318 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003319
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003320 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003321
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003322 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3323 ProcessRecord r = mLruProcesses.get(i);
3324 if (r != null && r.thread != null) {
3325 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003326 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3327 if (r.persistent) {
3328 firstPids.add(pid);
3329 } else {
3330 lastPids.put(pid, Boolean.TRUE);
3331 }
3332 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
3335 }
3336
Dan Egnor42471dd2010-01-07 17:25:22 -08003337 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003338 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003339 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003340 info.append("ANR in ").append(app.processName);
3341 if (activity != null && activity.shortComponentName != null) {
3342 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003343 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003344 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003346 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003348 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003349 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351
Dianne Hackborn287952c2010-09-22 22:34:31 -07003352 final ProcessStats processStats = new ProcessStats(true);
3353
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003354 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003355
Dan Egnor42471dd2010-01-07 17:25:22 -08003356 String cpuInfo = null;
3357 if (MONITOR_CPU_USAGE) {
3358 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003359 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003360 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003361 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003362 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003363 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 }
3365
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003366 info.append(processStats.printCurrentState(anrTime));
3367
Joe Onorato8a9b2202010-02-26 18:56:32 -08003368 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003369 if (tracesFile == null) {
3370 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3371 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3372 }
3373
Jeff Sharkeya353d262011-10-28 11:12:06 -07003374 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3375 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003376
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003377 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003379 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3380 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003382 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3383 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
3385 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003386 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
3388 }
3389
Dan Egnor42471dd2010-01-07 17:25:22 -08003390 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3391 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3392 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003393
3394 synchronized (this) {
3395 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003396 Slog.w(TAG, "Killing " + app + ": background ANR");
3397 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3398 app.processName, app.setAdj, "background ANR");
3399 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003400 return;
3401 }
3402
3403 // Set the app's notResponding state, and look up the errorReportReceiver
3404 makeAppNotRespondingLocked(app,
3405 activity != null ? activity.shortComponentName : null,
3406 annotation != null ? "ANR " + annotation : "ANR",
3407 info.toString());
3408
3409 // Bring up the infamous App Not Responding dialog
3410 Message msg = Message.obtain();
3411 HashMap map = new HashMap();
3412 msg.what = SHOW_NOT_RESPONDING_MSG;
3413 msg.obj = map;
3414 map.put("app", app);
3415 if (activity != null) {
3416 map.put("activity", activity);
3417 }
3418
3419 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
3422
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003423 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3424 if (!mLaunchWarningShown) {
3425 mLaunchWarningShown = true;
3426 mHandler.post(new Runnable() {
3427 @Override
3428 public void run() {
3429 synchronized (ActivityManagerService.this) {
3430 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3431 d.show();
3432 mHandler.postDelayed(new Runnable() {
3433 @Override
3434 public void run() {
3435 synchronized (ActivityManagerService.this) {
3436 d.dismiss();
3437 mLaunchWarningShown = false;
3438 }
3439 }
3440 }, 4000);
3441 }
3442 }
3443 });
3444 }
3445 }
3446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003448 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003449 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 int uid = Binder.getCallingUid();
3451 int pid = Binder.getCallingPid();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003452 userId = handleIncomingUserLocked(pid, uid,
3453 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 long callingId = Binder.clearCallingIdentity();
3455 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003456 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 int pkgUid = -1;
3458 synchronized(this) {
3459 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003460 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 } catch (RemoteException e) {
3462 }
3463 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003464 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 return false;
3466 }
3467 if (uid == pkgUid || checkComponentPermission(
3468 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003469 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003471 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 } else {
3473 throw new SecurityException(pid+" does not have permission:"+
3474 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3475 "for process:"+packageName);
3476 }
3477 }
3478
3479 try {
3480 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003481 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3483 Uri.fromParts("package", packageName, null));
3484 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003485 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003486 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 } catch (RemoteException e) {
3488 }
3489 } finally {
3490 Binder.restoreCallingIdentity(callingId);
3491 }
3492 return true;
3493 }
3494
Dianne Hackborn1676c852012-09-10 14:52:30 -07003495 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003496 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3497 != PackageManager.PERMISSION_GRANTED &&
3498 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3499 != PackageManager.PERMISSION_GRANTED) {
3500 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 + Binder.getCallingPid()
3502 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003503 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003504 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 throw new SecurityException(msg);
3506 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003507
3508 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3509 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 long callingId = Binder.clearCallingIdentity();
3511 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003512 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003514 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003516 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 } catch (RemoteException e) {
3518 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003519 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003520 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 return;
3522 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003523 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003524 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3525 }
3526 } finally {
3527 Binder.restoreCallingIdentity(callingId);
3528 }
3529 }
3530
3531 public void killAllBackgroundProcesses() {
3532 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3533 != PackageManager.PERMISSION_GRANTED) {
3534 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3535 + Binder.getCallingPid()
3536 + ", uid=" + Binder.getCallingUid()
3537 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3538 Slog.w(TAG, msg);
3539 throw new SecurityException(msg);
3540 }
3541
3542 long callingId = Binder.clearCallingIdentity();
3543 try {
3544 synchronized(this) {
3545 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3546 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3547 final int NA = apps.size();
3548 for (int ia=0; ia<NA; ia++) {
3549 ProcessRecord app = apps.valueAt(ia);
3550 if (app.persistent) {
3551 // we don't kill persistent processes
3552 continue;
3553 }
3554 if (app.removed) {
3555 procs.add(app);
3556 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3557 app.removed = true;
3558 procs.add(app);
3559 }
3560 }
3561 }
3562
3563 int N = procs.size();
3564 for (int i=0; i<N; i++) {
3565 removeProcessLocked(procs.get(i), false, true, "kill all background");
3566 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003567 }
3568 } finally {
3569 Binder.restoreCallingIdentity(callingId);
3570 }
3571 }
3572
Dianne Hackborn1676c852012-09-10 14:52:30 -07003573 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003574 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3575 != PackageManager.PERMISSION_GRANTED) {
3576 String msg = "Permission Denial: forceStopPackage() from pid="
3577 + Binder.getCallingPid()
3578 + ", uid=" + Binder.getCallingUid()
3579 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003580 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003581 throw new SecurityException(msg);
3582 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003583 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3584 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 long callingId = Binder.clearCallingIdentity();
3586 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003587 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003588 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003589 int[] users = userId == UserHandle.USER_ALL
3590 ? getUsersLocked() : new int[] { userId };
3591 for (int user : users) {
3592 int pkgUid = -1;
3593 try {
3594 pkgUid = pm.getPackageUid(packageName, user);
3595 } catch (RemoteException e) {
3596 }
3597 if (pkgUid == -1) {
3598 Slog.w(TAG, "Invalid packageName: " + packageName);
3599 continue;
3600 }
3601 try {
3602 pm.setPackageStoppedState(packageName, true, user);
3603 } catch (RemoteException e) {
3604 } catch (IllegalArgumentException e) {
3605 Slog.w(TAG, "Failed trying to unstop package "
3606 + packageName + ": " + e);
3607 }
3608 if (isUserRunningLocked(user)) {
3609 forceStopPackageLocked(packageName, pkgUid);
3610 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 }
3613 } finally {
3614 Binder.restoreCallingIdentity(callingId);
3615 }
3616 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003617
3618 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003619 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003620 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003621 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003622 if (pkg == null) {
3623 return;
3624 }
3625 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003626 if (appid < 0) {
3627 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003628 return;
3629 }
3630 int callerUid = Binder.getCallingUid();
3631 // Only the system server can kill an application
3632 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003633 // Post an aysnc message to kill the application
3634 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003635 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003636 msg.arg2 = 0;
3637 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003638 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003639 } else {
3640 throw new SecurityException(callerUid + " cannot kill pkg: " +
3641 pkg);
3642 }
3643 }
3644
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003645 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003646 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003647
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003648 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003649 final int uid = Binder.getCallingUid();
3650 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003651 try {
3652 synchronized (this) {
3653 // Only allow this from foreground processes, so that background
3654 // applications can't abuse it to prevent system UI from being shown.
3655 if (uid >= Process.FIRST_APPLICATION_UID) {
3656 ProcessRecord proc;
3657 synchronized (mPidsSelfLocked) {
3658 proc = mPidsSelfLocked.get(pid);
3659 }
3660 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3661 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3662 + " from background process " + proc);
3663 return;
3664 }
3665 }
3666 closeSystemDialogsLocked(reason);
3667 }
3668 } finally {
3669 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003670 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003671 }
3672
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003673 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003674 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003675 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003676 if (reason != null) {
3677 intent.putExtra("reason", reason);
3678 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003679 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003680
Dianne Hackborne302a162012-05-15 14:58:32 -07003681 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3682 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003683 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003684 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003685 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003686 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003687 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003688
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003689 broadcastIntentLocked(null, null, intent, null,
3690 null, 0, null, null, null, false, false, -1,
3691 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003692 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003693
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003694 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003695 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003696 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003697 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3698 for (int i=pids.length-1; i>=0; i--) {
3699 infos[i] = new Debug.MemoryInfo();
3700 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003701 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003702 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003703 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003704
Dianne Hackbornb437e092011-08-05 17:50:29 -07003705 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003706 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003707 long[] pss = new long[pids.length];
3708 for (int i=pids.length-1; i>=0; i--) {
3709 pss[i] = Debug.getPss(pids[i]);
3710 }
3711 return pss;
3712 }
3713
Christopher Tate5e1ab332009-09-01 20:32:49 -07003714 public void killApplicationProcess(String processName, int uid) {
3715 if (processName == null) {
3716 return;
3717 }
3718
3719 int callerUid = Binder.getCallingUid();
3720 // Only the system server can kill an application
3721 if (callerUid == Process.SYSTEM_UID) {
3722 synchronized (this) {
3723 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003724 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003725 try {
3726 app.thread.scheduleSuicide();
3727 } catch (RemoteException e) {
3728 // If the other end already died, then our work here is done.
3729 }
3730 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003731 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003732 + processName + " / " + uid);
3733 }
3734 }
3735 } else {
3736 throw new SecurityException(callerUid + " cannot kill app process: " +
3737 processName);
3738 }
3739 }
3740
Dianne Hackborn03abb812010-01-04 18:43:19 -08003741 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003742 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3743 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3745 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003746 if (!mProcessesReady) {
3747 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 intent.putExtra(Intent.EXTRA_UID, uid);
3750 broadcastIntentLocked(null, null, intent,
3751 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003752 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003753 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003755
3756 private void forceStopUserLocked(int userId) {
3757 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3758 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3759 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3760 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3761 broadcastIntentLocked(null, null, intent,
3762 null, null, 0, null, null, null,
3763 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003764 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003765 }
3766
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003767 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003768 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3769 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003770 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771
Dianne Hackborn03abb812010-01-04 18:43:19 -08003772 // Remove all processes this package may have touched: all with the
3773 // same UID (except for the system or root user), and all whose name
3774 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003775 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003776 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3777 final int NA = apps.size();
3778 for (int ia=0; ia<NA; ia++) {
3779 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003780 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003781 // we don't kill persistent processes
3782 continue;
3783 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003784 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003785 if (doit) {
3786 procs.add(app);
3787 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003788 continue;
3789 }
3790
3791 // Skip process if it doesn't meet our oom adj requirement.
3792 if (app.setAdj < minOomAdj) {
3793 continue;
3794 }
3795
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003796 // If no package is specified, we call all processes under the
3797 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003798 if (packageName == null) {
3799 if (app.userId != userId) {
3800 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003801 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003802 // Package has been specified, we want to hit all processes
3803 // that match it. We need to qualify this by the processes
3804 // that are running under the specified app and user ID.
3805 } else {
3806 if (UserHandle.getAppId(app.uid) != appId) {
3807 continue;
3808 }
3809 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3810 continue;
3811 }
3812 if (!app.pkgList.contains(packageName)) {
3813 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003814 }
3815 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003816
3817 // Process has passed all conditions, kill it!
3818 if (!doit) {
3819 return true;
3820 }
3821 app.removed = true;
3822 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003823 }
3824 }
3825
3826 int N = procs.size();
3827 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003828 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003829 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003830 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003831 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003832
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003833 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003834 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003835 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003836 int i;
3837 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003839 if (userId == UserHandle.USER_ALL && name == null) {
3840 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3841 }
3842
3843 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003845 appId = UserHandle.getAppId(
3846 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 } catch (RemoteException e) {
3848 }
3849 }
3850
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003851 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003852 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003853 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3854 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003855 } else {
3856 Slog.i(TAG, "Force stopping user " + userId);
3857 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003858
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003859 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3860 while (badApps.hasNext()) {
3861 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003862 for (i=ba.size()-1; i>=0; i--) {
3863 boolean remove = false;
3864 final int entUid = ba.keyAt(i);
3865 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003866 if (userId == UserHandle.USER_ALL) {
3867 if (UserHandle.getAppId(entUid) == appId) {
3868 remove = true;
3869 }
3870 } else {
3871 if (entUid == UserHandle.getUid(userId, appId)) {
3872 remove = true;
3873 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003874 }
3875 } else if (UserHandle.getUserId(entUid) == userId) {
3876 remove = true;
3877 }
3878 if (remove) {
3879 ba.removeAt(i);
3880 }
3881 }
3882 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003883 badApps.remove();
3884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 }
3886 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003887
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003888 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3889 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003890 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003892 TaskRecord lastTask = null;
3893 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003894 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003895 final boolean samePackage = r.packageName.equals(name)
3896 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003897 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003898 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003899 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003900 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003901 if (r.finishing) {
3902 // If this activity is just finishing, then it is not
3903 // interesting as far as something to stop.
3904 continue;
3905 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003906 return true;
3907 }
3908 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003909 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003910 if (samePackage) {
3911 if (r.app != null) {
3912 r.app.removed = true;
3913 }
3914 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003916 lastTask = r.task;
3917 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003918 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003919 i--;
3920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 }
3922 }
3923
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003924 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3925 if (!doit) {
3926 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003928 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003930
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003931 if (name == null) {
3932 // Remove all sticky broadcasts from this user.
3933 mStickyBroadcasts.remove(userId);
3934 }
3935
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003936 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003937 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3938 userId, providers)) {
3939 if (!doit) {
3940 return true;
3941 }
3942 didSomething = true;
3943 }
3944 N = providers.size();
3945 for (i=0; i<N; i++) {
3946 removeDyingProviderLocked(null, providers.get(i), true);
3947 }
3948
3949 if (mIntentSenderRecords.size() > 0) {
3950 Iterator<WeakReference<PendingIntentRecord>> it
3951 = mIntentSenderRecords.values().iterator();
3952 while (it.hasNext()) {
3953 WeakReference<PendingIntentRecord> wpir = it.next();
3954 if (wpir == null) {
3955 it.remove();
3956 continue;
3957 }
3958 PendingIntentRecord pir = wpir.get();
3959 if (pir == null) {
3960 it.remove();
3961 continue;
3962 }
3963 if (name == null) {
3964 // Stopping user, remove all objects for the user.
3965 if (pir.key.userId != userId) {
3966 // Not the same user, skip it.
3967 continue;
3968 }
3969 } else {
3970 if (UserHandle.getAppId(pir.uid) != appId) {
3971 // Different app id, skip it.
3972 continue;
3973 }
3974 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3975 // Different user, skip it.
3976 continue;
3977 }
3978 if (!pir.key.packageName.equals(name)) {
3979 // Different package, skip it.
3980 continue;
3981 }
3982 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003983 if (!doit) {
3984 return true;
3985 }
3986 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003987 it.remove();
3988 pir.canceled = true;
3989 if (pir.key.activity != null) {
3990 pir.key.activity.pendingResults.remove(pir.ref);
3991 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003992 }
3993 }
3994
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003995 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003996 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003997 AttributeCache ac = AttributeCache.instance();
3998 if (ac != null) {
3999 ac.removePackage(name);
4000 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004001 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004002 if (mBooted) {
4003 mMainStack.resumeTopActivityLocked(null);
4004 mMainStack.scheduleIdleLocked();
4005 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004006 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004007
4008 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 }
4010
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004011 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004012 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004014 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004015 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004016 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 + "/" + uid + ")");
4018
4019 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004020 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004021 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004022 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4023 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004024 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 boolean needRestart = false;
4027 if (app.pid > 0 && app.pid != MY_PID) {
4028 int pid = app.pid;
4029 synchronized (mPidsSelfLocked) {
4030 mPidsSelfLocked.remove(pid);
4031 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4032 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004033 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004034 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004035 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004036 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004038 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004040 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 } else {
4042 needRestart = true;
4043 }
4044 }
4045 } else {
4046 mRemovedProcesses.add(app);
4047 }
4048
4049 return needRestart;
4050 }
4051
4052 private final void processStartTimedOutLocked(ProcessRecord app) {
4053 final int pid = app.pid;
4054 boolean gone = false;
4055 synchronized (mPidsSelfLocked) {
4056 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4057 if (knownApp != null && knownApp.thread == null) {
4058 mPidsSelfLocked.remove(pid);
4059 gone = true;
4060 }
4061 }
4062
4063 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004064 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004065 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004066 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004067 mProcessNames.remove(app.processName, app.uid);
4068 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004069 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004070 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4071 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004072 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004073 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004074 // Take care of any launching providers waiting for this process.
4075 checkAppInLaunchingProvidersLocked(app, true);
4076 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004077 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004078 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4079 app.processName, app.setAdj, "start timeout");
4080 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004081 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004082 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004083 try {
4084 IBackupManager bm = IBackupManager.Stub.asInterface(
4085 ServiceManager.getService(Context.BACKUP_SERVICE));
4086 bm.agentDisconnected(app.info.packageName);
4087 } catch (RemoteException e) {
4088 // Can't happen; the backup manager is local
4089 }
4090 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004091 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004092 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004093 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004096 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 }
4098 }
4099
4100 private final boolean attachApplicationLocked(IApplicationThread thread,
4101 int pid) {
4102
4103 // Find the application record that is being attached... either via
4104 // the pid if we are running in multiple processes, or just pull the
4105 // next app record if we are emulating process with anonymous threads.
4106 ProcessRecord app;
4107 if (pid != MY_PID && pid >= 0) {
4108 synchronized (mPidsSelfLocked) {
4109 app = mPidsSelfLocked.get(pid);
4110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 } else {
4112 app = null;
4113 }
4114
4115 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004116 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004118 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004120 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 } else {
4122 try {
4123 thread.scheduleExit();
4124 } catch (Exception e) {
4125 // Ignore exceptions.
4126 }
4127 }
4128 return false;
4129 }
4130
4131 // If this application record is still attached to a previous
4132 // process, clean it up now.
4133 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004134 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 }
4136
4137 // Tell the process all about itself.
4138
Joe Onorato8a9b2202010-02-26 18:56:32 -08004139 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 TAG, "Binding process pid " + pid + " to record " + app);
4141
4142 String processName = app.processName;
4143 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004144 AppDeathRecipient adr = new AppDeathRecipient(
4145 app, pid, thread);
4146 thread.asBinder().linkToDeath(adr, 0);
4147 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 } catch (RemoteException e) {
4149 app.resetPackageList();
4150 startProcessLocked(app, "link fail", processName);
4151 return false;
4152 }
4153
Doug Zongker2bec3d42009-12-04 12:52:44 -08004154 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155
4156 app.thread = thread;
4157 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004158 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4159 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 app.forcingToForeground = null;
4161 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004162 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 app.debugging = false;
4164
4165 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4166
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004167 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004168 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004170 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004171 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004172 }
4173
Joe Onorato8a9b2202010-02-26 18:56:32 -08004174 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 TAG, "New app record " + app
4176 + " thread=" + thread.asBinder() + " pid=" + pid);
4177 try {
4178 int testMode = IApplicationThread.DEBUG_OFF;
4179 if (mDebugApp != null && mDebugApp.equals(processName)) {
4180 testMode = mWaitForDebugger
4181 ? IApplicationThread.DEBUG_WAIT
4182 : IApplicationThread.DEBUG_ON;
4183 app.debugging = true;
4184 if (mDebugTransient) {
4185 mDebugApp = mOrigDebugApp;
4186 mWaitForDebugger = mOrigWaitForDebugger;
4187 }
4188 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004189 String profileFile = app.instrumentationProfileFile;
4190 ParcelFileDescriptor profileFd = null;
4191 boolean profileAutoStop = false;
4192 if (mProfileApp != null && mProfileApp.equals(processName)) {
4193 mProfileProc = app;
4194 profileFile = mProfileFile;
4195 profileFd = mProfileFd;
4196 profileAutoStop = mAutoStopProfiler;
4197 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004198 boolean enableOpenGlTrace = false;
4199 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4200 enableOpenGlTrace = true;
4201 mOpenGlTraceApp = null;
4202 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004203
Christopher Tate181fafa2009-05-14 11:12:14 -07004204 // If the app is being launched for restore or full backup, set it up specially
4205 boolean isRestrictedBackupMode = false;
4206 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4207 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004208 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004209 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4210 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004211
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004212 ensurePackageDexOpt(app.instrumentationInfo != null
4213 ? app.instrumentationInfo.packageName
4214 : app.info.packageName);
4215 if (app.instrumentationClass != null) {
4216 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004217 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004218 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004219 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004220 ApplicationInfo appInfo = app.instrumentationInfo != null
4221 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004222 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004223 if (profileFd != null) {
4224 profileFd = profileFd.dup();
4225 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004226 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004227 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004228 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4229 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004230 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004231 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004232 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004233 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 } catch (Exception e) {
4235 // todo: Yikes! What should we do? For now we will try to
4236 // start another process, but that could easily get us in
4237 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004238 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239
4240 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004241 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 startProcessLocked(app, "bind fail", processName);
4243 return false;
4244 }
4245
4246 // Remove this record from the list of starting applications.
4247 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004248 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4249 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 mProcessesOnHold.remove(app);
4251
4252 boolean badApp = false;
4253 boolean didSomething = false;
4254
4255 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004256 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004257 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004258 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 && processName.equals(hr.processName)) {
4260 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004261 if (mHeadless) {
4262 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4263 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 didSomething = true;
4265 }
4266 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004267 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 + hr.intent.getComponent().flattenToShortString(), e);
4269 badApp = true;
4270 }
4271 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004272 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
4274 }
4275
4276 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004277 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004279 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 badApp = true;
4282 }
4283 }
4284
Christopher Tatef46723b2012-01-26 14:19:24 -08004285 // Check if a next-broadcast receiver is in this process...
4286 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004288 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004290 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 }
4293 }
4294
Christopher Tate181fafa2009-05-14 11:12:14 -07004295 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004296 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004297 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004298 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004299 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004300 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4301 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4302 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004303 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004304 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004305 e.printStackTrace();
4306 }
4307 }
4308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 if (badApp) {
4310 // todo: Also need to kill application to deal with all
4311 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004312 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 return false;
4314 }
4315
4316 if (!didSomething) {
4317 updateOomAdjLocked();
4318 }
4319
4320 return true;
4321 }
4322
4323 public final void attachApplication(IApplicationThread thread) {
4324 synchronized (this) {
4325 int callingPid = Binder.getCallingPid();
4326 final long origId = Binder.clearCallingIdentity();
4327 attachApplicationLocked(thread, callingPid);
4328 Binder.restoreCallingIdentity(origId);
4329 }
4330 }
4331
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004332 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004334 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4335 if (stopProfiling) {
4336 synchronized (this) {
4337 if (mProfileProc == r.app) {
4338 if (mProfileFd != null) {
4339 try {
4340 mProfileFd.close();
4341 } catch (IOException e) {
4342 }
4343 clearProfilerLocked();
4344 }
4345 }
4346 }
4347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 Binder.restoreCallingIdentity(origId);
4349 }
4350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004352 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004353 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004355
4356 synchronized (this) {
4357 updateEventDispatchingLocked();
4358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 }
4360
Dianne Hackborn661cd522011-08-22 00:26:20 -07004361 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004362 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004363 mWindowManager.showBootMessage(msg, always);
4364 }
4365
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004366 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004367 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004368 final long token = Binder.clearCallingIdentity();
4369 try {
4370 synchronized (this) {
4371 if (mLockScreenShown) {
4372 mLockScreenShown = false;
4373 comeOutOfSleepIfNeededLocked();
4374 }
4375 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004376 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004377 } finally {
4378 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004379 }
4380 }
4381
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004382 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004383 IntentFilter pkgFilter = new IntentFilter();
4384 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4385 pkgFilter.addDataScheme("package");
4386 mContext.registerReceiver(new BroadcastReceiver() {
4387 @Override
4388 public void onReceive(Context context, Intent intent) {
4389 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4390 if (pkgs != null) {
4391 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004392 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004393 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4394 setResultCode(Activity.RESULT_OK);
4395 return;
4396 }
4397 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004398 }
4399 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004400 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004401 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004402
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004403 synchronized (this) {
4404 // Ensure that any processes we had put on hold are now started
4405 // up.
4406 final int NP = mProcessesOnHold.size();
4407 if (NP > 0) {
4408 ArrayList<ProcessRecord> procs =
4409 new ArrayList<ProcessRecord>(mProcessesOnHold);
4410 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004411 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4412 + procs.get(ip));
4413 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004414 }
4415 }
4416
4417 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004418 // Start looking for apps that are abusing wake locks.
4419 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004420 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004421 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004422 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004423 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004424 for (int i=0; i<mStartedUsers.size(); i++) {
4425 UserStartedState uss = mStartedUsers.valueAt(i);
4426 if (uss.mState == UserStartedState.STATE_BOOTING) {
4427 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004428 final int userId = mStartedUsers.keyAt(i);
4429 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4430 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4431 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004432 null, null, 0, null, null,
4433 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004434 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004435 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004436 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004437 }
4438 }
4439 }
4440
4441 final void ensureBootCompleted() {
4442 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004443 boolean enableScreen;
4444 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004445 booting = mBooting;
4446 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004447 enableScreen = !mBooted;
4448 mBooted = true;
4449 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004450
4451 if (booting) {
4452 finishBooting();
4453 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004454
4455 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004456 enableScreenAfterBoot();
4457 }
4458 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004459
4460 public final void activityResumed(IBinder token) {
4461 final long origId = Binder.clearCallingIdentity();
4462 mMainStack.activityResumed(token);
4463 Binder.restoreCallingIdentity(origId);
4464 }
4465
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004466 public final void activityPaused(IBinder token) {
4467 final long origId = Binder.clearCallingIdentity();
4468 mMainStack.activityPaused(token, false);
4469 Binder.restoreCallingIdentity(origId);
4470 }
4471
4472 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4473 CharSequence description) {
4474 if (localLOGV) Slog.v(
4475 TAG, "Activity stopped: token=" + token);
4476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 // Refuse possible leaked file descriptors
4478 if (icicle != null && icicle.hasFileDescriptors()) {
4479 throw new IllegalArgumentException("File descriptors passed in Bundle");
4480 }
4481
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004482 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483
4484 final long origId = Binder.clearCallingIdentity();
4485
4486 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004487 r = mMainStack.isInStackLocked(token);
4488 if (r != null) {
4489 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 }
4491 }
4492
4493 if (r != null) {
4494 sendPendingThumbnail(r, null, null, null, false);
4495 }
4496
4497 trimApplications();
4498
4499 Binder.restoreCallingIdentity(origId);
4500 }
4501
4502 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004503 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004504 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
4506
4507 public String getCallingPackage(IBinder token) {
4508 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004509 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004510 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 }
4512 }
4513
4514 public ComponentName getCallingActivity(IBinder token) {
4515 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004516 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 return r != null ? r.intent.getComponent() : null;
4518 }
4519 }
4520
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004521 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004522 ActivityRecord r = mMainStack.isInStackLocked(token);
4523 if (r == null) {
4524 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004526 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 }
4528
4529 public ComponentName getActivityClassForToken(IBinder token) {
4530 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004531 ActivityRecord r = mMainStack.isInStackLocked(token);
4532 if (r == null) {
4533 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004535 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 }
4537 }
4538
4539 public String getPackageForToken(IBinder token) {
4540 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004541 ActivityRecord r = mMainStack.isInStackLocked(token);
4542 if (r == null) {
4543 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004545 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 }
4547 }
4548
4549 public IIntentSender getIntentSender(int type,
4550 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004551 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004552 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004553 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004555 if (intents != null) {
4556 if (intents.length < 1) {
4557 throw new IllegalArgumentException("Intents array length must be >= 1");
4558 }
4559 for (int i=0; i<intents.length; i++) {
4560 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004561 if (intent != null) {
4562 if (intent.hasFileDescriptors()) {
4563 throw new IllegalArgumentException("File descriptors passed in Intent");
4564 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004565 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004566 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4567 throw new IllegalArgumentException(
4568 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4569 }
4570 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004571 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004572 }
4573 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004574 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004575 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004576 }
4577 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004578 if (options != null) {
4579 if (options.hasFileDescriptors()) {
4580 throw new IllegalArgumentException("File descriptors passed in options");
4581 }
4582 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 synchronized(this) {
4585 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004586 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4587 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004589 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004590 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004591 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4592 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 String msg = "Permission Denial: getIntentSender() from pid="
4594 + Binder.getCallingPid()
4595 + ", uid=" + Binder.getCallingUid()
4596 + ", (need uid=" + uid + ")"
4597 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004598 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 throw new SecurityException(msg);
4600 }
4601 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004602
4603 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004604 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 } catch (RemoteException e) {
4607 throw new SecurityException(e);
4608 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004609 }
4610 }
4611
Dianne Hackborn41203752012-08-31 14:05:51 -07004612 IIntentSender getIntentSenderLocked(int type, String packageName,
4613 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004614 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4615 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004616 if (DEBUG_MU)
4617 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004618 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004619 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004620 activity = mMainStack.isInStackLocked(token);
4621 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004622 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004624 if (activity.finishing) {
4625 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004627 }
4628
4629 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4630 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4631 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4632 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4633 |PendingIntent.FLAG_UPDATE_CURRENT);
4634
4635 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4636 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004637 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004638 WeakReference<PendingIntentRecord> ref;
4639 ref = mIntentSenderRecords.get(key);
4640 PendingIntentRecord rec = ref != null ? ref.get() : null;
4641 if (rec != null) {
4642 if (!cancelCurrent) {
4643 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004644 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004645 rec.key.requestIntent.replaceExtras(intents != null ?
4646 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004647 }
4648 if (intents != null) {
4649 intents[intents.length-1] = rec.key.requestIntent;
4650 rec.key.allIntents = intents;
4651 rec.key.allResolvedTypes = resolvedTypes;
4652 } else {
4653 rec.key.allIntents = null;
4654 rec.key.allResolvedTypes = null;
4655 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 return rec;
4658 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004659 rec.canceled = true;
4660 mIntentSenderRecords.remove(key);
4661 }
4662 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 return rec;
4664 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004665 rec = new PendingIntentRecord(this, key, callingUid);
4666 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004667 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004668 if (activity.pendingResults == null) {
4669 activity.pendingResults
4670 = new HashSet<WeakReference<PendingIntentRecord>>();
4671 }
4672 activity.pendingResults.add(rec.ref);
4673 }
4674 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 }
4676
4677 public void cancelIntentSender(IIntentSender sender) {
4678 if (!(sender instanceof PendingIntentRecord)) {
4679 return;
4680 }
4681 synchronized(this) {
4682 PendingIntentRecord rec = (PendingIntentRecord)sender;
4683 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004684 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004685 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4686 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 String msg = "Permission Denial: cancelIntentSender() from pid="
4688 + Binder.getCallingPid()
4689 + ", uid=" + Binder.getCallingUid()
4690 + " is not allowed to cancel packges "
4691 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004692 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 throw new SecurityException(msg);
4694 }
4695 } catch (RemoteException e) {
4696 throw new SecurityException(e);
4697 }
4698 cancelIntentSenderLocked(rec, true);
4699 }
4700 }
4701
4702 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4703 rec.canceled = true;
4704 mIntentSenderRecords.remove(rec.key);
4705 if (cleanActivity && rec.key.activity != null) {
4706 rec.key.activity.pendingResults.remove(rec.ref);
4707 }
4708 }
4709
4710 public String getPackageForIntentSender(IIntentSender pendingResult) {
4711 if (!(pendingResult instanceof PendingIntentRecord)) {
4712 return null;
4713 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004714 try {
4715 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4716 return res.key.packageName;
4717 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 }
4719 return null;
4720 }
4721
Christopher Tatec4a07d12012-04-06 14:19:13 -07004722 public int getUidForIntentSender(IIntentSender sender) {
4723 if (sender instanceof PendingIntentRecord) {
4724 try {
4725 PendingIntentRecord res = (PendingIntentRecord)sender;
4726 return res.uid;
4727 } catch (ClassCastException e) {
4728 }
4729 }
4730 return -1;
4731 }
4732
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004733 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4734 if (!(pendingResult instanceof PendingIntentRecord)) {
4735 return false;
4736 }
4737 try {
4738 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4739 if (res.key.allIntents == null) {
4740 return false;
4741 }
4742 for (int i=0; i<res.key.allIntents.length; i++) {
4743 Intent intent = res.key.allIntents[i];
4744 if (intent.getPackage() != null && intent.getComponent() != null) {
4745 return false;
4746 }
4747 }
4748 return true;
4749 } catch (ClassCastException e) {
4750 }
4751 return false;
4752 }
4753
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004754 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4755 if (!(pendingResult instanceof PendingIntentRecord)) {
4756 return false;
4757 }
4758 try {
4759 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4760 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4761 return true;
4762 }
4763 return false;
4764 } catch (ClassCastException e) {
4765 }
4766 return false;
4767 }
4768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 public void setProcessLimit(int max) {
4770 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4771 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004772 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004773 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004774 mProcessLimitOverride = max;
4775 }
4776 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 }
4778
4779 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004780 synchronized (this) {
4781 return mProcessLimitOverride;
4782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783 }
4784
4785 void foregroundTokenDied(ForegroundToken token) {
4786 synchronized (ActivityManagerService.this) {
4787 synchronized (mPidsSelfLocked) {
4788 ForegroundToken cur
4789 = mForegroundProcesses.get(token.pid);
4790 if (cur != token) {
4791 return;
4792 }
4793 mForegroundProcesses.remove(token.pid);
4794 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4795 if (pr == null) {
4796 return;
4797 }
4798 pr.forcingToForeground = null;
4799 pr.foregroundServices = false;
4800 }
4801 updateOomAdjLocked();
4802 }
4803 }
4804
4805 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4806 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4807 "setProcessForeground()");
4808 synchronized(this) {
4809 boolean changed = false;
4810
4811 synchronized (mPidsSelfLocked) {
4812 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004813 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004814 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 return;
4816 }
4817 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4818 if (oldToken != null) {
4819 oldToken.token.unlinkToDeath(oldToken, 0);
4820 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004821 if (pr != null) {
4822 pr.forcingToForeground = null;
4823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 changed = true;
4825 }
4826 if (isForeground && token != null) {
4827 ForegroundToken newToken = new ForegroundToken() {
4828 public void binderDied() {
4829 foregroundTokenDied(this);
4830 }
4831 };
4832 newToken.pid = pid;
4833 newToken.token = token;
4834 try {
4835 token.linkToDeath(newToken, 0);
4836 mForegroundProcesses.put(pid, newToken);
4837 pr.forcingToForeground = token;
4838 changed = true;
4839 } catch (RemoteException e) {
4840 // If the process died while doing this, we will later
4841 // do the cleanup with the process death link.
4842 }
4843 }
4844 }
4845
4846 if (changed) {
4847 updateOomAdjLocked();
4848 }
4849 }
4850 }
4851
4852 // =========================================================
4853 // PERMISSIONS
4854 // =========================================================
4855
4856 static class PermissionController extends IPermissionController.Stub {
4857 ActivityManagerService mActivityManagerService;
4858 PermissionController(ActivityManagerService activityManagerService) {
4859 mActivityManagerService = activityManagerService;
4860 }
4861
4862 public boolean checkPermission(String permission, int pid, int uid) {
4863 return mActivityManagerService.checkPermission(permission, pid,
4864 uid) == PackageManager.PERMISSION_GRANTED;
4865 }
4866 }
4867
4868 /**
4869 * This can be called with or without the global lock held.
4870 */
4871 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004872 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 // We might be performing an operation on behalf of an indirect binder
4874 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4875 // client identity accordingly before proceeding.
4876 Identity tlsIdentity = sCallerIdentity.get();
4877 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004878 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004879 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4880 uid = tlsIdentity.uid;
4881 pid = tlsIdentity.pid;
4882 }
4883
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004884 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 return PackageManager.PERMISSION_GRANTED;
4886 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004887
4888 return ActivityManager.checkComponentPermission(permission, uid,
4889 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 }
4891
4892 /**
4893 * As the only public entry point for permissions checking, this method
4894 * can enforce the semantic that requesting a check on a null global
4895 * permission is automatically denied. (Internally a null permission
4896 * string is used when calling {@link #checkComponentPermission} in cases
4897 * when only uid-based security is needed.)
4898 *
4899 * This can be called with or without the global lock held.
4900 */
4901 public int checkPermission(String permission, int pid, int uid) {
4902 if (permission == null) {
4903 return PackageManager.PERMISSION_DENIED;
4904 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004905 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 }
4907
4908 /**
4909 * Binder IPC calls go through the public entry point.
4910 * This can be called with or without the global lock held.
4911 */
4912 int checkCallingPermission(String permission) {
4913 return checkPermission(permission,
4914 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004915 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 }
4917
4918 /**
4919 * This can be called with or without the global lock held.
4920 */
4921 void enforceCallingPermission(String permission, String func) {
4922 if (checkCallingPermission(permission)
4923 == PackageManager.PERMISSION_GRANTED) {
4924 return;
4925 }
4926
4927 String msg = "Permission Denial: " + func + " from pid="
4928 + Binder.getCallingPid()
4929 + ", uid=" + Binder.getCallingUid()
4930 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004931 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 throw new SecurityException(msg);
4933 }
4934
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004935 /**
4936 * Determine if UID is holding permissions required to access {@link Uri} in
4937 * the given {@link ProviderInfo}. Final permission checking is always done
4938 * in {@link ContentProvider}.
4939 */
4940 private final boolean checkHoldingPermissionsLocked(
4941 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004942 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4943 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004944
4945 if (pi.applicationInfo.uid == uid) {
4946 return true;
4947 } else if (!pi.exported) {
4948 return false;
4949 }
4950
4951 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4952 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004954 // check if target holds top-level <provider> permissions
4955 if (!readMet && pi.readPermission != null
4956 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4957 readMet = true;
4958 }
4959 if (!writeMet && pi.writePermission != null
4960 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4961 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004963
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004964 // track if unprotected read/write is allowed; any denied
4965 // <path-permission> below removes this ability
4966 boolean allowDefaultRead = pi.readPermission == null;
4967 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004968
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004969 // check if target holds any <path-permission> that match uri
4970 final PathPermission[] pps = pi.pathPermissions;
4971 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004972 final String path = uri.getPath();
4973 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004974 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004975 i--;
4976 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004977 if (pp.match(path)) {
4978 if (!readMet) {
4979 final String pprperm = pp.getReadPermission();
4980 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4981 + pprperm + " for " + pp.getPath()
4982 + ": match=" + pp.match(path)
4983 + " check=" + pm.checkUidPermission(pprperm, uid));
4984 if (pprperm != null) {
4985 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4986 readMet = true;
4987 } else {
4988 allowDefaultRead = false;
4989 }
4990 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004991 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004992 if (!writeMet) {
4993 final String ppwperm = pp.getWritePermission();
4994 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4995 + ppwperm + " for " + pp.getPath()
4996 + ": match=" + pp.match(path)
4997 + " check=" + pm.checkUidPermission(ppwperm, uid));
4998 if (ppwperm != null) {
4999 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5000 writeMet = true;
5001 } else {
5002 allowDefaultWrite = false;
5003 }
5004 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005005 }
5006 }
5007 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005008 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005009
5010 // grant unprotected <provider> read/write, if not blocked by
5011 // <path-permission> above
5012 if (allowDefaultRead) readMet = true;
5013 if (allowDefaultWrite) writeMet = true;
5014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 } catch (RemoteException e) {
5016 return false;
5017 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005018
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005019 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 }
5021
5022 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5023 int modeFlags) {
5024 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005025 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 return true;
5027 }
5028 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5029 if (perms == null) return false;
5030 UriPermission perm = perms.get(uri);
5031 if (perm == null) return false;
5032 return (modeFlags&perm.modeFlags) == modeFlags;
5033 }
5034
5035 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005036 enforceNotIsolatedCaller("checkUriPermission");
5037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 // Another redirected-binder-call permissions check as in
5039 // {@link checkComponentPermission}.
5040 Identity tlsIdentity = sCallerIdentity.get();
5041 if (tlsIdentity != null) {
5042 uid = tlsIdentity.uid;
5043 pid = tlsIdentity.pid;
5044 }
5045
5046 // Our own process gets to do everything.
5047 if (pid == MY_PID) {
5048 return PackageManager.PERMISSION_GRANTED;
5049 }
5050 synchronized(this) {
5051 return checkUriPermissionLocked(uri, uid, modeFlags)
5052 ? PackageManager.PERMISSION_GRANTED
5053 : PackageManager.PERMISSION_DENIED;
5054 }
5055 }
5056
Dianne Hackborn39792d22010-08-19 18:01:52 -07005057 /**
5058 * Check if the targetPkg can be granted permission to access uri by
5059 * the callingUid using the given modeFlags. Throws a security exception
5060 * if callingUid is not allowed to do this. Returns the uid of the target
5061 * if the URI permission grant should be performed; returns -1 if it is not
5062 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005063 * If you already know the uid of the target, you can supply it in
5064 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005065 */
5066 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005067 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5069 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5070 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005071 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 }
5073
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005074 if (targetPkg != null) {
5075 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5076 "Checking grant " + targetPkg + " permission to " + uri);
5077 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005078
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005079 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080
5081 // If this is not a content: uri, we can't do anything with it.
5082 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005083 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005084 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005085 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 }
5087
5088 String name = uri.getAuthority();
5089 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005090 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005091 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 if (cpr != null) {
5093 pi = cpr.info;
5094 } else {
5095 try {
5096 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005097 PackageManager.GET_URI_PERMISSION_PATTERNS,
5098 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 } catch (RemoteException ex) {
5100 }
5101 }
5102 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005103 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005104 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 }
5106
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005107 int targetUid = lastTargetUid;
5108 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005109 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005110 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005111 if (targetUid < 0) {
5112 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5113 "Can't grant URI permission no uid for: " + targetPkg);
5114 return -1;
5115 }
5116 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005117 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 }
5120
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005121 if (targetUid >= 0) {
5122 // First... does the target actually need this permission?
5123 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5124 // No need to grant the target this permission.
5125 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5126 "Target " + targetPkg + " already has full permission to " + uri);
5127 return -1;
5128 }
5129 } else {
5130 // First... there is no target package, so can anyone access it?
5131 boolean allowed = pi.exported;
5132 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5133 if (pi.readPermission != null) {
5134 allowed = false;
5135 }
5136 }
5137 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5138 if (pi.writePermission != null) {
5139 allowed = false;
5140 }
5141 }
5142 if (allowed) {
5143 return -1;
5144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 }
5146
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005147 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 if (!pi.grantUriPermissions) {
5149 throw new SecurityException("Provider " + pi.packageName
5150 + "/" + pi.name
5151 + " does not allow granting of Uri permissions (uri "
5152 + uri + ")");
5153 }
5154 if (pi.uriPermissionPatterns != null) {
5155 final int N = pi.uriPermissionPatterns.length;
5156 boolean allowed = false;
5157 for (int i=0; i<N; i++) {
5158 if (pi.uriPermissionPatterns[i] != null
5159 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5160 allowed = true;
5161 break;
5162 }
5163 }
5164 if (!allowed) {
5165 throw new SecurityException("Provider " + pi.packageName
5166 + "/" + pi.name
5167 + " does not allow granting of permission to path of Uri "
5168 + uri);
5169 }
5170 }
5171
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005172 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005174 if (callingUid != Process.myUid()) {
5175 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5176 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5177 throw new SecurityException("Uid " + callingUid
5178 + " does not have permission to uri " + uri);
5179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180 }
5181 }
5182
Dianne Hackborn39792d22010-08-19 18:01:52 -07005183 return targetUid;
5184 }
5185
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005186 public int checkGrantUriPermission(int callingUid, String targetPkg,
5187 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005188 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005189 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005190 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005191 }
5192 }
5193
Dianne Hackborn39792d22010-08-19 18:01:52 -07005194 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5195 Uri uri, int modeFlags, UriPermissionOwner owner) {
5196 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5197 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5198 if (modeFlags == 0) {
5199 return;
5200 }
5201
5202 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 // to the uri, and the target doesn't. Let's now give this to
5204 // the target.
5205
Joe Onorato8a9b2202010-02-26 18:56:32 -08005206 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005207 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 HashMap<Uri, UriPermission> targetUris
5210 = mGrantedUriPermissions.get(targetUid);
5211 if (targetUris == null) {
5212 targetUris = new HashMap<Uri, UriPermission>();
5213 mGrantedUriPermissions.put(targetUid, targetUris);
5214 }
5215
5216 UriPermission perm = targetUris.get(uri);
5217 if (perm == null) {
5218 perm = new UriPermission(targetUid, uri);
5219 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005223 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005225 } else {
5226 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5227 perm.readOwners.add(owner);
5228 owner.addReadPermission(perm);
5229 }
5230 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5231 perm.writeOwners.add(owner);
5232 owner.addWritePermission(perm);
5233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 }
5235 }
5236
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005237 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5238 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005239 if (targetPkg == null) {
5240 throw new NullPointerException("targetPkg");
5241 }
5242
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005243 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005244 if (targetUid < 0) {
5245 return;
5246 }
5247
5248 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5249 }
5250
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005251 static class NeededUriGrants extends ArrayList<Uri> {
5252 final String targetPkg;
5253 final int targetUid;
5254 final int flags;
5255
5256 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5257 targetPkg = _targetPkg;
5258 targetUid = _targetUid;
5259 flags = _flags;
5260 }
5261 }
5262
Dianne Hackborn39792d22010-08-19 18:01:52 -07005263 /**
5264 * Like checkGrantUriPermissionLocked, but takes an Intent.
5265 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005266 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5267 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005268 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005269 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5270 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005271 + " from " + intent + "; flags=0x"
5272 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5273
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005274 if (targetPkg == null) {
5275 throw new NullPointerException("targetPkg");
5276 }
5277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005279 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 }
5281 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005282 ClipData clip = intent.getClipData();
5283 if (data == null && clip == null) {
5284 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005285 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005286 if (data != null) {
5287 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5288 mode, needed != null ? needed.targetUid : -1);
5289 if (target > 0) {
5290 if (needed == null) {
5291 needed = new NeededUriGrants(targetPkg, target, mode);
5292 }
5293 needed.add(data);
5294 }
5295 }
5296 if (clip != null) {
5297 for (int i=0; i<clip.getItemCount(); i++) {
5298 Uri uri = clip.getItemAt(i).getUri();
5299 if (uri != null) {
5300 int target = -1;
5301 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5302 mode, needed != null ? needed.targetUid : -1);
5303 if (target > 0) {
5304 if (needed == null) {
5305 needed = new NeededUriGrants(targetPkg, target, mode);
5306 }
5307 needed.add(uri);
5308 }
5309 } else {
5310 Intent clipIntent = clip.getItemAt(i).getIntent();
5311 if (clipIntent != null) {
5312 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5313 callingUid, targetPkg, clipIntent, mode, needed);
5314 if (newNeeded != null) {
5315 needed = newNeeded;
5316 }
5317 }
5318 }
5319 }
5320 }
5321
5322 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005323 }
5324
5325 /**
5326 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5327 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005328 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5329 UriPermissionOwner owner) {
5330 if (needed != null) {
5331 for (int i=0; i<needed.size(); i++) {
5332 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5333 needed.get(i), needed.flags, owner);
5334 }
5335 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005336 }
5337
5338 void grantUriPermissionFromIntentLocked(int callingUid,
5339 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005340 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005341 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005342 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 return;
5344 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005345
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005346 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347 }
5348
5349 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5350 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005351 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 synchronized(this) {
5353 final ProcessRecord r = getRecordForAppLocked(caller);
5354 if (r == null) {
5355 throw new SecurityException("Unable to find app for caller "
5356 + caller
5357 + " when granting permission to uri " + uri);
5358 }
5359 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005360 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 }
5362 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005363 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 }
5365
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005366 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 null);
5368 }
5369 }
5370
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005371 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5373 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5374 HashMap<Uri, UriPermission> perms
5375 = mGrantedUriPermissions.get(perm.uid);
5376 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005377 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005378 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 perms.remove(perm.uri);
5380 if (perms.size() == 0) {
5381 mGrantedUriPermissions.remove(perm.uid);
5382 }
5383 }
5384 }
5385 }
5386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5388 int modeFlags) {
5389 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5390 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5391 if (modeFlags == 0) {
5392 return;
5393 }
5394
Joe Onorato8a9b2202010-02-26 18:56:32 -08005395 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005396 "Revoking all granted permissions to " + uri);
5397
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005398 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399
5400 final String authority = uri.getAuthority();
5401 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005402 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005403 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 if (cpr != null) {
5405 pi = cpr.info;
5406 } else {
5407 try {
5408 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005409 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 } catch (RemoteException ex) {
5411 }
5412 }
5413 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005414 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 return;
5416 }
5417
5418 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005419 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 // Right now, if you are not the original owner of the permission,
5421 // you are not allowed to revoke it.
5422 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5423 throw new SecurityException("Uid " + callingUid
5424 + " does not have permission to uri " + uri);
5425 //}
5426 }
5427
5428 // Go through all of the permissions and remove any that match.
5429 final List<String> SEGMENTS = uri.getPathSegments();
5430 if (SEGMENTS != null) {
5431 final int NS = SEGMENTS.size();
5432 int N = mGrantedUriPermissions.size();
5433 for (int i=0; i<N; i++) {
5434 HashMap<Uri, UriPermission> perms
5435 = mGrantedUriPermissions.valueAt(i);
5436 Iterator<UriPermission> it = perms.values().iterator();
5437 toploop:
5438 while (it.hasNext()) {
5439 UriPermission perm = it.next();
5440 Uri targetUri = perm.uri;
5441 if (!authority.equals(targetUri.getAuthority())) {
5442 continue;
5443 }
5444 List<String> targetSegments = targetUri.getPathSegments();
5445 if (targetSegments == null) {
5446 continue;
5447 }
5448 if (targetSegments.size() < NS) {
5449 continue;
5450 }
5451 for (int j=0; j<NS; j++) {
5452 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5453 continue toploop;
5454 }
5455 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005456 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005457 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 perm.clearModes(modeFlags);
5459 if (perm.modeFlags == 0) {
5460 it.remove();
5461 }
5462 }
5463 if (perms.size() == 0) {
5464 mGrantedUriPermissions.remove(
5465 mGrantedUriPermissions.keyAt(i));
5466 N--;
5467 i--;
5468 }
5469 }
5470 }
5471 }
5472
5473 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5474 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005475 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 synchronized(this) {
5477 final ProcessRecord r = getRecordForAppLocked(caller);
5478 if (r == null) {
5479 throw new SecurityException("Unable to find app for caller "
5480 + caller
5481 + " when revoking permission to uri " + uri);
5482 }
5483 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005484 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 return;
5486 }
5487
5488 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5489 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5490 if (modeFlags == 0) {
5491 return;
5492 }
5493
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005494 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495
5496 final String authority = uri.getAuthority();
5497 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005498 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 if (cpr != null) {
5500 pi = cpr.info;
5501 } else {
5502 try {
5503 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005504 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 } catch (RemoteException ex) {
5506 }
5507 }
5508 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005509 Slog.w(TAG, "No content provider found for permission revoke: "
5510 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 return;
5512 }
5513
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005514 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 }
5516 }
5517
Dianne Hackborn7e269642010-08-25 19:50:20 -07005518 @Override
5519 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005520 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005521 synchronized(this) {
5522 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5523 return owner.getExternalTokenLocked();
5524 }
5525 }
5526
5527 @Override
5528 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5529 Uri uri, int modeFlags) {
5530 synchronized(this) {
5531 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5532 if (owner == null) {
5533 throw new IllegalArgumentException("Unknown owner: " + token);
5534 }
5535 if (fromUid != Binder.getCallingUid()) {
5536 if (Binder.getCallingUid() != Process.myUid()) {
5537 // Only system code can grant URI permissions on behalf
5538 // of other users.
5539 throw new SecurityException("nice try");
5540 }
5541 }
5542 if (targetPkg == null) {
5543 throw new IllegalArgumentException("null target");
5544 }
5545 if (uri == null) {
5546 throw new IllegalArgumentException("null uri");
5547 }
5548
5549 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5550 }
5551 }
5552
5553 @Override
5554 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5555 synchronized(this) {
5556 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5557 if (owner == null) {
5558 throw new IllegalArgumentException("Unknown owner: " + token);
5559 }
5560
5561 if (uri == null) {
5562 owner.removeUriPermissionsLocked(mode);
5563 } else {
5564 owner.removeUriPermissionLocked(uri, mode);
5565 }
5566 }
5567 }
5568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5570 synchronized (this) {
5571 ProcessRecord app =
5572 who != null ? getRecordForAppLocked(who) : null;
5573 if (app == null) return;
5574
5575 Message msg = Message.obtain();
5576 msg.what = WAIT_FOR_DEBUGGER_MSG;
5577 msg.obj = app;
5578 msg.arg1 = waiting ? 1 : 0;
5579 mHandler.sendMessage(msg);
5580 }
5581 }
5582
5583 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005584 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5585 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005587 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005588 outInfo.threshold = homeAppMem;
5589 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5590 outInfo.hiddenAppThreshold = hiddenAppMem;
5591 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005592 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005593 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5594 ProcessList.VISIBLE_APP_ADJ);
5595 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5596 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 }
5598
5599 // =========================================================
5600 // TASK MANAGEMENT
5601 // =========================================================
5602
5603 public List getTasks(int maxNum, int flags,
5604 IThumbnailReceiver receiver) {
5605 ArrayList list = new ArrayList();
5606
5607 PendingThumbnailsRecord pending = null;
5608 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005609 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610
5611 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005612 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5614 + ", receiver=" + receiver);
5615
5616 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5617 != PackageManager.PERMISSION_GRANTED) {
5618 if (receiver != null) {
5619 // If the caller wants to wait for pending thumbnails,
5620 // it ain't gonna get them.
5621 try {
5622 receiver.finished();
5623 } catch (RemoteException ex) {
5624 }
5625 }
5626 String msg = "Permission Denial: getTasks() from pid="
5627 + Binder.getCallingPid()
5628 + ", uid=" + Binder.getCallingUid()
5629 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005630 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 throw new SecurityException(msg);
5632 }
5633
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005634 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005635 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005636 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005637 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 TaskRecord curTask = null;
5639 int numActivities = 0;
5640 int numRunning = 0;
5641 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005642 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005644 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645
5646 // Initialize state for next task if needed.
5647 if (top == null ||
5648 (top.state == ActivityState.INITIALIZING
5649 && top.task == r.task)) {
5650 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 curTask = r.task;
5652 numActivities = numRunning = 0;
5653 }
5654
5655 // Add 'r' into the current task.
5656 numActivities++;
5657 if (r.app != null && r.app.thread != null) {
5658 numRunning++;
5659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660
Joe Onorato8a9b2202010-02-26 18:56:32 -08005661 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 TAG, r.intent.getComponent().flattenToShortString()
5663 + ": task=" + r.task);
5664
5665 // If the next one is a different task, generate a new
5666 // TaskInfo entry for what we have.
5667 if (next == null || next.task != curTask) {
5668 ActivityManager.RunningTaskInfo ci
5669 = new ActivityManager.RunningTaskInfo();
5670 ci.id = curTask.taskId;
5671 ci.baseActivity = r.intent.getComponent();
5672 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005673 if (top.thumbHolder != null) {
5674 ci.description = top.thumbHolder.lastDescription;
5675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 ci.numActivities = numActivities;
5677 ci.numRunning = numRunning;
5678 //System.out.println(
5679 // "#" + maxNum + ": " + " descr=" + ci.description);
5680 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005681 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 TAG, "State=" + top.state + "Idle=" + top.idle
5683 + " app=" + top.app
5684 + " thr=" + (top.app != null ? top.app.thread : null));
5685 if (top.state == ActivityState.RESUMED
5686 || top.state == ActivityState.PAUSING) {
5687 if (top.idle && top.app != null
5688 && top.app.thread != null) {
5689 topRecord = top;
5690 topThumbnail = top.app.thread;
5691 } else {
5692 top.thumbnailNeeded = true;
5693 }
5694 }
5695 if (pending == null) {
5696 pending = new PendingThumbnailsRecord(receiver);
5697 }
5698 pending.pendingRecords.add(top);
5699 }
5700 list.add(ci);
5701 maxNum--;
5702 top = null;
5703 }
5704 }
5705
5706 if (pending != null) {
5707 mPendingThumbnails.add(pending);
5708 }
5709 }
5710
Joe Onorato8a9b2202010-02-26 18:56:32 -08005711 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712
5713 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005714 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005716 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005718 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005719 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 }
5721 }
5722
5723 if (pending == null && receiver != null) {
5724 // In this case all thumbnails were available and the client
5725 // is being asked to be told when the remaining ones come in...
5726 // which is unusually, since the top-most currently running
5727 // activity should never have a canned thumbnail! Oh well.
5728 try {
5729 receiver.finished();
5730 } catch (RemoteException ex) {
5731 }
5732 }
5733
5734 return list;
5735 }
5736
5737 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005738 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005739 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005740 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005741 // Check if the caller is holding permissions for cross-user requests.
5742 if (checkComponentPermission(
5743 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5744 Binder.getCallingPid(), callingUid, -1, true)
5745 != PackageManager.PERMISSION_GRANTED) {
5746 String msg = "Permission Denial: "
5747 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005748 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005749 + "; this requires "
5750 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5751 Slog.w(TAG, msg);
5752 throw new SecurityException(msg);
5753 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005754 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005755 userId = mCurrentUserId;
5756 }
5757 }
5758 }
5759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 synchronized (this) {
5761 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5762 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005763 final boolean detailed = checkCallingPermission(
5764 android.Manifest.permission.GET_DETAILED_TASKS)
5765 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005767 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 final int N = mRecentTasks.size();
5770 ArrayList<ActivityManager.RecentTaskInfo> res
5771 = new ArrayList<ActivityManager.RecentTaskInfo>(
5772 maxNum < N ? maxNum : N);
5773 for (int i=0; i<N && maxNum > 0; i++) {
5774 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005775 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005776 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005777 // Return the entry if desired by the caller. We always return
5778 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005779 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005780 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5781 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005782
Dianne Hackborn905577f2011-09-07 18:31:28 -07005783 if (i == 0
5784 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 || (tr.intent == null)
5786 || ((tr.intent.getFlags()
5787 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5788 ActivityManager.RecentTaskInfo rti
5789 = new ActivityManager.RecentTaskInfo();
5790 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005791 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 rti.baseIntent = new Intent(
5793 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005794 if (!detailed) {
5795 rti.baseIntent.replaceExtras((Bundle)null);
5796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005798 rti.description = tr.lastDescription;
5799
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005800 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5801 // Check whether this activity is currently available.
5802 try {
5803 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005804 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005805 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005806 continue;
5807 }
5808 } else if (rti.baseIntent != null) {
5809 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005810 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005811 continue;
5812 }
5813 }
5814 } catch (RemoteException e) {
5815 // Will never happen.
5816 }
5817 }
5818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 res.add(rti);
5820 maxNum--;
5821 }
5822 }
5823 return res;
5824 }
5825 }
5826
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005827 private TaskRecord taskForIdLocked(int id) {
5828 final int N = mRecentTasks.size();
5829 for (int i=0; i<N; i++) {
5830 TaskRecord tr = mRecentTasks.get(i);
5831 if (tr.taskId == id) {
5832 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005833 }
5834 }
5835 return null;
5836 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005837
5838 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5839 synchronized (this) {
5840 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5841 "getTaskThumbnails()");
5842 TaskRecord tr = taskForIdLocked(id);
5843 if (tr != null) {
5844 return mMainStack.getTaskThumbnailsLocked(tr);
5845 }
5846 }
5847 return null;
5848 }
5849
Dianne Hackborn15491c62012-09-19 10:59:14 -07005850 public Bitmap getTaskTopThumbnail(int id) {
5851 synchronized (this) {
5852 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5853 "getTaskTopThumbnail()");
5854 TaskRecord tr = taskForIdLocked(id);
5855 if (tr != null) {
5856 return mMainStack.getTaskTopThumbnailLocked(tr);
5857 }
5858 }
5859 return null;
5860 }
5861
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005862 public boolean removeSubTask(int taskId, int subTaskIndex) {
5863 synchronized (this) {
5864 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5865 "removeSubTask()");
5866 long ident = Binder.clearCallingIdentity();
5867 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005868 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5869 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005870 } finally {
5871 Binder.restoreCallingIdentity(ident);
5872 }
5873 }
5874 }
5875
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005876 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5877 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005878 Intent baseIntent = new Intent(
5879 tr.intent != null ? tr.intent : tr.affinityIntent);
5880 ComponentName component = baseIntent.getComponent();
5881 if (component == null) {
5882 Slog.w(TAG, "Now component for base intent of task: " + tr);
5883 return;
5884 }
5885
5886 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005887 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005888
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005889 if (killProcesses) {
5890 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005891 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005892 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005893 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5894 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5895 for (int i=0; i<uids.size(); i++) {
5896 ProcessRecord proc = uids.valueAt(i);
5897 if (proc.userId != tr.userId) {
5898 continue;
5899 }
5900 if (!proc.pkgList.contains(pkg)) {
5901 continue;
5902 }
5903 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005904 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005905 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005906
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005907 // Kill the running processes.
5908 for (int i=0; i<procs.size(); i++) {
5909 ProcessRecord pr = procs.get(i);
5910 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5911 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5912 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5913 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005914 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005915 Process.killProcessQuiet(pr.pid);
5916 } else {
5917 pr.waitingToKill = "remove task";
5918 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005919 }
5920 }
5921 }
5922
5923 public boolean removeTask(int taskId, int flags) {
5924 synchronized (this) {
5925 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5926 "removeTask()");
5927 long ident = Binder.clearCallingIdentity();
5928 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005929 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5930 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005931 if (r != null) {
5932 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005933 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005934 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005935 } else {
5936 TaskRecord tr = null;
5937 int i=0;
5938 while (i < mRecentTasks.size()) {
5939 TaskRecord t = mRecentTasks.get(i);
5940 if (t.taskId == taskId) {
5941 tr = t;
5942 break;
5943 }
5944 i++;
5945 }
5946 if (tr != null) {
5947 if (tr.numActivities <= 0) {
5948 // Caller is just removing a recent task that is
5949 // not actively running. That is easy!
5950 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005951 cleanUpRemovedTaskLocked(tr, flags);
5952 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005953 } else {
5954 Slog.w(TAG, "removeTask: task " + taskId
5955 + " does not have activities to remove, "
5956 + " but numActivities=" + tr.numActivities
5957 + ": " + tr);
5958 }
5959 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005960 }
5961 } finally {
5962 Binder.restoreCallingIdentity(ident);
5963 }
5964 }
5965 return false;
5966 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5969 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005970 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 TaskRecord jt = startTask;
5972
5973 // First look backwards
5974 for (j=startIndex-1; j>=0; 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 jt = r.task;
5978 if (affinity.equals(jt.affinity)) {
5979 return j;
5980 }
5981 }
5982 }
5983
5984 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005985 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 jt = startTask;
5987 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005988 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 if (r.task != jt) {
5990 if (affinity.equals(jt.affinity)) {
5991 return j;
5992 }
5993 jt = r.task;
5994 }
5995 }
5996
5997 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005998 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 return N-1;
6000 }
6001
6002 return -1;
6003 }
6004
6005 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006006 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006008 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6010 "moveTaskToFront()");
6011
6012 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006013 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6014 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006015 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006016 return;
6017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 final long origId = Binder.clearCallingIdentity();
6019 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006020 TaskRecord tr = taskForIdLocked(task);
6021 if (tr != null) {
6022 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6023 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006025 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6026 // Caller wants the home activity moved with it. To accomplish this,
6027 // we'll just move the home task to the top first.
6028 mMainStack.moveHomeToFrontLocked();
6029 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006030 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006031 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006033 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6034 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006036 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6037 mMainStack.mUserLeaving = true;
6038 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006039 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6040 // Caller wants the home activity moved with it. To accomplish this,
6041 // we'll just move the home task to the top first.
6042 mMainStack.moveHomeToFrontLocked();
6043 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006044 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 return;
6046 }
6047 }
6048 } finally {
6049 Binder.restoreCallingIdentity(origId);
6050 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006051 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 }
6053 }
6054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 public void moveTaskToBack(int task) {
6056 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6057 "moveTaskToBack()");
6058
6059 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006060 if (mMainStack.mResumedActivity != null
6061 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006062 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6063 Binder.getCallingUid(), "Task to back")) {
6064 return;
6065 }
6066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006068 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 Binder.restoreCallingIdentity(origId);
6070 }
6071 }
6072
6073 /**
6074 * Moves an activity, and all of the other activities within the same task, to the bottom
6075 * of the history stack. The activity's order within the task is unchanged.
6076 *
6077 * @param token A reference to the activity we wish to move
6078 * @param nonRoot If false then this only works if the activity is the root
6079 * of a task; if true it will work for any activity in a task.
6080 * @return Returns true if the move completed, false if not.
6081 */
6082 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006083 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 synchronized(this) {
6085 final long origId = Binder.clearCallingIdentity();
6086 int taskId = getTaskForActivityLocked(token, !nonRoot);
6087 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006088 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 }
6090 Binder.restoreCallingIdentity(origId);
6091 }
6092 return false;
6093 }
6094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 public void moveTaskBackwards(int task) {
6096 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6097 "moveTaskBackwards()");
6098
6099 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006100 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6101 Binder.getCallingUid(), "Task backwards")) {
6102 return;
6103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 final long origId = Binder.clearCallingIdentity();
6105 moveTaskBackwardsLocked(task);
6106 Binder.restoreCallingIdentity(origId);
6107 }
6108 }
6109
6110 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006111 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 }
6113
6114 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6115 synchronized(this) {
6116 return getTaskForActivityLocked(token, onlyRoot);
6117 }
6118 }
6119
6120 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006121 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 TaskRecord lastTask = null;
6123 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006124 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006125 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 if (!onlyRoot || lastTask != r.task) {
6127 return r.task.taskId;
6128 }
6129 return -1;
6130 }
6131 lastTask = r.task;
6132 }
6133
6134 return -1;
6135 }
6136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 // =========================================================
6138 // THUMBNAILS
6139 // =========================================================
6140
6141 public void reportThumbnail(IBinder token,
6142 Bitmap thumbnail, CharSequence description) {
6143 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6144 final long origId = Binder.clearCallingIdentity();
6145 sendPendingThumbnail(null, token, thumbnail, description, true);
6146 Binder.restoreCallingIdentity(origId);
6147 }
6148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006149 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 Bitmap thumbnail, CharSequence description, boolean always) {
6151 TaskRecord task = null;
6152 ArrayList receivers = null;
6153
6154 //System.out.println("Send pending thumbnail: " + r);
6155
6156 synchronized(this) {
6157 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006158 r = mMainStack.isInStackLocked(token);
6159 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 return;
6161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006163 if (thumbnail == null && r.thumbHolder != null) {
6164 thumbnail = r.thumbHolder.lastThumbnail;
6165 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 }
6167 if (thumbnail == null && !always) {
6168 // If there is no thumbnail, and this entry is not actually
6169 // going away, then abort for now and pick up the next
6170 // thumbnail we get.
6171 return;
6172 }
6173 task = r.task;
6174
6175 int N = mPendingThumbnails.size();
6176 int i=0;
6177 while (i<N) {
6178 PendingThumbnailsRecord pr =
6179 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6180 //System.out.println("Looking in " + pr.pendingRecords);
6181 if (pr.pendingRecords.remove(r)) {
6182 if (receivers == null) {
6183 receivers = new ArrayList();
6184 }
6185 receivers.add(pr);
6186 if (pr.pendingRecords.size() == 0) {
6187 pr.finished = true;
6188 mPendingThumbnails.remove(i);
6189 N--;
6190 continue;
6191 }
6192 }
6193 i++;
6194 }
6195 }
6196
6197 if (receivers != null) {
6198 final int N = receivers.size();
6199 for (int i=0; i<N; i++) {
6200 try {
6201 PendingThumbnailsRecord pr =
6202 (PendingThumbnailsRecord)receivers.get(i);
6203 pr.receiver.newThumbnail(
6204 task != null ? task.taskId : -1, thumbnail, description);
6205 if (pr.finished) {
6206 pr.receiver.finished();
6207 }
6208 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006209 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 }
6211 }
6212 }
6213 }
6214
6215 // =========================================================
6216 // CONTENT PROVIDERS
6217 // =========================================================
6218
Jeff Brown10e89712011-07-08 18:52:57 -07006219 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6220 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006222 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006223 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006224 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 } catch (RemoteException ex) {
6226 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006227 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006228 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6229 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006231 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 for (int i=0; i<N; i++) {
6233 ProviderInfo cpi =
6234 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006235 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6236 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006237 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006238 // This is a singleton provider, but a user besides the
6239 // default user is asking to initialize a process it runs
6240 // in... well, no, it doesn't actually run in this process,
6241 // it runs in the process of the default user. Get rid of it.
6242 providers.remove(i);
6243 N--;
6244 continue;
6245 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006246
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006247 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006248 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006250 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006251 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006253 if (DEBUG_MU)
6254 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 app.pubProviders.put(cpi.name, cpr);
6256 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006257 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 }
6259 }
6260 return providers;
6261 }
6262
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006263 /**
6264 * Check if {@link ProcessRecord} has a possible chance at accessing the
6265 * given {@link ProviderInfo}. Final permission checking is always done
6266 * in {@link ContentProvider}.
6267 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006269 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006271 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006273 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006274 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 return null;
6276 }
6277 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006278 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 == PackageManager.PERMISSION_GRANTED) {
6280 return null;
6281 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006282
6283 PathPermission[] pps = cpi.pathPermissions;
6284 if (pps != null) {
6285 int i = pps.length;
6286 while (i > 0) {
6287 i--;
6288 PathPermission pp = pps[i];
6289 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006290 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006291 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006292 return null;
6293 }
6294 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006295 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006296 == PackageManager.PERMISSION_GRANTED) {
6297 return null;
6298 }
6299 }
6300 }
6301
Dianne Hackbornb424b632010-08-18 15:59:05 -07006302 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6303 if (perms != null) {
6304 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6305 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6306 return null;
6307 }
6308 }
6309 }
6310
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006311 String msg;
6312 if (!cpi.exported) {
6313 msg = "Permission Denial: opening provider " + cpi.name
6314 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6315 + ", uid=" + callingUid + ") that is not exported from uid "
6316 + cpi.applicationInfo.uid;
6317 } else {
6318 msg = "Permission Denial: opening provider " + cpi.name
6319 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6320 + ", uid=" + callingUid + ") requires "
6321 + cpi.readPermission + " or " + cpi.writePermission;
6322 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006323 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 return msg;
6325 }
6326
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006327 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6328 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006329 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006330 for (int i=0; i<r.conProviders.size(); i++) {
6331 ContentProviderConnection conn = r.conProviders.get(i);
6332 if (conn.provider == cpr) {
6333 if (DEBUG_PROVIDER) Slog.v(TAG,
6334 "Adding provider requested by "
6335 + r.processName + " from process "
6336 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6337 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6338 if (stable) {
6339 conn.stableCount++;
6340 conn.numStableIncs++;
6341 } else {
6342 conn.unstableCount++;
6343 conn.numUnstableIncs++;
6344 }
6345 return conn;
6346 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006347 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006348 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6349 if (stable) {
6350 conn.stableCount = 1;
6351 conn.numStableIncs = 1;
6352 } else {
6353 conn.unstableCount = 1;
6354 conn.numUnstableIncs = 1;
6355 }
6356 cpr.connections.add(conn);
6357 r.conProviders.add(conn);
6358 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006359 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006360 cpr.addExternalProcessHandleLocked(externalProcessToken);
6361 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006362 }
6363
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006364 boolean decProviderCountLocked(ContentProviderConnection conn,
6365 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6366 if (conn != null) {
6367 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006368 if (DEBUG_PROVIDER) Slog.v(TAG,
6369 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006370 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006371 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006372 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6373 if (stable) {
6374 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006375 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006376 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006377 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006378 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6379 cpr.connections.remove(conn);
6380 conn.client.conProviders.remove(conn);
6381 return true;
6382 }
6383 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006384 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006385 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006386 return false;
6387 }
6388
Amith Yamasani742a6712011-05-04 14:49:28 -07006389 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006390 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006392 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 ProviderInfo cpi = null;
6394
6395 synchronized(this) {
6396 ProcessRecord r = null;
6397 if (caller != null) {
6398 r = getRecordForAppLocked(caller);
6399 if (r == null) {
6400 throw new SecurityException(
6401 "Unable to find app for caller " + caller
6402 + " (pid=" + Binder.getCallingPid()
6403 + ") when getting content provider " + name);
6404 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006405 if (r.userId != userId) {
6406 throw new SecurityException("Calling requested user " + userId
6407 + " but app is user " + r.userId);
6408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 }
6410
6411 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006412 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006413 boolean providerRunning = cpr != null;
6414 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006416 String msg;
6417 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6418 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 }
6420
6421 if (r != null && cpr.canRunHere(r)) {
6422 // This provider has been published or is in the process
6423 // of being published... but it is also allowed to run
6424 // in the caller's process, so don't make a connection
6425 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006426 ContentProviderHolder holder = cpr.newHolder(null);
6427 // don't give caller the provider object, it needs
6428 // to make its own.
6429 holder.provider = null;
6430 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
6432
6433 final long origId = Binder.clearCallingIdentity();
6434
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006435 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006437 conn = incProviderCountLocked(r, cpr, token, stable);
6438 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006439 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006440 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006441 // make sure to count it as being accessed and thus
6442 // back up on the LRU list. This is good because
6443 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006444 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006445 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006446 }
6447
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006448 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006449 if (false) {
6450 if (cpr.name.flattenToShortString().equals(
6451 "com.android.providers.calendar/.CalendarProvider2")) {
6452 Slog.v(TAG, "****************** KILLING "
6453 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006454 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006455 }
6456 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006457 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006458 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6459 // NOTE: there is still a race here where a signal could be
6460 // pending on the process even though we managed to update its
6461 // adj level. Not sure what to do about this, but at least
6462 // the race is now smaller.
6463 if (!success) {
6464 // Uh oh... it looks like the provider's process
6465 // has been killed on us. We need to wait for a new
6466 // process to be started, and make sure its death
6467 // doesn't kill our process.
6468 Slog.i(TAG,
6469 "Existing provider " + cpr.name.flattenToShortString()
6470 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006471 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006472 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006473 if (!lastRef) {
6474 // This wasn't the last ref our process had on
6475 // the provider... we have now been killed, bail.
6476 return null;
6477 }
6478 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006479 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 }
6482
6483 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006486 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006487 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006489 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006490 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006491 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 } catch (RemoteException ex) {
6493 }
6494 if (cpi == null) {
6495 return null;
6496 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006497 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6498 cpi.name, cpi.flags);
6499 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006500 userId = 0;
6501 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006502 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006503
Dianne Hackbornb424b632010-08-18 15:59:05 -07006504 String msg;
6505 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6506 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 }
6508
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006509 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006510 && !cpi.processName.equals("system")) {
6511 // If this content provider does not run in the system
6512 // process, and the system is not yet ready to run other
6513 // processes, then fail fast instead of hanging.
6514 throw new IllegalArgumentException(
6515 "Attempt to launch content provider before system ready");
6516 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006517
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006518 // Make sure that the user who owns this provider is started. If not,
6519 // we don't want to allow it to run.
6520 if (mStartedUsers.get(userId) == null) {
6521 Slog.w(TAG, "Unable to launch app "
6522 + cpi.applicationInfo.packageName + "/"
6523 + cpi.applicationInfo.uid + " for provider "
6524 + name + ": user " + userId + " is stopped");
6525 return null;
6526 }
6527
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006528 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006529 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 final boolean firstClass = cpr == null;
6531 if (firstClass) {
6532 try {
6533 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006534 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 getApplicationInfo(
6536 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006537 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006539 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 + cpi.name);
6541 return null;
6542 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006543 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006544 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 } catch (RemoteException ex) {
6546 // pm is in same process, this will never happen.
6547 }
6548 }
6549
6550 if (r != null && cpr.canRunHere(r)) {
6551 // If this is a multiprocess provider, then just return its
6552 // info and allow the caller to instantiate it. Only do
6553 // this if the provider is the same user as the caller's
6554 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006555 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 }
6557
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006558 if (DEBUG_PROVIDER) {
6559 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006560 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006561 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 }
6563
6564 // This is single process, and our app is now connecting to it.
6565 // See if we are already in the process of launching this
6566 // provider.
6567 final int N = mLaunchingProviders.size();
6568 int i;
6569 for (i=0; i<N; i++) {
6570 if (mLaunchingProviders.get(i) == cpr) {
6571 break;
6572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 }
6574
6575 // If the provider is not already being launched, then get it
6576 // started.
6577 if (i >= N) {
6578 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006579
6580 try {
6581 // Content provider is now in use, its package can't be stopped.
6582 try {
6583 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006584 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006585 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006586 } catch (IllegalArgumentException e) {
6587 Slog.w(TAG, "Failed trying to unstop package "
6588 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006589 }
6590
6591 ProcessRecord proc = startProcessLocked(cpi.processName,
6592 cpr.appInfo, false, 0, "content provider",
6593 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006594 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006595 if (proc == null) {
6596 Slog.w(TAG, "Unable to launch app "
6597 + cpi.applicationInfo.packageName + "/"
6598 + cpi.applicationInfo.uid + " for provider "
6599 + name + ": process is bad");
6600 return null;
6601 }
6602 cpr.launchingApp = proc;
6603 mLaunchingProviders.add(cpr);
6604 } finally {
6605 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 }
6608
6609 // Make sure the provider is published (the same provider class
6610 // may be published under multiple names).
6611 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006612 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006614
Amith Yamasani742a6712011-05-04 14:49:28 -07006615 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006616 conn = incProviderCountLocked(r, cpr, token, stable);
6617 if (conn != null) {
6618 conn.waiting = true;
6619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 }
6621 }
6622
6623 // Wait for the provider to be published...
6624 synchronized (cpr) {
6625 while (cpr.provider == null) {
6626 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006627 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 + cpi.applicationInfo.packageName + "/"
6629 + cpi.applicationInfo.uid + " for provider "
6630 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006631 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 cpi.applicationInfo.packageName,
6633 cpi.applicationInfo.uid, name);
6634 return null;
6635 }
6636 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006637 if (DEBUG_MU) {
6638 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6639 + cpr.launchingApp);
6640 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006641 if (conn != null) {
6642 conn.waiting = true;
6643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 cpr.wait();
6645 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006646 } finally {
6647 if (conn != null) {
6648 conn.waiting = false;
6649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 }
6651 }
6652 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006653 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 }
6655
6656 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006657 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006658 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 if (caller == null) {
6660 String msg = "null IApplicationThread when getting content provider "
6661 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006662 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 throw new SecurityException(msg);
6664 }
6665
Dianne Hackborn41203752012-08-31 14:05:51 -07006666 return getContentProviderImpl(caller, name, null, stable,
6667 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 }
6669
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006670 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6671 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6672 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006673 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006674 }
6675
Dianne Hackborn41203752012-08-31 14:05:51 -07006676 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6677 IBinder token, int userId) {
6678 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 }
6680
6681 /**
6682 * Drop a content provider from a ProcessRecord's bookkeeping
6683 * @param cpr
6684 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006685 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006686 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006688 ContentProviderConnection conn;
6689 try {
6690 conn = (ContentProviderConnection)connection;
6691 } catch (ClassCastException e) {
6692 String msg ="removeContentProvider: " + connection
6693 + " not a ContentProviderConnection";
6694 Slog.w(TAG, msg);
6695 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006697 if (conn == null) {
6698 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006700 if (decProviderCountLocked(conn, null, null, stable)) {
6701 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 }
6704 }
6705
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006706 public void removeContentProviderExternal(String name, IBinder token) {
6707 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6708 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006709 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006710 }
6711
Dianne Hackborn41203752012-08-31 14:05:51 -07006712 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006714 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 if(cpr == null) {
6716 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006717 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 return;
6719 }
6720
6721 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006722 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006723 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006724 if (localCpr.hasExternalProcessHandles()) {
6725 if (localCpr.removeExternalProcessHandleLocked(token)) {
6726 updateOomAdjLocked();
6727 } else {
6728 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6729 + " with no external reference for token: "
6730 + token + ".");
6731 }
6732 } else {
6733 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6734 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 }
6737 }
6738
6739 public final void publishContentProviders(IApplicationThread caller,
6740 List<ContentProviderHolder> providers) {
6741 if (providers == null) {
6742 return;
6743 }
6744
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006745 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006746 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006748 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006749 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 if (r == null) {
6751 throw new SecurityException(
6752 "Unable to find app for caller " + caller
6753 + " (pid=" + Binder.getCallingPid()
6754 + ") when publishing content providers");
6755 }
6756
6757 final long origId = Binder.clearCallingIdentity();
6758
6759 final int N = providers.size();
6760 for (int i=0; i<N; i++) {
6761 ContentProviderHolder src = providers.get(i);
6762 if (src == null || src.info == null || src.provider == null) {
6763 continue;
6764 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006765 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006766 if (DEBUG_MU)
6767 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006769 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006770 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 String names[] = dst.info.authority.split(";");
6772 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006773 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 }
6775
6776 int NL = mLaunchingProviders.size();
6777 int j;
6778 for (j=0; j<NL; j++) {
6779 if (mLaunchingProviders.get(j) == dst) {
6780 mLaunchingProviders.remove(j);
6781 j--;
6782 NL--;
6783 }
6784 }
6785 synchronized (dst) {
6786 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006787 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 dst.notifyAll();
6789 }
6790 updateOomAdjLocked(r);
6791 }
6792 }
6793
6794 Binder.restoreCallingIdentity(origId);
6795 }
6796 }
6797
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006798 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6799 ContentProviderConnection conn;
6800 try {
6801 conn = (ContentProviderConnection)connection;
6802 } catch (ClassCastException e) {
6803 String msg ="refContentProvider: " + connection
6804 + " not a ContentProviderConnection";
6805 Slog.w(TAG, msg);
6806 throw new IllegalArgumentException(msg);
6807 }
6808 if (conn == null) {
6809 throw new NullPointerException("connection is null");
6810 }
6811
6812 synchronized (this) {
6813 if (stable > 0) {
6814 conn.numStableIncs += stable;
6815 }
6816 stable = conn.stableCount + stable;
6817 if (stable < 0) {
6818 throw new IllegalStateException("stableCount < 0: " + stable);
6819 }
6820
6821 if (unstable > 0) {
6822 conn.numUnstableIncs += unstable;
6823 }
6824 unstable = conn.unstableCount + unstable;
6825 if (unstable < 0) {
6826 throw new IllegalStateException("unstableCount < 0: " + unstable);
6827 }
6828
6829 if ((stable+unstable) <= 0) {
6830 throw new IllegalStateException("ref counts can't go to zero here: stable="
6831 + stable + " unstable=" + unstable);
6832 }
6833 conn.stableCount = stable;
6834 conn.unstableCount = unstable;
6835 return !conn.dead;
6836 }
6837 }
6838
6839 public void unstableProviderDied(IBinder connection) {
6840 ContentProviderConnection conn;
6841 try {
6842 conn = (ContentProviderConnection)connection;
6843 } catch (ClassCastException e) {
6844 String msg ="refContentProvider: " + connection
6845 + " not a ContentProviderConnection";
6846 Slog.w(TAG, msg);
6847 throw new IllegalArgumentException(msg);
6848 }
6849 if (conn == null) {
6850 throw new NullPointerException("connection is null");
6851 }
6852
6853 // Safely retrieve the content provider associated with the connection.
6854 IContentProvider provider;
6855 synchronized (this) {
6856 provider = conn.provider.provider;
6857 }
6858
6859 if (provider == null) {
6860 // Um, yeah, we're way ahead of you.
6861 return;
6862 }
6863
6864 // Make sure the caller is being honest with us.
6865 if (provider.asBinder().pingBinder()) {
6866 // Er, no, still looks good to us.
6867 synchronized (this) {
6868 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6869 + " says " + conn + " died, but we don't agree");
6870 return;
6871 }
6872 }
6873
6874 // Well look at that! It's dead!
6875 synchronized (this) {
6876 if (conn.provider.provider != provider) {
6877 // But something changed... good enough.
6878 return;
6879 }
6880
6881 ProcessRecord proc = conn.provider.proc;
6882 if (proc == null || proc.thread == null) {
6883 // Seems like the process is already cleaned up.
6884 return;
6885 }
6886
6887 // As far as we're concerned, this is just like receiving a
6888 // death notification... just a bit prematurely.
6889 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6890 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006891 final long ident = Binder.clearCallingIdentity();
6892 try {
6893 appDiedLocked(proc, proc.pid, proc.thread);
6894 } finally {
6895 Binder.restoreCallingIdentity(ident);
6896 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006897 }
6898 }
6899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006901 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006902 synchronized (mSelf) {
6903 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6904 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006905 if (providers != null) {
6906 for (int i=providers.size()-1; i>=0; i--) {
6907 ProviderInfo pi = (ProviderInfo)providers.get(i);
6908 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6909 Slog.w(TAG, "Not installing system proc provider " + pi.name
6910 + ": not system .apk");
6911 providers.remove(i);
6912 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006913 }
6914 }
6915 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006916 if (providers != null) {
6917 mSystemThread.installSystemProviders(providers);
6918 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006919
6920 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006921
6922 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 }
6924
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006925 /**
6926 * Allows app to retrieve the MIME type of a URI without having permission
6927 * to access its content provider.
6928 *
6929 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6930 *
6931 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6932 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6933 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006934 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006935 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006936 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
6937 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006938 final String name = uri.getAuthority();
6939 final long ident = Binder.clearCallingIdentity();
6940 ContentProviderHolder holder = null;
6941
6942 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006943 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006944 if (holder != null) {
6945 return holder.provider.getType(uri);
6946 }
6947 } catch (RemoteException e) {
6948 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6949 return null;
6950 } finally {
6951 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006952 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006953 }
6954 Binder.restoreCallingIdentity(ident);
6955 }
6956
6957 return null;
6958 }
6959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 // =========================================================
6961 // GLOBAL MANAGEMENT
6962 // =========================================================
6963
6964 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006965 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 String proc = customProcess != null ? customProcess : info.processName;
6967 BatteryStatsImpl.Uid.Proc ps = null;
6968 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006969 int uid = info.uid;
6970 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006971 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006972 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6973 uid = 0;
6974 while (true) {
6975 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6976 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6977 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6978 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006979 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006980 mNextIsolatedProcessUid++;
6981 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6982 // No process for this uid, use it.
6983 break;
6984 }
6985 stepsLeft--;
6986 if (stepsLeft <= 0) {
6987 return null;
6988 }
6989 }
6990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 synchronized (stats) {
6992 ps = stats.getProcessStatsLocked(info.uid, proc);
6993 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006994 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006995 }
6996
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006997 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6998 ProcessRecord app;
6999 if (!isolated) {
7000 app = getProcessRecordLocked(info.processName, info.uid);
7001 } else {
7002 app = null;
7003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004
7005 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007006 app = newProcessRecordLocked(null, info, null, isolated);
7007 mProcessNames.put(info.processName, app.uid, app);
7008 if (isolated) {
7009 mIsolatedProcesses.put(app.uid, app);
7010 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007011 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 }
7013
Dianne Hackborne7f97212011-02-24 14:40:20 -08007014 // This package really, really can not be stopped.
7015 try {
7016 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007017 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007018 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007019 } catch (IllegalArgumentException e) {
7020 Slog.w(TAG, "Failed trying to unstop package "
7021 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007022 }
7023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7025 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7026 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007027 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 }
7029 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7030 mPersistentStartingProcesses.add(app);
7031 startProcessLocked(app, "added application", app.processName);
7032 }
7033
7034 return app;
7035 }
7036
7037 public void unhandledBack() {
7038 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7039 "unhandledBack()");
7040
7041 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007042 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007043 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 TAG, "Performing unhandledBack(): stack size = " + count);
7045 if (count > 1) {
7046 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007047 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007048 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 Binder.restoreCallingIdentity(origId);
7050 }
7051 }
7052 }
7053
7054 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007055 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007056 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007057 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007058 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 ParcelFileDescriptor pfd = null;
7060 if (cph != null) {
7061 // We record the binder invoker's uid in thread-local storage before
7062 // going to the content provider to open the file. Later, in the code
7063 // that handles all permissions checks, we look for this uid and use
7064 // that rather than the Activity Manager's own uid. The effect is that
7065 // we do the check against the caller's permissions even though it looks
7066 // to the content provider like the Activity Manager itself is making
7067 // the request.
7068 sCallerIdentity.set(new Identity(
7069 Binder.getCallingPid(), Binder.getCallingUid()));
7070 try {
7071 pfd = cph.provider.openFile(uri, "r");
7072 } catch (FileNotFoundException e) {
7073 // do nothing; pfd will be returned null
7074 } finally {
7075 // Ensure that whatever happens, we clean up the identity state
7076 sCallerIdentity.remove();
7077 }
7078
7079 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007080 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007082 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 }
7084 return pfd;
7085 }
7086
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007087 // Actually is sleeping or shutting down or whatever else in the future
7088 // is an inactive state.
7089 public boolean isSleeping() {
7090 return mSleeping || mShuttingDown;
7091 }
7092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007094 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7095 != PackageManager.PERMISSION_GRANTED) {
7096 throw new SecurityException("Requires permission "
7097 + android.Manifest.permission.DEVICE_POWER);
7098 }
7099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007101 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007102 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007104 if (!mSleeping) {
7105 mSleeping = true;
7106 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007107
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007108 // Initialize the wake times of all processes.
7109 checkExcessivePowerUsageLocked(false);
7110 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7111 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7112 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007114 }
7115 }
7116
Dianne Hackborn55280a92009-05-07 15:53:46 -07007117 public boolean shutdown(int timeout) {
7118 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7119 != PackageManager.PERMISSION_GRANTED) {
7120 throw new SecurityException("Requires permission "
7121 + android.Manifest.permission.SHUTDOWN);
7122 }
7123
7124 boolean timedout = false;
7125
7126 synchronized(this) {
7127 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007128 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007129
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007130 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007131 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007132 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007133 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007134 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007135 long delay = endTime - System.currentTimeMillis();
7136 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007137 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007138 timedout = true;
7139 break;
7140 }
7141 try {
7142 this.wait();
7143 } catch (InterruptedException e) {
7144 }
7145 }
7146 }
7147 }
7148
7149 mUsageStatsService.shutdown();
7150 mBatteryStatsService.shutdown();
7151
7152 return timedout;
7153 }
7154
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007155 public final void activitySlept(IBinder token) {
7156 if (localLOGV) Slog.v(
7157 TAG, "Activity slept: token=" + token);
7158
7159 ActivityRecord r = null;
7160
7161 final long origId = Binder.clearCallingIdentity();
7162
7163 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007164 r = mMainStack.isInStackLocked(token);
7165 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007166 mMainStack.activitySleptLocked(r);
7167 }
7168 }
7169
7170 Binder.restoreCallingIdentity(origId);
7171 }
7172
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007173 private void comeOutOfSleepIfNeededLocked() {
7174 if (!mWentToSleep && !mLockScreenShown) {
7175 if (mSleeping) {
7176 mSleeping = false;
7177 mMainStack.awakeFromSleepingLocked();
7178 mMainStack.resumeTopActivityLocked(null);
7179 }
7180 }
7181 }
7182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007184 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7185 != PackageManager.PERMISSION_GRANTED) {
7186 throw new SecurityException("Requires permission "
7187 + android.Manifest.permission.DEVICE_POWER);
7188 }
7189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007191 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007192 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007193 comeOutOfSleepIfNeededLocked();
7194 }
7195 }
7196
Jeff Brownc042ee22012-05-08 13:03:42 -07007197 private void updateEventDispatchingLocked() {
7198 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7199 }
7200
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007201 public void setLockScreenShown(boolean shown) {
7202 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7203 != PackageManager.PERMISSION_GRANTED) {
7204 throw new SecurityException("Requires permission "
7205 + android.Manifest.permission.DEVICE_POWER);
7206 }
7207
7208 synchronized(this) {
7209 mLockScreenShown = shown;
7210 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 }
7212 }
7213
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007214 public void stopAppSwitches() {
7215 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7216 != PackageManager.PERMISSION_GRANTED) {
7217 throw new SecurityException("Requires permission "
7218 + android.Manifest.permission.STOP_APP_SWITCHES);
7219 }
7220
7221 synchronized(this) {
7222 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7223 + APP_SWITCH_DELAY_TIME;
7224 mDidAppSwitch = false;
7225 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7226 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7227 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7228 }
7229 }
7230
7231 public void resumeAppSwitches() {
7232 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7233 != PackageManager.PERMISSION_GRANTED) {
7234 throw new SecurityException("Requires permission "
7235 + android.Manifest.permission.STOP_APP_SWITCHES);
7236 }
7237
7238 synchronized(this) {
7239 // Note that we don't execute any pending app switches... we will
7240 // let those wait until either the timeout, or the next start
7241 // activity request.
7242 mAppSwitchesAllowedTime = 0;
7243 }
7244 }
7245
7246 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7247 String name) {
7248 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7249 return true;
7250 }
7251
7252 final int perm = checkComponentPermission(
7253 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007254 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007255 if (perm == PackageManager.PERMISSION_GRANTED) {
7256 return true;
7257 }
7258
Joe Onorato8a9b2202010-02-26 18:56:32 -08007259 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007260 return false;
7261 }
7262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007263 public void setDebugApp(String packageName, boolean waitForDebugger,
7264 boolean persistent) {
7265 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7266 "setDebugApp()");
7267
7268 // Note that this is not really thread safe if there are multiple
7269 // callers into it at the same time, but that's not a situation we
7270 // care about.
7271 if (persistent) {
7272 final ContentResolver resolver = mContext.getContentResolver();
7273 Settings.System.putString(
7274 resolver, Settings.System.DEBUG_APP,
7275 packageName);
7276 Settings.System.putInt(
7277 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7278 waitForDebugger ? 1 : 0);
7279 }
7280
7281 synchronized (this) {
7282 if (!persistent) {
7283 mOrigDebugApp = mDebugApp;
7284 mOrigWaitForDebugger = mWaitForDebugger;
7285 }
7286 mDebugApp = packageName;
7287 mWaitForDebugger = waitForDebugger;
7288 mDebugTransient = !persistent;
7289 if (packageName != null) {
7290 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007291 forceStopPackageLocked(packageName, -1, false, false, true, true,
7292 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007293 Binder.restoreCallingIdentity(origId);
7294 }
7295 }
7296 }
7297
Siva Velusamy92a8b222012-03-09 16:24:04 -08007298 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7299 synchronized (this) {
7300 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7301 if (!isDebuggable) {
7302 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7303 throw new SecurityException("Process not debuggable: " + app.packageName);
7304 }
7305 }
7306
7307 mOpenGlTraceApp = processName;
7308 }
7309 }
7310
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007311 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7312 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7313 synchronized (this) {
7314 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7315 if (!isDebuggable) {
7316 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7317 throw new SecurityException("Process not debuggable: " + app.packageName);
7318 }
7319 }
7320 mProfileApp = processName;
7321 mProfileFile = profileFile;
7322 if (mProfileFd != null) {
7323 try {
7324 mProfileFd.close();
7325 } catch (IOException e) {
7326 }
7327 mProfileFd = null;
7328 }
7329 mProfileFd = profileFd;
7330 mProfileType = 0;
7331 mAutoStopProfiler = autoStopProfiler;
7332 }
7333 }
7334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 public void setAlwaysFinish(boolean enabled) {
7336 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7337 "setAlwaysFinish()");
7338
7339 Settings.System.putInt(
7340 mContext.getContentResolver(),
7341 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7342
7343 synchronized (this) {
7344 mAlwaysFinishActivities = enabled;
7345 }
7346 }
7347
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007348 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007350 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007352 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007353 }
7354 }
7355
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007356 public boolean isUserAMonkey() {
7357 // For now the fact that there is a controller implies
7358 // we have a monkey.
7359 synchronized (this) {
7360 return mController != null;
7361 }
7362 }
7363
Jeff Sharkeya4620792011-05-20 15:29:23 -07007364 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007365 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7366 "registerProcessObserver()");
7367 synchronized (this) {
7368 mProcessObservers.register(observer);
7369 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007370 }
7371
7372 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007373 synchronized (this) {
7374 mProcessObservers.unregister(observer);
7375 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007376 }
7377
Daniel Sandler69a48172010-06-23 16:29:36 -04007378 public void setImmersive(IBinder token, boolean immersive) {
7379 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007380 ActivityRecord r = mMainStack.isInStackLocked(token);
7381 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007382 throw new IllegalArgumentException();
7383 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007384 r.immersive = immersive;
7385 }
7386 }
7387
7388 public boolean isImmersive(IBinder token) {
7389 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007390 ActivityRecord r = mMainStack.isInStackLocked(token);
7391 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007392 throw new IllegalArgumentException();
7393 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007394 return r.immersive;
7395 }
7396 }
7397
7398 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007399 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007400 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007401 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007402 return (r != null) ? r.immersive : false;
7403 }
7404 }
7405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 public final void enterSafeMode() {
7407 synchronized(this) {
7408 // It only makes sense to do this before the system is ready
7409 // and started launching other packages.
7410 if (!mSystemReady) {
7411 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007412 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 } catch (RemoteException e) {
7414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 }
7416 }
7417 }
7418
Jeff Brownb09abc12011-01-13 21:08:27 -08007419 public final void showSafeModeOverlay() {
7420 View v = LayoutInflater.from(mContext).inflate(
7421 com.android.internal.R.layout.safe_mode, null);
7422 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7423 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7424 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7425 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007426 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007427 lp.format = v.getBackground().getOpacity();
7428 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7429 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7430 ((WindowManager)mContext.getSystemService(
7431 Context.WINDOW_SERVICE)).addView(v, lp);
7432 }
7433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 public void noteWakeupAlarm(IIntentSender sender) {
7435 if (!(sender instanceof PendingIntentRecord)) {
7436 return;
7437 }
7438 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7439 synchronized (stats) {
7440 if (mBatteryStatsService.isOnBattery()) {
7441 mBatteryStatsService.enforceCallingPermission();
7442 PendingIntentRecord rec = (PendingIntentRecord)sender;
7443 int MY_UID = Binder.getCallingUid();
7444 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7445 BatteryStatsImpl.Uid.Pkg pkg =
7446 stats.getPackageStatsLocked(uid, rec.key.packageName);
7447 pkg.incWakeupsLocked();
7448 }
7449 }
7450 }
7451
Dianne Hackborn64825172011-03-02 21:32:58 -08007452 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007453 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007454 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007456 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 // XXX Note: don't acquire main activity lock here, because the window
7458 // manager calls in with its locks held.
7459
7460 boolean killed = false;
7461 synchronized (mPidsSelfLocked) {
7462 int[] types = new int[pids.length];
7463 int worstType = 0;
7464 for (int i=0; i<pids.length; i++) {
7465 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7466 if (proc != null) {
7467 int type = proc.setAdj;
7468 types[i] = type;
7469 if (type > worstType) {
7470 worstType = type;
7471 }
7472 }
7473 }
7474
Dianne Hackborn64825172011-03-02 21:32:58 -08007475 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007477 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7478 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007479 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007481
7482 // If this is not a secure call, don't let it kill processes that
7483 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007484 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7485 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007486 }
7487
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007488 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 for (int i=0; i<pids.length; i++) {
7490 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7491 if (proc == null) {
7492 continue;
7493 }
7494 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007495 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007496 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007497 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7498 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007500 proc.killedBackground = true;
7501 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 }
7503 }
7504 }
7505 return killed;
7506 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007507
7508 @Override
7509 public boolean killProcessesBelowForeground(String reason) {
7510 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7511 throw new SecurityException("killProcessesBelowForeground() only available to system");
7512 }
7513
7514 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7515 }
7516
7517 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7518 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7519 throw new SecurityException("killProcessesBelowAdj() only available to system");
7520 }
7521
7522 boolean killed = false;
7523 synchronized (mPidsSelfLocked) {
7524 final int size = mPidsSelfLocked.size();
7525 for (int i = 0; i < size; i++) {
7526 final int pid = mPidsSelfLocked.keyAt(i);
7527 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7528 if (proc == null) continue;
7529
7530 final int adj = proc.setAdj;
7531 if (adj > belowAdj && !proc.killedBackground) {
7532 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7533 EventLog.writeEvent(
7534 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7535 killed = true;
7536 proc.killedBackground = true;
7537 Process.killProcessQuiet(pid);
7538 }
7539 }
7540 }
7541 return killed;
7542 }
7543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 public final void startRunning(String pkg, String cls, String action,
7545 String data) {
7546 synchronized(this) {
7547 if (mStartRunning) {
7548 return;
7549 }
7550 mStartRunning = true;
7551 mTopComponent = pkg != null && cls != null
7552 ? new ComponentName(pkg, cls) : null;
7553 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7554 mTopData = data;
7555 if (!mSystemReady) {
7556 return;
7557 }
7558 }
7559
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007560 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 }
7562
7563 private void retrieveSettings() {
7564 final ContentResolver resolver = mContext.getContentResolver();
7565 String debugApp = Settings.System.getString(
7566 resolver, Settings.System.DEBUG_APP);
7567 boolean waitForDebugger = Settings.System.getInt(
7568 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7569 boolean alwaysFinishActivities = Settings.System.getInt(
7570 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7571
7572 Configuration configuration = new Configuration();
7573 Settings.System.getConfiguration(resolver, configuration);
7574
7575 synchronized (this) {
7576 mDebugApp = mOrigDebugApp = debugApp;
7577 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7578 mAlwaysFinishActivities = alwaysFinishActivities;
7579 // This happens before any activities are started, so we can
7580 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007581 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007582 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
7584 }
7585
7586 public boolean testIsSystemReady() {
7587 // no need to synchronize(this) just to read & return the value
7588 return mSystemReady;
7589 }
7590
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007591 private static File getCalledPreBootReceiversFile() {
7592 File dataDir = Environment.getDataDirectory();
7593 File systemDir = new File(dataDir, "system");
7594 File fname = new File(systemDir, "called_pre_boots.dat");
7595 return fname;
7596 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007597
7598 static final int LAST_DONE_VERSION = 10000;
7599
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007600 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7601 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7602 File file = getCalledPreBootReceiversFile();
7603 FileInputStream fis = null;
7604 try {
7605 fis = new FileInputStream(file);
7606 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007607 int fvers = dis.readInt();
7608 if (fvers == LAST_DONE_VERSION) {
7609 String vers = dis.readUTF();
7610 String codename = dis.readUTF();
7611 String build = dis.readUTF();
7612 if (android.os.Build.VERSION.RELEASE.equals(vers)
7613 && android.os.Build.VERSION.CODENAME.equals(codename)
7614 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7615 int num = dis.readInt();
7616 while (num > 0) {
7617 num--;
7618 String pkg = dis.readUTF();
7619 String cls = dis.readUTF();
7620 lastDoneReceivers.add(new ComponentName(pkg, cls));
7621 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007622 }
7623 }
7624 } catch (FileNotFoundException e) {
7625 } catch (IOException e) {
7626 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7627 } finally {
7628 if (fis != null) {
7629 try {
7630 fis.close();
7631 } catch (IOException e) {
7632 }
7633 }
7634 }
7635 return lastDoneReceivers;
7636 }
7637
7638 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7639 File file = getCalledPreBootReceiversFile();
7640 FileOutputStream fos = null;
7641 DataOutputStream dos = null;
7642 try {
7643 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7644 fos = new FileOutputStream(file);
7645 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007646 dos.writeInt(LAST_DONE_VERSION);
7647 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007648 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007649 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007650 dos.writeInt(list.size());
7651 for (int i=0; i<list.size(); i++) {
7652 dos.writeUTF(list.get(i).getPackageName());
7653 dos.writeUTF(list.get(i).getClassName());
7654 }
7655 } catch (IOException e) {
7656 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7657 file.delete();
7658 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007659 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007660 if (dos != null) {
7661 try {
7662 dos.close();
7663 } catch (IOException e) {
7664 // TODO Auto-generated catch block
7665 e.printStackTrace();
7666 }
7667 }
7668 }
7669 }
7670
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007671 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 synchronized(this) {
7673 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007674 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 return;
7676 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007677
7678 // Check to see if there are any update receivers to run.
7679 if (!mDidUpdate) {
7680 if (mWaitingUpdate) {
7681 return;
7682 }
7683 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7684 List<ResolveInfo> ris = null;
7685 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007686 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007687 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007688 } catch (RemoteException e) {
7689 }
7690 if (ris != null) {
7691 for (int i=ris.size()-1; i>=0; i--) {
7692 if ((ris.get(i).activityInfo.applicationInfo.flags
7693 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7694 ris.remove(i);
7695 }
7696 }
7697 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007698
7699 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7700
7701 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007702 for (int i=0; i<ris.size(); i++) {
7703 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007704 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7705 if (lastDoneReceivers.contains(comp)) {
7706 ris.remove(i);
7707 i--;
7708 }
7709 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007710
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007711 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007712 for (int i=0; i<ris.size(); i++) {
7713 ActivityInfo ai = ris.get(i).activityInfo;
7714 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7715 doneReceivers.add(comp);
7716 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007717 for (int j=0; j<users.length; j++) {
7718 IIntentReceiver finisher = null;
7719 if (i == ris.size()-1 && j == users.length-1) {
7720 finisher = new IIntentReceiver.Stub() {
7721 public void performReceive(Intent intent, int resultCode,
7722 String data, Bundle extras, boolean ordered,
7723 boolean sticky, int sendingUser) {
7724 // The raw IIntentReceiver interface is called
7725 // with the AM lock held, so redispatch to
7726 // execute our code without the lock.
7727 mHandler.post(new Runnable() {
7728 public void run() {
7729 synchronized (ActivityManagerService.this) {
7730 mDidUpdate = true;
7731 }
7732 writeLastDonePreBootReceivers(doneReceivers);
7733 showBootMessage(mContext.getText(
7734 R.string.android_upgrading_complete),
7735 false);
7736 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007737 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007738 });
7739 }
7740 };
7741 }
7742 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7743 + " for user " + users[j]);
7744 broadcastIntentLocked(null, null, intent, null, finisher,
7745 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7746 users[j]);
7747 if (finisher != null) {
7748 mWaitingUpdate = true;
7749 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007750 }
7751 }
7752 }
7753 if (mWaitingUpdate) {
7754 return;
7755 }
7756 mDidUpdate = true;
7757 }
7758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 mSystemReady = true;
7760 if (!mStartRunning) {
7761 return;
7762 }
7763 }
7764
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007765 ArrayList<ProcessRecord> procsToKill = null;
7766 synchronized(mPidsSelfLocked) {
7767 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7768 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7769 if (!isAllowedWhileBooting(proc.info)){
7770 if (procsToKill == null) {
7771 procsToKill = new ArrayList<ProcessRecord>();
7772 }
7773 procsToKill.add(proc);
7774 }
7775 }
7776 }
7777
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007778 synchronized(this) {
7779 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007780 for (int i=procsToKill.size()-1; i>=0; i--) {
7781 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007782 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007783 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007784 }
7785 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007786
7787 // Now that we have cleaned up any update processes, we
7788 // are ready to start launching real processes and know that
7789 // we won't trample on them any more.
7790 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007791 }
7792
Joe Onorato8a9b2202010-02-26 18:56:32 -08007793 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007794 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 SystemClock.uptimeMillis());
7796
7797 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007798 // Make sure we have no pre-ready processes sitting around.
7799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7801 ResolveInfo ri = mContext.getPackageManager()
7802 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007803 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 CharSequence errorMsg = null;
7805 if (ri != null) {
7806 ActivityInfo ai = ri.activityInfo;
7807 ApplicationInfo app = ai.applicationInfo;
7808 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7809 mTopAction = Intent.ACTION_FACTORY_TEST;
7810 mTopData = null;
7811 mTopComponent = new ComponentName(app.packageName,
7812 ai.name);
7813 } else {
7814 errorMsg = mContext.getResources().getText(
7815 com.android.internal.R.string.factorytest_not_system);
7816 }
7817 } else {
7818 errorMsg = mContext.getResources().getText(
7819 com.android.internal.R.string.factorytest_no_action);
7820 }
7821 if (errorMsg != null) {
7822 mTopAction = null;
7823 mTopData = null;
7824 mTopComponent = null;
7825 Message msg = Message.obtain();
7826 msg.what = SHOW_FACTORY_ERROR_MSG;
7827 msg.getData().putCharSequence("msg", errorMsg);
7828 mHandler.sendMessage(msg);
7829 }
7830 }
7831 }
7832
7833 retrieveSettings();
7834
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007835 if (goingCallback != null) goingCallback.run();
7836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 synchronized (this) {
7838 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7839 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007840 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007841 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 if (apps != null) {
7843 int N = apps.size();
7844 int i;
7845 for (i=0; i<N; i++) {
7846 ApplicationInfo info
7847 = (ApplicationInfo)apps.get(i);
7848 if (info != null &&
7849 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007850 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 }
7852 }
7853 }
7854 } catch (RemoteException ex) {
7855 // pm is in same process, this will never happen.
7856 }
7857 }
7858
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007859 // Start up initial activity.
7860 mBooting = true;
7861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007863 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 Message msg = Message.obtain();
7865 msg.what = SHOW_UID_ERROR_MSG;
7866 mHandler.sendMessage(msg);
7867 }
7868 } catch (RemoteException e) {
7869 }
7870
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007871 long ident = Binder.clearCallingIdentity();
7872 try {
7873 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7874 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7875 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7876 broadcastIntentLocked(null, null, intent,
7877 null, null, 0, null, null, null,
7878 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
7879 } finally {
7880 Binder.restoreCallingIdentity(ident);
7881 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007882 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007883 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 }
7885 }
7886
Dan Egnorb7f03672009-12-09 16:22:32 -08007887 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007888 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007890 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007891 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 startAppProblemLocked(app);
7893 app.stopFreezingAllLocked();
7894 return handleAppCrashLocked(app);
7895 }
7896
Dan Egnorb7f03672009-12-09 16:22:32 -08007897 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007898 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007900 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007901 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7902 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 startAppProblemLocked(app);
7904 app.stopFreezingAllLocked();
7905 }
7906
7907 /**
7908 * Generate a process error record, suitable for attachment to a ProcessRecord.
7909 *
7910 * @param app The ProcessRecord in which the error occurred.
7911 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7912 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007913 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 * @param shortMsg Short message describing the crash.
7915 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007916 * @param stackTrace Full crash stack trace, may be null.
7917 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 * @return Returns a fully-formed AppErrorStateInfo record.
7919 */
7920 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007921 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 report.condition = condition;
7925 report.processName = app.processName;
7926 report.pid = app.pid;
7927 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007928 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 report.shortMsg = shortMsg;
7930 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007931 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007932
7933 return report;
7934 }
7935
Dan Egnor42471dd2010-01-07 17:25:22 -08007936 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 synchronized (this) {
7938 app.crashing = false;
7939 app.crashingReport = null;
7940 app.notResponding = false;
7941 app.notRespondingReport = null;
7942 if (app.anrDialog == fromDialog) {
7943 app.anrDialog = null;
7944 }
7945 if (app.waitDialog == fromDialog) {
7946 app.waitDialog = null;
7947 }
7948 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007949 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007950 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007951 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7952 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007953 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 }
7956 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007957
Dan Egnorb7f03672009-12-09 16:22:32 -08007958 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007959 if (mHeadless) {
7960 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7961 return false;
7962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 long now = SystemClock.uptimeMillis();
7964
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007965 Long crashTime;
7966 if (!app.isolated) {
7967 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7968 } else {
7969 crashTime = null;
7970 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007971 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007973 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007975 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007976 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007977 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7978 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007980 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007982 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7983 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 }
7985 }
7986 if (!app.persistent) {
7987 // We don't want to start this process again until the user
7988 // explicitly does so... but for persistent process, we really
7989 // need to keep it running. If a persistent process is actually
7990 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007991 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007993 if (!app.isolated) {
7994 // XXX We don't have a way to mark isolated processes
7995 // as bad, since they don't have a peristent identity.
7996 mBadProcesses.put(app.info.processName, app.uid, now);
7997 mProcessCrashTimes.remove(app.info.processName, app.uid);
7998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008001 // Don't let services in this process be restarted and potentially
8002 // annoy the user repeatedly. Unless it is persistent, since those
8003 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008004 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008005 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 return false;
8007 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008008 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008009 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008010 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008011 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008012 // If the top running activity is from this crashing
8013 // process, then terminate it to avoid getting in a loop.
8014 Slog.w(TAG, " Force finishing activity "
8015 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008016 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008017 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008018 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008019 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008020 // stopped, to avoid a situation where one will get
8021 // re-start our crashing activity once it gets resumed again.
8022 index--;
8023 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008024 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008025 if (r.state == ActivityState.RESUMED
8026 || r.state == ActivityState.PAUSING
8027 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008028 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008029 Slog.w(TAG, " Force finishing activity "
8030 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008031 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008032 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008033 }
8034 }
8035 }
8036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 }
8038
8039 // Bump up the crash count of any services currently running in the proc.
8040 if (app.services.size() != 0) {
8041 // Any services running in the application need to be placed
8042 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008043 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008045 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 sr.crashCount++;
8047 }
8048 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008049
8050 // If the crashing process is what we consider to be the "home process" and it has been
8051 // replaced by a third-party app, clear the package preferred activities from packages
8052 // with a home activity running in the process to prevent a repeatedly crashing app
8053 // from blocking the user to manually clear the list.
8054 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8055 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8056 Iterator it = mHomeProcess.activities.iterator();
8057 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008058 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008059 if (r.isHomeActivity) {
8060 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8061 try {
8062 ActivityThread.getPackageManager()
8063 .clearPackagePreferredActivities(r.packageName);
8064 } catch (RemoteException c) {
8065 // pm is in same process, this will never happen.
8066 }
8067 }
8068 }
8069 }
8070
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008071 if (!app.isolated) {
8072 // XXX Can't keep track of crash times for isolated processes,
8073 // because they don't have a perisistent identity.
8074 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8075 }
8076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 return true;
8078 }
8079
8080 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008081 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8082 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 skipCurrentReceiverLocked(app);
8084 }
8085
8086 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008087 for (BroadcastQueue queue : mBroadcastQueues) {
8088 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 }
8090 }
8091
Dan Egnor60d87622009-12-16 16:32:58 -08008092 /**
8093 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8094 * The application process will exit immediately after this call returns.
8095 * @param app object of the crashing app, null for the system server
8096 * @param crashInfo describing the exception
8097 */
8098 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008099 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008100 final String processName = app == null ? "system_server"
8101 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008102
8103 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008104 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008105 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008106 crashInfo.exceptionClassName,
8107 crashInfo.exceptionMessage,
8108 crashInfo.throwFileName,
8109 crashInfo.throwLineNumber);
8110
Jeff Sharkeya353d262011-10-28 11:12:06 -07008111 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008112
8113 crashApplication(r, crashInfo);
8114 }
8115
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008116 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008117 IBinder app,
8118 int violationMask,
8119 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008120 ProcessRecord r = findAppProcess(app, "StrictMode");
8121 if (r == null) {
8122 return;
8123 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008124
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008125 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008126 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008127 boolean logIt = true;
8128 synchronized (mAlreadyLoggedViolatedStacks) {
8129 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8130 logIt = false;
8131 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008132 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008133 // the relative pain numbers, without logging all
8134 // the stack traces repeatedly. We'd want to do
8135 // likewise in the client code, which also does
8136 // dup suppression, before the Binder call.
8137 } else {
8138 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8139 mAlreadyLoggedViolatedStacks.clear();
8140 }
8141 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8142 }
8143 }
8144 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008145 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008146 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008147 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008148
8149 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8150 AppErrorResult result = new AppErrorResult();
8151 synchronized (this) {
8152 final long origId = Binder.clearCallingIdentity();
8153
8154 Message msg = Message.obtain();
8155 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8156 HashMap<String, Object> data = new HashMap<String, Object>();
8157 data.put("result", result);
8158 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008159 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008160 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008161 msg.obj = data;
8162 mHandler.sendMessage(msg);
8163
8164 Binder.restoreCallingIdentity(origId);
8165 }
8166 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008167 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008168 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008169 }
8170
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008171 // Depending on the policy in effect, there could be a bunch of
8172 // these in quick succession so we try to batch these together to
8173 // minimize disk writes, number of dropbox entries, and maximize
8174 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008175 private void logStrictModeViolationToDropBox(
8176 ProcessRecord process,
8177 StrictMode.ViolationInfo info) {
8178 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008179 return;
8180 }
8181 final boolean isSystemApp = process == null ||
8182 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8183 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008184 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008185 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8186 final DropBoxManager dbox = (DropBoxManager)
8187 mContext.getSystemService(Context.DROPBOX_SERVICE);
8188
8189 // Exit early if the dropbox isn't configured to accept this report type.
8190 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8191
8192 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008193 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008194 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8195 synchronized (sb) {
8196 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008197 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008198 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8199 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008200 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8201 if (info.violationNumThisLoop != 0) {
8202 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8203 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008204 if (info.numAnimationsRunning != 0) {
8205 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8206 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008207 if (info.broadcastIntentAction != null) {
8208 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8209 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008210 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008211 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008212 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008213 if (info.numInstances != -1) {
8214 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8215 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008216 if (info.tags != null) {
8217 for (String tag : info.tags) {
8218 sb.append("Span-Tag: ").append(tag).append("\n");
8219 }
8220 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008221 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008222 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8223 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008224 }
8225 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008226
8227 // Only buffer up to ~64k. Various logging bits truncate
8228 // things at 128k.
8229 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008230 }
8231
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008232 // Flush immediately if the buffer's grown too large, or this
8233 // is a non-system app. Non-system apps are isolated with a
8234 // different tag & policy and not batched.
8235 //
8236 // Batching is useful during internal testing with
8237 // StrictMode settings turned up high. Without batching,
8238 // thousands of separate files could be created on boot.
8239 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008240 new Thread("Error dump: " + dropboxTag) {
8241 @Override
8242 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008243 String report;
8244 synchronized (sb) {
8245 report = sb.toString();
8246 sb.delete(0, sb.length());
8247 sb.trimToSize();
8248 }
8249 if (report.length() != 0) {
8250 dbox.addText(dropboxTag, report);
8251 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008252 }
8253 }.start();
8254 return;
8255 }
8256
8257 // System app batching:
8258 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008259 // An existing dropbox-writing thread is outstanding, so
8260 // we don't need to start it up. The existing thread will
8261 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008262 return;
8263 }
8264
8265 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8266 // (After this point, we shouldn't access AMS internal data structures.)
8267 new Thread("Error dump: " + dropboxTag) {
8268 @Override
8269 public void run() {
8270 // 5 second sleep to let stacks arrive and be batched together
8271 try {
8272 Thread.sleep(5000); // 5 seconds
8273 } catch (InterruptedException e) {}
8274
8275 String errorReport;
8276 synchronized (mStrictModeBuffer) {
8277 errorReport = mStrictModeBuffer.toString();
8278 if (errorReport.length() == 0) {
8279 return;
8280 }
8281 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8282 mStrictModeBuffer.trimToSize();
8283 }
8284 dbox.addText(dropboxTag, errorReport);
8285 }
8286 }.start();
8287 }
8288
Dan Egnor60d87622009-12-16 16:32:58 -08008289 /**
8290 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8291 * @param app object of the crashing app, null for the system server
8292 * @param tag reported by the caller
8293 * @param crashInfo describing the context of the error
8294 * @return true if the process should exit immediately (WTF is fatal)
8295 */
8296 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008297 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008298 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008299 final String processName = app == null ? "system_server"
8300 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008301
8302 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008303 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008304 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008305 tag, crashInfo.exceptionMessage);
8306
Jeff Sharkeya353d262011-10-28 11:12:06 -07008307 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008308
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008309 if (r != null && r.pid != Process.myPid() &&
8310 Settings.Secure.getInt(mContext.getContentResolver(),
8311 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008312 crashApplication(r, crashInfo);
8313 return true;
8314 } else {
8315 return false;
8316 }
8317 }
8318
8319 /**
8320 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8321 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8322 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008323 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008324 if (app == null) {
8325 return null;
8326 }
8327
8328 synchronized (this) {
8329 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8330 final int NA = apps.size();
8331 for (int ia=0; ia<NA; ia++) {
8332 ProcessRecord p = apps.valueAt(ia);
8333 if (p.thread != null && p.thread.asBinder() == app) {
8334 return p;
8335 }
8336 }
8337 }
8338
Dianne Hackborncb44d962011-03-10 17:02:27 -08008339 Slog.w(TAG, "Can't find mystery application for " + reason
8340 + " from pid=" + Binder.getCallingPid()
8341 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008342 return null;
8343 }
8344 }
8345
8346 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008347 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8348 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008349 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008350 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8351 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008352 // Watchdog thread ends up invoking this function (with
8353 // a null ProcessRecord) to add the stack file to dropbox.
8354 // Do not acquire a lock on this (am) in such cases, as it
8355 // could cause a potential deadlock, if and when watchdog
8356 // is invoked due to unavailability of lock on am and it
8357 // would prevent watchdog from killing system_server.
8358 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008359 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008360 return;
8361 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008362 // Note: ProcessRecord 'process' is guarded by the service
8363 // instance. (notably process.pkgList, which could otherwise change
8364 // concurrently during execution of this method)
8365 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008366 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008367 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008368 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008369 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8370 for (String pkg : process.pkgList) {
8371 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008372 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008373 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008374 if (pi != null) {
8375 sb.append(" v").append(pi.versionCode);
8376 if (pi.versionName != null) {
8377 sb.append(" (").append(pi.versionName).append(")");
8378 }
8379 }
8380 } catch (RemoteException e) {
8381 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008382 }
Dan Egnora455d192010-03-12 08:52:28 -08008383 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008384 }
Dan Egnora455d192010-03-12 08:52:28 -08008385 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008386 }
8387
8388 private static String processClass(ProcessRecord process) {
8389 if (process == null || process.pid == MY_PID) {
8390 return "system_server";
8391 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8392 return "system_app";
8393 } else {
8394 return "data_app";
8395 }
8396 }
8397
8398 /**
8399 * Write a description of an error (crash, WTF, ANR) to the drop box.
8400 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8401 * @param process which caused the error, null means the system server
8402 * @param activity which triggered the error, null if unknown
8403 * @param parent activity related to the error, null if unknown
8404 * @param subject line related to the error, null if absent
8405 * @param report in long form describing the error, null if absent
8406 * @param logFile to include in the report, null if none
8407 * @param crashInfo giving an application stack trace, null if absent
8408 */
8409 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008410 ProcessRecord process, String processName, ActivityRecord activity,
8411 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008412 final String report, final File logFile,
8413 final ApplicationErrorReport.CrashInfo crashInfo) {
8414 // NOTE -- this must never acquire the ActivityManagerService lock,
8415 // otherwise the watchdog may be prevented from resetting the system.
8416
8417 final String dropboxTag = processClass(process) + "_" + eventType;
8418 final DropBoxManager dbox = (DropBoxManager)
8419 mContext.getSystemService(Context.DROPBOX_SERVICE);
8420
8421 // Exit early if the dropbox isn't configured to accept this report type.
8422 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8423
8424 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008425 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008426 if (activity != null) {
8427 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8428 }
8429 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8430 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8431 }
8432 if (parent != null && parent != activity) {
8433 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8434 }
8435 if (subject != null) {
8436 sb.append("Subject: ").append(subject).append("\n");
8437 }
8438 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008439 if (Debug.isDebuggerConnected()) {
8440 sb.append("Debugger: Connected\n");
8441 }
Dan Egnora455d192010-03-12 08:52:28 -08008442 sb.append("\n");
8443
8444 // Do the rest in a worker thread to avoid blocking the caller on I/O
8445 // (After this point, we shouldn't access AMS internal data structures.)
8446 Thread worker = new Thread("Error dump: " + dropboxTag) {
8447 @Override
8448 public void run() {
8449 if (report != null) {
8450 sb.append(report);
8451 }
8452 if (logFile != null) {
8453 try {
8454 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8455 } catch (IOException e) {
8456 Slog.e(TAG, "Error reading " + logFile, e);
8457 }
8458 }
8459 if (crashInfo != null && crashInfo.stackTrace != null) {
8460 sb.append(crashInfo.stackTrace);
8461 }
8462
8463 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8464 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8465 if (lines > 0) {
8466 sb.append("\n");
8467
8468 // Merge several logcat streams, and take the last N lines
8469 InputStreamReader input = null;
8470 try {
8471 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8472 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8473 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8474
8475 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8476 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8477 input = new InputStreamReader(logcat.getInputStream());
8478
8479 int num;
8480 char[] buf = new char[8192];
8481 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8482 } catch (IOException e) {
8483 Slog.e(TAG, "Error running logcat", e);
8484 } finally {
8485 if (input != null) try { input.close(); } catch (IOException e) {}
8486 }
8487 }
8488
8489 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008490 }
Dan Egnora455d192010-03-12 08:52:28 -08008491 };
8492
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008493 if (process == null) {
8494 // If process is null, we are being called from some internal code
8495 // and may be about to die -- run this synchronously.
8496 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008497 } else {
8498 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008499 }
8500 }
8501
8502 /**
8503 * Bring up the "unexpected error" dialog box for a crashing app.
8504 * Deal with edge cases (intercepts from instrumented applications,
8505 * ActivityController, error intent receivers, that sort of thing).
8506 * @param r the application crashing
8507 * @param crashInfo describing the failure
8508 */
8509 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008510 long timeMillis = System.currentTimeMillis();
8511 String shortMsg = crashInfo.exceptionClassName;
8512 String longMsg = crashInfo.exceptionMessage;
8513 String stackTrace = crashInfo.stackTrace;
8514 if (shortMsg != null && longMsg != null) {
8515 longMsg = shortMsg + ": " + longMsg;
8516 } else if (shortMsg != null) {
8517 longMsg = shortMsg;
8518 }
8519
Dan Egnor60d87622009-12-16 16:32:58 -08008520 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008522 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 try {
8524 String name = r != null ? r.processName : null;
8525 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008526 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008527 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008528 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008529 + " at watcher's request");
8530 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008531 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008532 }
8533 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008534 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008535 }
8536 }
8537
8538 final long origId = Binder.clearCallingIdentity();
8539
8540 // If this process is running instrumentation, finish it.
8541 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008542 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008544 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8545 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 Bundle info = new Bundle();
8547 info.putString("shortMsg", shortMsg);
8548 info.putString("longMsg", longMsg);
8549 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8550 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008551 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 }
8553
Dan Egnor60d87622009-12-16 16:32:58 -08008554 // If we can't identify the process or it's already exceeded its crash quota,
8555 // quit right away without showing a crash dialog.
8556 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008558 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 }
8560
8561 Message msg = Message.obtain();
8562 msg.what = SHOW_ERROR_MSG;
8563 HashMap data = new HashMap();
8564 data.put("result", result);
8565 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 msg.obj = data;
8567 mHandler.sendMessage(msg);
8568
8569 Binder.restoreCallingIdentity(origId);
8570 }
8571
8572 int res = result.get();
8573
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008574 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008576 if (r != null && !r.isolated) {
8577 // XXX Can't keep track of crash time for isolated processes,
8578 // since they don't have a persistent identity.
8579 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 SystemClock.uptimeMillis());
8581 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008582 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008583 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008584 }
8585 }
8586
8587 if (appErrorIntent != null) {
8588 try {
8589 mContext.startActivity(appErrorIntent);
8590 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008591 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008594 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008595
8596 Intent createAppErrorIntentLocked(ProcessRecord r,
8597 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8598 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008599 if (report == null) {
8600 return null;
8601 }
8602 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8603 result.setComponent(r.errorReportReceiver);
8604 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8605 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8606 return result;
8607 }
8608
Dan Egnorb7f03672009-12-09 16:22:32 -08008609 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8610 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008611 if (r.errorReportReceiver == null) {
8612 return null;
8613 }
8614
8615 if (!r.crashing && !r.notResponding) {
8616 return null;
8617 }
8618
Dan Egnorb7f03672009-12-09 16:22:32 -08008619 ApplicationErrorReport report = new ApplicationErrorReport();
8620 report.packageName = r.info.packageName;
8621 report.installerPackageName = r.errorReportReceiver.getPackageName();
8622 report.processName = r.processName;
8623 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008624 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008625
Dan Egnorb7f03672009-12-09 16:22:32 -08008626 if (r.crashing) {
8627 report.type = ApplicationErrorReport.TYPE_CRASH;
8628 report.crashInfo = crashInfo;
8629 } else if (r.notResponding) {
8630 report.type = ApplicationErrorReport.TYPE_ANR;
8631 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008632
Dan Egnorb7f03672009-12-09 16:22:32 -08008633 report.anrInfo.activity = r.notRespondingReport.tag;
8634 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8635 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008636 }
8637
Dan Egnorb7f03672009-12-09 16:22:32 -08008638 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008639 }
8640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008642 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 // assume our apps are happy - lazy create the list
8644 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8645
Dianne Hackborn0c380492012-08-20 17:23:30 -07008646 final boolean allUsers = ActivityManager.checkUidPermission(
8647 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8648 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8649 int userId = UserHandle.getUserId(Binder.getCallingUid());
8650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 synchronized (this) {
8652
8653 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008654 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8655 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008656 if (!allUsers && app.userId != userId) {
8657 continue;
8658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8660 // This one's in trouble, so we'll generate a report for it
8661 // crashes are higher priority (in case there's a crash *and* an anr)
8662 ActivityManager.ProcessErrorStateInfo report = null;
8663 if (app.crashing) {
8664 report = app.crashingReport;
8665 } else if (app.notResponding) {
8666 report = app.notRespondingReport;
8667 }
8668
8669 if (report != null) {
8670 if (errList == null) {
8671 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8672 }
8673 errList.add(report);
8674 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008675 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 " crashing = " + app.crashing +
8677 " notResponding = " + app.notResponding);
8678 }
8679 }
8680 }
8681 }
8682
8683 return errList;
8684 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008685
8686 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008687 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008688 if (currApp != null) {
8689 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8690 }
8691 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008692 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8693 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008694 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8695 if (currApp != null) {
8696 currApp.lru = 0;
8697 }
8698 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008699 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008700 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8701 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8702 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8703 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8704 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8705 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8706 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8707 } else {
8708 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8709 }
8710 }
8711
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008712 private void fillInProcMemInfo(ProcessRecord app,
8713 ActivityManager.RunningAppProcessInfo outInfo) {
8714 outInfo.pid = app.pid;
8715 outInfo.uid = app.info.uid;
8716 if (mHeavyWeightProcess == app) {
8717 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8718 }
8719 if (app.persistent) {
8720 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8721 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008722 if (app.hasActivities) {
8723 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8724 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008725 outInfo.lastTrimLevel = app.trimMemoryLevel;
8726 int adj = app.curAdj;
8727 outInfo.importance = oomAdjToImportance(adj, outInfo);
8728 outInfo.importanceReasonCode = app.adjTypeCode;
8729 }
8730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008732 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 // Lazy instantiation of list
8734 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008735 final boolean allUsers = ActivityManager.checkUidPermission(
8736 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8737 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8738 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 synchronized (this) {
8740 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008741 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8742 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008743 if (!allUsers && app.userId != userId) {
8744 continue;
8745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8747 // Generate process state info for running application
8748 ActivityManager.RunningAppProcessInfo currApp =
8749 new ActivityManager.RunningAppProcessInfo(app.processName,
8750 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008751 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008752 if (app.adjSource instanceof ProcessRecord) {
8753 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008754 currApp.importanceReasonImportance = oomAdjToImportance(
8755 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008756 } else if (app.adjSource instanceof ActivityRecord) {
8757 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008758 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8759 }
8760 if (app.adjTarget instanceof ComponentName) {
8761 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8762 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008763 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 // + " lru=" + currApp.lru);
8765 if (runList == null) {
8766 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8767 }
8768 runList.add(currApp);
8769 }
8770 }
8771 }
8772 return runList;
8773 }
8774
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008775 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008776 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008777 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8778 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8779 if (runningApps != null && runningApps.size() > 0) {
8780 Set<String> extList = new HashSet<String>();
8781 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8782 if (app.pkgList != null) {
8783 for (String pkg : app.pkgList) {
8784 extList.add(pkg);
8785 }
8786 }
8787 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008788 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008789 for (String pkg : extList) {
8790 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008791 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008792 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8793 retList.add(info);
8794 }
8795 } catch (RemoteException e) {
8796 }
8797 }
8798 }
8799 return retList;
8800 }
8801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008803 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8804 enforceNotIsolatedCaller("getMyMemoryState");
8805 synchronized (this) {
8806 ProcessRecord proc;
8807 synchronized (mPidsSelfLocked) {
8808 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8809 }
8810 fillInProcMemInfo(proc, outInfo);
8811 }
8812 }
8813
8814 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008816 if (checkCallingPermission(android.Manifest.permission.DUMP)
8817 != PackageManager.PERMISSION_GRANTED) {
8818 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8819 + Binder.getCallingPid()
8820 + ", uid=" + Binder.getCallingUid()
8821 + " without permission "
8822 + android.Manifest.permission.DUMP);
8823 return;
8824 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008825
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008826 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008827 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008828 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008829
8830 int opti = 0;
8831 while (opti < args.length) {
8832 String opt = args[opti];
8833 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8834 break;
8835 }
8836 opti++;
8837 if ("-a".equals(opt)) {
8838 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008839 } else if ("-c".equals(opt)) {
8840 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008841 } else if ("-h".equals(opt)) {
8842 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008843 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008844 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008845 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008846 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8847 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8848 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008849 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008850 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008851 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008852 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008853 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008854 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008855 pw.println(" all: dump all activities");
8856 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008857 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008858 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8859 pw.println(" a partial substring in a component name, a");
8860 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008861 pw.println(" -a: include all available server state.");
8862 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008864 } else {
8865 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008867 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008868
8869 long origId = Binder.clearCallingIdentity();
8870 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008871 // Is the caller requesting to dump a particular piece of data?
8872 if (opti < args.length) {
8873 String cmd = args[opti];
8874 opti++;
8875 if ("activities".equals(cmd) || "a".equals(cmd)) {
8876 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008877 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008879 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008880 String[] newArgs;
8881 String name;
8882 if (opti >= args.length) {
8883 name = null;
8884 newArgs = EMPTY_STRING_ARRAY;
8885 } else {
8886 name = args[opti];
8887 opti++;
8888 newArgs = new String[args.length - opti];
8889 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8890 args.length - opti);
8891 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008892 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008893 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008894 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008895 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008896 String[] newArgs;
8897 String name;
8898 if (opti >= args.length) {
8899 name = null;
8900 newArgs = EMPTY_STRING_ARRAY;
8901 } else {
8902 name = args[opti];
8903 opti++;
8904 newArgs = new String[args.length - opti];
8905 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8906 args.length - opti);
8907 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008908 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008909 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008911 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008912 String[] newArgs;
8913 String name;
8914 if (opti >= args.length) {
8915 name = null;
8916 newArgs = EMPTY_STRING_ARRAY;
8917 } else {
8918 name = args[opti];
8919 opti++;
8920 newArgs = new String[args.length - opti];
8921 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8922 args.length - opti);
8923 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008925 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008926 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008927 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8928 synchronized (this) {
8929 dumpOomLocked(fd, pw, args, opti, true);
8930 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008931 } else if ("provider".equals(cmd)) {
8932 String[] newArgs;
8933 String name;
8934 if (opti >= args.length) {
8935 name = null;
8936 newArgs = EMPTY_STRING_ARRAY;
8937 } else {
8938 name = args[opti];
8939 opti++;
8940 newArgs = new String[args.length - opti];
8941 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8942 }
8943 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8944 pw.println("No providers match: " + name);
8945 pw.println("Use -h for help.");
8946 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008947 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8948 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008950 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008951 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008952 String[] newArgs;
8953 String name;
8954 if (opti >= args.length) {
8955 name = null;
8956 newArgs = EMPTY_STRING_ARRAY;
8957 } else {
8958 name = args[opti];
8959 opti++;
8960 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008961 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8962 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008963 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008964 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008965 pw.println("No services match: " + name);
8966 pw.println("Use -h for help.");
8967 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008968 } else if ("package".equals(cmd)) {
8969 String[] newArgs;
8970 if (opti >= args.length) {
8971 pw.println("package: no package name specified");
8972 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008973 } else {
8974 dumpPackage = args[opti];
8975 opti++;
8976 newArgs = new String[args.length - opti];
8977 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8978 args.length - opti);
8979 args = newArgs;
8980 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008981 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008982 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008983 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8984 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008985 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008986 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008987 } else {
8988 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008989 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8990 pw.println("Bad activity command, or no activities match: " + cmd);
8991 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008992 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008993 }
8994 if (!more) {
8995 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008996 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008998 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008999
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009000 // No piece of data specified, dump everything.
9001 synchronized (this) {
9002 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009003 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009004 if (needSep) {
9005 pw.println(" ");
9006 }
9007 if (dumpAll) {
9008 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009009 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009010 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 if (needSep) {
9012 pw.println(" ");
9013 }
9014 if (dumpAll) {
9015 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009016 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009017 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 if (needSep) {
9019 pw.println(" ");
9020 }
9021 if (dumpAll) {
9022 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009023 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009024 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009025 if (needSep) {
9026 pw.println(" ");
9027 }
9028 if (dumpAll) {
9029 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009030 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009031 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009032 if (needSep) {
9033 pw.println(" ");
9034 }
9035 if (dumpAll) {
9036 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009037 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009038 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009039 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009040 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009041 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009042
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009044 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009045 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9046 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009047 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9048 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009049 pw.println(" ");
9050 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9052 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009053 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009056 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009057 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009059 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009061 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009062 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009063 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009064 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009065 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9066 pw.println(" ");
9067 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009068 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009069 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009070 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009071 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009072 pw.println(" ");
9073 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009074 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009075 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009077
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009078 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009079 if (mMainStack.mPausingActivity != null) {
9080 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009081 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009082 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009083 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009084 if (dumpAll) {
9085 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9086 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009087 pw.println(" mDismissKeyguardOnNextActivity: "
9088 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009091 if (mRecentTasks.size() > 0) {
9092 pw.println();
9093 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094
9095 final int N = mRecentTasks.size();
9096 for (int i=0; i<N; i++) {
9097 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009098 if (dumpPackage != null) {
9099 if (tr.realActivity == null ||
9100 !dumpPackage.equals(tr.realActivity)) {
9101 continue;
9102 }
9103 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009104 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9105 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009106 if (dumpAll) {
9107 mRecentTasks.get(i).dump(pw, " ");
9108 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009109 }
9110 }
9111
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009112 if (dumpAll) {
9113 pw.println(" ");
9114 pw.println(" mCurTask: " + mCurTask);
9115 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009116
9117 return true;
9118 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009119
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009120 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009121 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009122 boolean needSep = false;
9123 int numPers = 0;
9124
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009125 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9126
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009128 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9129 final int NA = procs.size();
9130 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009131 ProcessRecord r = procs.valueAt(ia);
9132 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9133 continue;
9134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009135 if (!needSep) {
9136 pw.println(" All known processes:");
9137 needSep = true;
9138 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009139 pw.print(r.persistent ? " *PERS*" : " *APP*");
9140 pw.print(" UID "); pw.print(procs.keyAt(ia));
9141 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 r.dump(pw, " ");
9143 if (r.persistent) {
9144 numPers++;
9145 }
9146 }
9147 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009148 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009149
9150 if (mIsolatedProcesses.size() > 0) {
9151 if (needSep) pw.println(" ");
9152 needSep = true;
9153 pw.println(" Isolated process list (sorted by uid):");
9154 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9155 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9156 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9157 continue;
9158 }
9159 pw.println(String.format("%sIsolated #%2d: %s",
9160 " ", i, r.toString()));
9161 }
9162 }
9163
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009164 if (mLruProcesses.size() > 0) {
9165 if (needSep) pw.println(" ");
9166 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009167 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009168 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009169 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009170 needSep = true;
9171 }
9172
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009173 if (dumpAll) {
9174 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009175 boolean printed = false;
9176 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9177 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9178 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9179 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009180 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009181 if (!printed) {
9182 if (needSep) pw.println(" ");
9183 needSep = true;
9184 pw.println(" PID mappings:");
9185 printed = true;
9186 }
9187 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9188 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 }
9190 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009191 }
9192
9193 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009194 synchronized (mPidsSelfLocked) {
9195 boolean printed = false;
9196 for (int i=0; i<mForegroundProcesses.size(); i++) {
9197 ProcessRecord r = mPidsSelfLocked.get(
9198 mForegroundProcesses.valueAt(i).pid);
9199 if (dumpPackage != null && (r == null
9200 || !dumpPackage.equals(r.info.packageName))) {
9201 continue;
9202 }
9203 if (!printed) {
9204 if (needSep) pw.println(" ");
9205 needSep = true;
9206 pw.println(" Foreground Processes:");
9207 printed = true;
9208 }
9209 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9210 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009212 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009213 }
9214
9215 if (mPersistentStartingProcesses.size() > 0) {
9216 if (needSep) pw.println(" ");
9217 needSep = true;
9218 pw.println(" Persisent processes that are starting:");
9219 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009220 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009222
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009223 if (mRemovedProcesses.size() > 0) {
9224 if (needSep) pw.println(" ");
9225 needSep = true;
9226 pw.println(" Processes that are being removed:");
9227 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009228 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009229 }
9230
9231 if (mProcessesOnHold.size() > 0) {
9232 if (needSep) pw.println(" ");
9233 needSep = true;
9234 pw.println(" Processes that are on old until the system is ready:");
9235 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009236 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009238
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009239 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009240
9241 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009242 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 long now = SystemClock.uptimeMillis();
9244 for (Map.Entry<String, SparseArray<Long>> procs
9245 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009246 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009247 SparseArray<Long> uids = procs.getValue();
9248 final int N = uids.size();
9249 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009250 int puid = uids.keyAt(i);
9251 ProcessRecord r = mProcessNames.get(pname, puid);
9252 if (dumpPackage != null && (r == null
9253 || !dumpPackage.equals(r.info.packageName))) {
9254 continue;
9255 }
9256 if (!printed) {
9257 if (needSep) pw.println(" ");
9258 needSep = true;
9259 pw.println(" Time since processes crashed:");
9260 printed = true;
9261 }
9262 pw.print(" Process "); pw.print(pname);
9263 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009265 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9266 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009267 }
9268 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009271 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009272 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009273 for (Map.Entry<String, SparseArray<Long>> procs
9274 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009275 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009276 SparseArray<Long> uids = procs.getValue();
9277 final int N = uids.size();
9278 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009279 int puid = uids.keyAt(i);
9280 ProcessRecord r = mProcessNames.get(pname, puid);
9281 if (dumpPackage != null && (r == null
9282 || !dumpPackage.equals(r.info.packageName))) {
9283 continue;
9284 }
9285 if (!printed) {
9286 if (needSep) pw.println(" ");
9287 needSep = true;
9288 pw.println(" Bad processes:");
9289 }
9290 pw.print(" Bad process "); pw.print(pname);
9291 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009292 pw.print(": crashed at time ");
9293 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 }
9295 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009298 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009299 pw.println(" mStartedUsers:");
9300 for (int i=0; i<mStartedUsers.size(); i++) {
9301 UserStartedState uss = mStartedUsers.valueAt(i);
9302 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009303 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009304 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009305 pw.print(" mUserLru: [");
9306 for (int i=0; i<mUserLru.size(); i++) {
9307 if (i > 0) pw.print(", ");
9308 pw.print(mUserLru.get(i));
9309 }
9310 pw.println("]");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009312 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009313 if (dumpAll) {
9314 StringBuilder sb = new StringBuilder(128);
9315 sb.append(" mPreviousProcessVisibleTime: ");
9316 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9317 pw.println(sb);
9318 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009319 if (mHeavyWeightProcess != null) {
9320 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9321 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009322 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009323 if (dumpAll) {
9324 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009325 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009326 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009327 for (Map.Entry<String, Integer> entry
9328 : mCompatModePackages.getPackages().entrySet()) {
9329 String pkg = entry.getKey();
9330 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009331 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9332 continue;
9333 }
9334 if (!printed) {
9335 pw.println(" mScreenCompatPackages:");
9336 printed = true;
9337 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009338 pw.print(" "); pw.print(pkg); pw.print(": ");
9339 pw.print(mode); pw.println();
9340 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009341 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009342 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009343 if (mSleeping || mWentToSleep || mLockScreenShown) {
9344 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9345 + " mLockScreenShown " + mLockScreenShown);
9346 }
9347 if (mShuttingDown) {
9348 pw.println(" mShuttingDown=" + mShuttingDown);
9349 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009350 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9351 || mOrigWaitForDebugger) {
9352 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9353 + " mDebugTransient=" + mDebugTransient
9354 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9355 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009356 if (mOpenGlTraceApp != null) {
9357 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9358 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009359 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9360 || mProfileFd != null) {
9361 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9362 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9363 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9364 + mAutoStopProfiler);
9365 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009366 if (mAlwaysFinishActivities || mController != null) {
9367 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9368 + " mController=" + mController);
9369 }
9370 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009371 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009373 + " mProcessesReady=" + mProcessesReady
9374 + " mSystemReady=" + mSystemReady);
9375 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 + " mBooted=" + mBooted
9377 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009378 pw.print(" mLastPowerCheckRealtime=");
9379 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9380 pw.println("");
9381 pw.print(" mLastPowerCheckUptime=");
9382 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9383 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009384 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9385 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009386 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009387 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9388 + " mNumHiddenProcs=" + mNumHiddenProcs
9389 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009390 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009392
9393 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009394 }
9395
Dianne Hackborn287952c2010-09-22 22:34:31 -07009396 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009397 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009398 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009399 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009400 long now = SystemClock.uptimeMillis();
9401 for (int i=0; i<mProcessesToGc.size(); i++) {
9402 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009403 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9404 continue;
9405 }
9406 if (!printed) {
9407 if (needSep) pw.println(" ");
9408 needSep = true;
9409 pw.println(" Processes that are waiting to GC:");
9410 printed = true;
9411 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009412 pw.print(" Process "); pw.println(proc);
9413 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9414 pw.print(", last gced=");
9415 pw.print(now-proc.lastRequestedGc);
9416 pw.print(" ms ago, last lowMem=");
9417 pw.print(now-proc.lastLowMemory);
9418 pw.println(" ms ago");
9419
9420 }
9421 }
9422 return needSep;
9423 }
9424
9425 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9426 int opti, boolean dumpAll) {
9427 boolean needSep = false;
9428
9429 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009430 if (needSep) pw.println(" ");
9431 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009432 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009433 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009434 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009435 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9436 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9437 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9438 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9439 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009440 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009441 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009442 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009443 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009444 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009445 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009446
9447 if (needSep) pw.println(" ");
9448 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009449 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009450 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009451 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009452 needSep = true;
9453 }
9454
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009455 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009456
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009457 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009458 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009459 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009460 if (mHeavyWeightProcess != null) {
9461 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9462 }
9463
9464 return true;
9465 }
9466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 /**
9468 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009469 * - no provider specified: dump all the providers
9470 * - a flattened component name that matched an existing provider was specified as the
9471 * first arg: dump that one provider
9472 * - the first arg isn't the flattened component name of an existing provider:
9473 * dump all providers whose component contains the first arg as a substring
9474 */
9475 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9476 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009477 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009478 }
9479
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009480 static class ItemMatcher {
9481 ArrayList<ComponentName> components;
9482 ArrayList<String> strings;
9483 ArrayList<Integer> objects;
9484 boolean all;
9485
9486 ItemMatcher() {
9487 all = true;
9488 }
9489
9490 void build(String name) {
9491 ComponentName componentName = ComponentName.unflattenFromString(name);
9492 if (componentName != null) {
9493 if (components == null) {
9494 components = new ArrayList<ComponentName>();
9495 }
9496 components.add(componentName);
9497 all = false;
9498 } else {
9499 int objectId = 0;
9500 // Not a '/' separated full component name; maybe an object ID?
9501 try {
9502 objectId = Integer.parseInt(name, 16);
9503 if (objects == null) {
9504 objects = new ArrayList<Integer>();
9505 }
9506 objects.add(objectId);
9507 all = false;
9508 } catch (RuntimeException e) {
9509 // Not an integer; just do string match.
9510 if (strings == null) {
9511 strings = new ArrayList<String>();
9512 }
9513 strings.add(name);
9514 all = false;
9515 }
9516 }
9517 }
9518
9519 int build(String[] args, int opti) {
9520 for (; opti<args.length; opti++) {
9521 String name = args[opti];
9522 if ("--".equals(name)) {
9523 return opti+1;
9524 }
9525 build(name);
9526 }
9527 return opti;
9528 }
9529
9530 boolean match(Object object, ComponentName comp) {
9531 if (all) {
9532 return true;
9533 }
9534 if (components != null) {
9535 for (int i=0; i<components.size(); i++) {
9536 if (components.get(i).equals(comp)) {
9537 return true;
9538 }
9539 }
9540 }
9541 if (objects != null) {
9542 for (int i=0; i<objects.size(); i++) {
9543 if (System.identityHashCode(object) == objects.get(i)) {
9544 return true;
9545 }
9546 }
9547 }
9548 if (strings != null) {
9549 String flat = comp.flattenToString();
9550 for (int i=0; i<strings.size(); i++) {
9551 if (flat.contains(strings.get(i))) {
9552 return true;
9553 }
9554 }
9555 }
9556 return false;
9557 }
9558 }
9559
Dianne Hackborn625ac272010-09-17 18:29:22 -07009560 /**
9561 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009562 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009563 * - the cmd arg isn't the flattened component name of an existing activity:
9564 * dump all activity whose component contains the cmd as a substring
9565 * - A hex number of the ActivityRecord object instance.
9566 */
9567 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9568 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009569 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009570
9571 if ("all".equals(name)) {
9572 synchronized (this) {
9573 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009574 activities.add(r1);
9575 }
9576 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009577 } else if ("top".equals(name)) {
9578 synchronized (this) {
9579 final int N = mMainStack.mHistory.size();
9580 if (N > 0) {
9581 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9582 }
9583 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009584 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009585 ItemMatcher matcher = new ItemMatcher();
9586 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009587
9588 synchronized (this) {
9589 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009590 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009591 activities.add(r1);
9592 }
9593 }
9594 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009595 }
9596
9597 if (activities.size() <= 0) {
9598 return false;
9599 }
9600
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009601 String[] newArgs = new String[args.length - opti];
9602 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9603
Dianne Hackborn30d71892010-12-11 10:37:55 -08009604 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009605 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009606 for (int i=activities.size()-1; i>=0; i--) {
9607 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009608 if (needSep) {
9609 pw.println();
9610 }
9611 needSep = true;
9612 synchronized (this) {
9613 if (lastTask != r.task) {
9614 lastTask = r.task;
9615 pw.print("TASK "); pw.print(lastTask.affinity);
9616 pw.print(" id="); pw.println(lastTask.taskId);
9617 if (dumpAll) {
9618 lastTask.dump(pw, " ");
9619 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009620 }
9621 }
9622 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009623 }
9624 return true;
9625 }
9626
9627 /**
9628 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9629 * there is a thread associated with the activity.
9630 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009631 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009632 final ActivityRecord r, String[] args, boolean dumpAll) {
9633 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009634 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009635 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9636 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9637 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009638 if (r.app != null) pw.println(r.app.pid);
9639 else pw.println("(not running)");
9640 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009641 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009642 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009643 }
9644 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009645 // flush anything that is already in the PrintWriter since the thread is going
9646 // to write to the file descriptor directly
9647 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009648 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009649 TransferPipe tp = new TransferPipe();
9650 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009651 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9652 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009653 tp.go(fd);
9654 } finally {
9655 tp.kill();
9656 }
9657 } catch (IOException e) {
9658 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009659 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009660 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009661 }
9662 }
9663 }
9664
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009665 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009666 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009667 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009668 boolean onlyHistory = false;
9669
9670 if ("history".equals(dumpPackage)) {
9671 onlyHistory = true;
9672 dumpPackage = null;
9673 }
9674
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009675 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009676 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009677 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009678 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 Iterator it = mRegisteredReceivers.values().iterator();
9680 while (it.hasNext()) {
9681 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009682 if (dumpPackage != null && (r.app == null ||
9683 !dumpPackage.equals(r.app.info.packageName))) {
9684 continue;
9685 }
9686 if (!printed) {
9687 pw.println(" Registered Receivers:");
9688 needSep = true;
9689 printed = true;
9690 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009691 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009692 r.dump(pw, " ");
9693 }
9694 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009695
9696 if (mReceiverResolver.dump(pw, needSep ?
9697 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9698 " ", dumpPackage, false)) {
9699 needSep = true;
9700 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009701 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009702
9703 for (BroadcastQueue q : mBroadcastQueues) {
9704 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009706
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009707 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009708
Dianne Hackborn786b4402012-08-27 15:14:02 -07009709 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009710 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9711 if (needSep) {
9712 pw.println();
9713 }
9714 needSep = true;
9715 pw.print(" Sticky broadcasts for user ");
9716 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9717 StringBuilder sb = new StringBuilder(128);
9718 for (Map.Entry<String, ArrayList<Intent>> ent
9719 : mStickyBroadcasts.valueAt(user).entrySet()) {
9720 pw.print(" * Sticky action "); pw.print(ent.getKey());
9721 if (dumpAll) {
9722 pw.println(":");
9723 ArrayList<Intent> intents = ent.getValue();
9724 final int N = intents.size();
9725 for (int i=0; i<N; i++) {
9726 sb.setLength(0);
9727 sb.append(" Intent: ");
9728 intents.get(i).toShortString(sb, false, true, false, false);
9729 pw.println(sb.toString());
9730 Bundle bundle = intents.get(i).getExtras();
9731 if (bundle != null) {
9732 pw.print(" ");
9733 pw.println(bundle.toString());
9734 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009735 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009736 } else {
9737 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 }
9739 }
9740 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009741 }
9742
Dianne Hackborn786b4402012-08-27 15:14:02 -07009743 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009744 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009745 for (BroadcastQueue queue : mBroadcastQueues) {
9746 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9747 + queue.mBroadcastsScheduled);
9748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009749 pw.println(" mHandler:");
9750 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009751 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009752 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009753
9754 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 }
9756
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009757 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009758 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009759 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009760
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009761 ItemMatcher matcher = new ItemMatcher();
9762 matcher.build(args, opti);
9763
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009764 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009765
9766 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009767
9768 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009769 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009770 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009771 ContentProviderRecord r = mLaunchingProviders.get(i);
9772 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9773 continue;
9774 }
9775 if (!printed) {
9776 if (needSep) pw.println(" ");
9777 needSep = true;
9778 pw.println(" Launching content providers:");
9779 printed = true;
9780 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009781 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009782 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009783 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009784 }
9785
9786 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009787 if (needSep) pw.println();
9788 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009789 pw.println("Granted Uri Permissions:");
9790 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9791 int uid = mGrantedUriPermissions.keyAt(i);
9792 HashMap<Uri, UriPermission> perms
9793 = mGrantedUriPermissions.valueAt(i);
9794 pw.print(" * UID "); pw.print(uid);
9795 pw.println(" holds:");
9796 for (UriPermission perm : perms.values()) {
9797 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009798 if (dumpAll) {
9799 perm.dump(pw, " ");
9800 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009801 }
9802 }
9803 needSep = true;
9804 }
9805
9806 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009807 }
9808
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009809 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009810 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009811 boolean needSep = false;
9812
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009813 if (mIntentSenderRecords.size() > 0) {
9814 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009815 Iterator<WeakReference<PendingIntentRecord>> it
9816 = mIntentSenderRecords.values().iterator();
9817 while (it.hasNext()) {
9818 WeakReference<PendingIntentRecord> ref = it.next();
9819 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009820 if (dumpPackage != null && (rec == null
9821 || !dumpPackage.equals(rec.key.packageName))) {
9822 continue;
9823 }
9824 if (!printed) {
9825 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9826 printed = true;
9827 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009828 needSep = true;
9829 if (rec != null) {
9830 pw.print(" * "); pw.println(rec);
9831 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009833 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009834 } else {
9835 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 }
9837 }
9838 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009839
9840 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 }
9842
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009844 String prefix, String label, boolean complete, boolean brief, boolean client,
9845 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009846 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 boolean needNL = false;
9848 final String innerPrefix = prefix + " ";
9849 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009850 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009851 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009852 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9853 continue;
9854 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009855 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009856 if (needNL) {
9857 pw.println(" ");
9858 needNL = false;
9859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009860 if (lastTask != r.task) {
9861 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009862 pw.print(prefix);
9863 pw.print(full ? "* " : " ");
9864 pw.println(lastTask);
9865 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009866 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009867 } else if (complete) {
9868 // Complete + brief == give a summary. Isn't that obvious?!?
9869 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009870 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009871 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009872 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009874 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009875 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9876 pw.print(" #"); pw.print(i); pw.print(": ");
9877 pw.println(r);
9878 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009879 r.dump(pw, innerPrefix);
9880 } else if (complete) {
9881 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009882 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009883 if (r.app != null) {
9884 pw.print(innerPrefix); pw.println(r.app);
9885 }
9886 }
9887 if (client && r.app != null && r.app.thread != null) {
9888 // flush anything that is already in the PrintWriter since the thread is going
9889 // to write to the file descriptor directly
9890 pw.flush();
9891 try {
9892 TransferPipe tp = new TransferPipe();
9893 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009894 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9895 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009896 // Short timeout, since blocking here can
9897 // deadlock with the application.
9898 tp.go(fd, 2000);
9899 } finally {
9900 tp.kill();
9901 }
9902 } catch (IOException e) {
9903 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9904 } catch (RemoteException e) {
9905 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9906 }
9907 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909 }
9910 }
9911
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009912 private static String buildOomTag(String prefix, String space, int val, int base) {
9913 if (val == base) {
9914 if (space == null) return prefix;
9915 return prefix + " ";
9916 }
9917 return prefix + "+" + Integer.toString(val-base);
9918 }
9919
9920 private static final int dumpProcessList(PrintWriter pw,
9921 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009922 String prefix, String normalLabel, String persistentLabel,
9923 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009924 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009925 final int N = list.size()-1;
9926 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009928 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9929 continue;
9930 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009931 pw.println(String.format("%s%s #%2d: %s",
9932 prefix, (r.persistent ? persistentLabel : normalLabel),
9933 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009934 if (r.persistent) {
9935 numPers++;
9936 }
9937 }
9938 return numPers;
9939 }
9940
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009941 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009942 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009943 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009944 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009945
Dianne Hackborn905577f2011-09-07 18:31:28 -07009946 ArrayList<Pair<ProcessRecord, Integer>> list
9947 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9948 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009949 ProcessRecord r = origList.get(i);
9950 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9951 continue;
9952 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009953 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9954 }
9955
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009956 if (list.size() <= 0) {
9957 return false;
9958 }
9959
Dianne Hackborn905577f2011-09-07 18:31:28 -07009960 Comparator<Pair<ProcessRecord, Integer>> comparator
9961 = new Comparator<Pair<ProcessRecord, Integer>>() {
9962 @Override
9963 public int compare(Pair<ProcessRecord, Integer> object1,
9964 Pair<ProcessRecord, Integer> object2) {
9965 if (object1.first.setAdj != object2.first.setAdj) {
9966 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9967 }
9968 if (object1.second.intValue() != object2.second.intValue()) {
9969 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9970 }
9971 return 0;
9972 }
9973 };
9974
9975 Collections.sort(list, comparator);
9976
Dianne Hackborn287952c2010-09-22 22:34:31 -07009977 final long curRealtime = SystemClock.elapsedRealtime();
9978 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9979 final long curUptime = SystemClock.uptimeMillis();
9980 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9981
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009982 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009983 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009984 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009985 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009986 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009987 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9988 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009989 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9990 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009991 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9992 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009993 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9994 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009995 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009996 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009997 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9998 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9999 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10000 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10001 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10002 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10003 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10004 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010005 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10006 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010007 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10008 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010009 } else {
10010 oomAdj = Integer.toString(r.setAdj);
10011 }
10012 String schedGroup;
10013 switch (r.setSchedGroup) {
10014 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10015 schedGroup = "B";
10016 break;
10017 case Process.THREAD_GROUP_DEFAULT:
10018 schedGroup = "F";
10019 break;
10020 default:
10021 schedGroup = Integer.toString(r.setSchedGroup);
10022 break;
10023 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010024 String foreground;
10025 if (r.foregroundActivities) {
10026 foreground = "A";
10027 } else if (r.foregroundServices) {
10028 foreground = "S";
10029 } else {
10030 foreground = " ";
10031 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010032 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010033 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010034 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10035 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010036 if (r.adjSource != null || r.adjTarget != null) {
10037 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010038 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010039 if (r.adjTarget instanceof ComponentName) {
10040 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10041 } else if (r.adjTarget != null) {
10042 pw.print(r.adjTarget.toString());
10043 } else {
10044 pw.print("{null}");
10045 }
10046 pw.print("<=");
10047 if (r.adjSource instanceof ProcessRecord) {
10048 pw.print("Proc{");
10049 pw.print(((ProcessRecord)r.adjSource).toShortString());
10050 pw.println("}");
10051 } else if (r.adjSource != null) {
10052 pw.println(r.adjSource.toString());
10053 } else {
10054 pw.println("{null}");
10055 }
10056 }
10057 if (inclDetails) {
10058 pw.print(prefix);
10059 pw.print(" ");
10060 pw.print("oom: max="); pw.print(r.maxAdj);
10061 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010062 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010063 pw.print(" curRaw="); pw.print(r.curRawAdj);
10064 pw.print(" setRaw="); pw.print(r.setRawAdj);
10065 pw.print(" cur="); pw.print(r.curAdj);
10066 pw.print(" set="); pw.println(r.setAdj);
10067 pw.print(prefix);
10068 pw.print(" ");
10069 pw.print("keeping="); pw.print(r.keeping);
10070 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010071 pw.print(" empty="); pw.print(r.empty);
10072 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010073
10074 if (!r.keeping) {
10075 if (r.lastWakeTime != 0) {
10076 long wtime;
10077 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10078 synchronized (stats) {
10079 wtime = stats.getProcessWakeTime(r.info.uid,
10080 r.pid, curRealtime);
10081 }
10082 long timeUsed = wtime - r.lastWakeTime;
10083 pw.print(prefix);
10084 pw.print(" ");
10085 pw.print("keep awake over ");
10086 TimeUtils.formatDuration(realtimeSince, pw);
10087 pw.print(" used ");
10088 TimeUtils.formatDuration(timeUsed, pw);
10089 pw.print(" (");
10090 pw.print((timeUsed*100)/realtimeSince);
10091 pw.println("%)");
10092 }
10093 if (r.lastCpuTime != 0) {
10094 long timeUsed = r.curCpuTime - r.lastCpuTime;
10095 pw.print(prefix);
10096 pw.print(" ");
10097 pw.print("run cpu over ");
10098 TimeUtils.formatDuration(uptimeSince, pw);
10099 pw.print(" used ");
10100 TimeUtils.formatDuration(timeUsed, pw);
10101 pw.print(" (");
10102 pw.print((timeUsed*100)/uptimeSince);
10103 pw.println("%)");
10104 }
10105 }
10106 }
10107 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010108 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010109 }
10110
Dianne Hackbornb437e092011-08-05 17:50:29 -070010111 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010112 ArrayList<ProcessRecord> procs;
10113 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010114 if (args != null && args.length > start
10115 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010116 procs = new ArrayList<ProcessRecord>();
10117 int pid = -1;
10118 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010119 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010120 } catch (NumberFormatException e) {
10121
10122 }
10123 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10124 ProcessRecord proc = mLruProcesses.get(i);
10125 if (proc.pid == pid) {
10126 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010127 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010128 procs.add(proc);
10129 }
10130 }
10131 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010132 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010133 return null;
10134 }
10135 } else {
10136 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10137 }
10138 }
10139 return procs;
10140 }
10141
10142 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10143 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010144 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010145 if (procs == null) {
10146 return;
10147 }
10148
10149 long uptime = SystemClock.uptimeMillis();
10150 long realtime = SystemClock.elapsedRealtime();
10151 pw.println("Applications Graphics Acceleration Info:");
10152 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10153
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010154 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10155 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010156 if (r.thread != null) {
10157 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10158 pw.flush();
10159 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010160 TransferPipe tp = new TransferPipe();
10161 try {
10162 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10163 tp.go(fd);
10164 } finally {
10165 tp.kill();
10166 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010167 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010168 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010169 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010170 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010171 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010172 pw.flush();
10173 }
10174 }
10175 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010176 }
10177
Jeff Brown6754ba22011-12-14 20:20:01 -080010178 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10179 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10180 if (procs == null) {
10181 return;
10182 }
10183
10184 pw.println("Applications Database Info:");
10185
10186 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10187 ProcessRecord r = procs.get(i);
10188 if (r.thread != null) {
10189 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10190 pw.flush();
10191 try {
10192 TransferPipe tp = new TransferPipe();
10193 try {
10194 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10195 tp.go(fd);
10196 } finally {
10197 tp.kill();
10198 }
10199 } catch (IOException e) {
10200 pw.println("Failure while dumping the app: " + r);
10201 pw.flush();
10202 } catch (RemoteException e) {
10203 pw.println("Got a RemoteException while dumping the app " + r);
10204 pw.flush();
10205 }
10206 }
10207 }
10208 }
10209
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010210 final static class MemItem {
10211 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010212 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010213 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010214 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010215 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010216
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010217 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010218 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010219 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010220 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010221 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010222 }
10223 }
10224
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010225 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010226 boolean sort) {
10227 if (sort) {
10228 Collections.sort(items, new Comparator<MemItem>() {
10229 @Override
10230 public int compare(MemItem lhs, MemItem rhs) {
10231 if (lhs.pss < rhs.pss) {
10232 return 1;
10233 } else if (lhs.pss > rhs.pss) {
10234 return -1;
10235 }
10236 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010237 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010238 });
10239 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010240
10241 for (int i=0; i<items.size(); i++) {
10242 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010243 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010244 if (mi.subitems != null) {
10245 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10246 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010247 }
10248 }
10249
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010250 // These are in KB.
10251 static final long[] DUMP_MEM_BUCKETS = new long[] {
10252 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10253 120*1024, 160*1024, 200*1024,
10254 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10255 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10256 };
10257
Dianne Hackborn672342c2011-11-29 11:29:02 -080010258 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10259 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010260 int start = label.lastIndexOf('.');
10261 if (start >= 0) start++;
10262 else start = 0;
10263 int end = label.length();
10264 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10265 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10266 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10267 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010268 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010269 out.append(label, start, end);
10270 return;
10271 }
10272 }
10273 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010274 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010275 out.append(label, start, end);
10276 }
10277
10278 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10279 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10280 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10281 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10282 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10283 };
10284 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10285 "System", "Persistent", "Foreground",
10286 "Visible", "Perceptible", "Heavy Weight",
10287 "Backup", "A Services", "Home", "Previous",
10288 "B Services", "Background"
10289 };
10290
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010291 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010292 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010293 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010294 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010295 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010296
10297 int opti = 0;
10298 while (opti < args.length) {
10299 String opt = args[opti];
10300 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10301 break;
10302 }
10303 opti++;
10304 if ("-a".equals(opt)) {
10305 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010306 } else if ("--oom".equals(opt)) {
10307 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010308 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010309 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010310 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010311 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010312 pw.println("If [process] is specified it can be the name or ");
10313 pw.println("pid of a specific process to dump.");
10314 return;
10315 } else {
10316 pw.println("Unknown argument: " + opt + "; use -h for help");
10317 }
10318 }
10319
10320 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010321 if (procs == null) {
10322 return;
10323 }
10324
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010325 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010326 long uptime = SystemClock.uptimeMillis();
10327 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010328
10329 if (procs.size() == 1 || isCheckinRequest) {
10330 dumpAll = true;
10331 }
10332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 if (isCheckinRequest) {
10334 // short checkin version
10335 pw.println(uptime + "," + realtime);
10336 pw.flush();
10337 } else {
10338 pw.println("Applications Memory Usage (kB):");
10339 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10340 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010341
Dianne Hackbornb437e092011-08-05 17:50:29 -070010342 String[] innerArgs = new String[args.length-opti];
10343 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10344
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010345 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10346 long nativePss=0, dalvikPss=0, otherPss=0;
10347 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10348
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010349 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10350 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10351 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010352
10353 long totalPss = 0;
10354
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010355 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10356 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010357 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010358 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10360 pw.flush();
10361 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010362 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010363 if (dumpAll) {
10364 try {
10365 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10366 } catch (RemoteException e) {
10367 if (!isCheckinRequest) {
10368 pw.println("Got RemoteException!");
10369 pw.flush();
10370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010371 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010372 } else {
10373 mi = new Debug.MemoryInfo();
10374 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010375 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010376
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010377 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010378 long myTotalPss = mi.getTotalPss();
10379 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010380 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010381 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010382 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010383
10384 nativePss += mi.nativePss;
10385 dalvikPss += mi.dalvikPss;
10386 otherPss += mi.otherPss;
10387 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10388 long mem = mi.getOtherPss(j);
10389 miscPss[j] += mem;
10390 otherPss -= mem;
10391 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010392
10393 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010394 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10395 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010396 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010397 if (oomProcs[oomIndex] == null) {
10398 oomProcs[oomIndex] = new ArrayList<MemItem>();
10399 }
10400 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010401 break;
10402 }
10403 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010405 }
10406 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010407
10408 if (!isCheckinRequest && procs.size() > 1) {
10409 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10410
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010411 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10412 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10413 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010414 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010415 String label = Debug.MemoryInfo.getOtherLabel(j);
10416 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010417 }
10418
Dianne Hackbornb437e092011-08-05 17:50:29 -070010419 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10420 for (int j=0; j<oomPss.length; j++) {
10421 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010422 String label = DUMP_MEM_OOM_LABEL[j];
10423 MemItem item = new MemItem(label, label, oomPss[j],
10424 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010425 item.subitems = oomProcs[j];
10426 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010427 }
10428 }
10429
Dianne Hackborn672342c2011-11-29 11:29:02 -080010430 if (outTag != null || outStack != null) {
10431 if (outTag != null) {
10432 appendMemBucket(outTag, totalPss, "total", false);
10433 }
10434 if (outStack != null) {
10435 appendMemBucket(outStack, totalPss, "total", true);
10436 }
10437 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010438 for (int i=0; i<oomMems.size(); i++) {
10439 MemItem miCat = oomMems.get(i);
10440 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10441 continue;
10442 }
10443 if (miCat.id < ProcessList.SERVICE_ADJ
10444 || miCat.id == ProcessList.HOME_APP_ADJ
10445 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010446 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10447 outTag.append(" / ");
10448 }
10449 if (outStack != null) {
10450 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10451 if (firstLine) {
10452 outStack.append(":");
10453 firstLine = false;
10454 }
10455 outStack.append("\n\t at ");
10456 } else {
10457 outStack.append("$");
10458 }
10459 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010460 for (int j=0; j<miCat.subitems.size(); j++) {
10461 MemItem mi = miCat.subitems.get(j);
10462 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010463 if (outTag != null) {
10464 outTag.append(" ");
10465 }
10466 if (outStack != null) {
10467 outStack.append("$");
10468 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010469 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010470 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10471 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10472 }
10473 if (outStack != null) {
10474 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10475 }
10476 }
10477 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10478 outStack.append("(");
10479 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10480 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10481 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10482 outStack.append(":");
10483 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10484 }
10485 }
10486 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010487 }
10488 }
10489 }
10490 }
10491
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010492 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010493 pw.println();
10494 pw.println("Total PSS by process:");
10495 dumpMemItems(pw, " ", procMems, true);
10496 pw.println();
10497 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010498 pw.println("Total PSS by OOM adjustment:");
10499 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010500 if (!oomOnly) {
10501 PrintWriter out = categoryPw != null ? categoryPw : pw;
10502 out.println();
10503 out.println("Total PSS by category:");
10504 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010505 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010506 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010507 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010508 final int[] SINGLE_LONG_FORMAT = new int[] {
10509 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10510 };
10511 long[] longOut = new long[1];
10512 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10513 SINGLE_LONG_FORMAT, null, longOut, null);
10514 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10515 longOut[0] = 0;
10516 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10517 SINGLE_LONG_FORMAT, null, longOut, null);
10518 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10519 longOut[0] = 0;
10520 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10521 SINGLE_LONG_FORMAT, null, longOut, null);
10522 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10523 longOut[0] = 0;
10524 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10525 SINGLE_LONG_FORMAT, null, longOut, null);
10526 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10527 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10528 pw.print(shared); pw.println(" kB");
10529 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10530 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010532 }
10533
10534 /**
10535 * Searches array of arguments for the specified string
10536 * @param args array of argument strings
10537 * @param value value to search for
10538 * @return true if the value is contained in the array
10539 */
10540 private static boolean scanArgs(String[] args, String value) {
10541 if (args != null) {
10542 for (String arg : args) {
10543 if (value.equals(arg)) {
10544 return true;
10545 }
10546 }
10547 }
10548 return false;
10549 }
10550
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010551 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10552 ContentProviderRecord cpr, boolean always) {
10553 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10554
10555 if (!inLaunching || always) {
10556 synchronized (cpr) {
10557 cpr.launchingApp = null;
10558 cpr.notifyAll();
10559 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010560 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010561 String names[] = cpr.info.authority.split(";");
10562 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010563 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 }
10565 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010566
10567 for (int i=0; i<cpr.connections.size(); i++) {
10568 ContentProviderConnection conn = cpr.connections.get(i);
10569 if (conn.waiting) {
10570 // If this connection is waiting for the provider, then we don't
10571 // need to mess with its process unless we are always removing
10572 // or for some reason the provider is not currently launching.
10573 if (inLaunching && !always) {
10574 continue;
10575 }
10576 }
10577 ProcessRecord capp = conn.client;
10578 conn.dead = true;
10579 if (conn.stableCount > 0) {
10580 if (!capp.persistent && capp.thread != null
10581 && capp.pid != 0
10582 && capp.pid != MY_PID) {
10583 Slog.i(TAG, "Kill " + capp.processName
10584 + " (pid " + capp.pid + "): provider " + cpr.info.name
10585 + " in dying process " + (proc != null ? proc.processName : "??"));
10586 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10587 capp.processName, capp.setAdj, "dying provider "
10588 + cpr.name.toShortString());
10589 Process.killProcessQuiet(capp.pid);
10590 }
10591 } else if (capp.thread != null && conn.provider.provider != null) {
10592 try {
10593 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10594 } catch (RemoteException e) {
10595 }
10596 // In the protocol here, we don't expect the client to correctly
10597 // clean up this connection, we'll just remove it.
10598 cpr.connections.remove(i);
10599 conn.client.conProviders.remove(conn);
10600 }
10601 }
10602
10603 if (inLaunching && always) {
10604 mLaunchingProviders.remove(cpr);
10605 }
10606 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 }
10608
10609 /**
10610 * Main code for cleaning up a process when it has gone away. This is
10611 * called both as a result of the process dying, or directly when stopping
10612 * a process when running in single process mode.
10613 */
10614 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010615 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010617 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 }
10619
Dianne Hackborn36124872009-10-08 16:22:03 -070010620 mProcessesToGc.remove(app);
10621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010622 // Dismiss any open dialogs.
10623 if (app.crashDialog != null) {
10624 app.crashDialog.dismiss();
10625 app.crashDialog = null;
10626 }
10627 if (app.anrDialog != null) {
10628 app.anrDialog.dismiss();
10629 app.anrDialog = null;
10630 }
10631 if (app.waitDialog != null) {
10632 app.waitDialog.dismiss();
10633 app.waitDialog = null;
10634 }
10635
10636 app.crashing = false;
10637 app.notResponding = false;
10638
10639 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010640 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641 app.thread = null;
10642 app.forcingToForeground = null;
10643 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010644 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010645 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010646 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010647
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010648 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010649
10650 boolean restart = false;
10651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010652 // Remove published content providers.
10653 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010654 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010655 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010656 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010657
10658 final boolean always = app.bad || !allowRestart;
10659 if (removeDyingProviderLocked(app, cpr, always) || always) {
10660 // We left the provider in the launching list, need to
10661 // restart it.
10662 restart = true;
10663 }
10664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010666 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010667 }
10668 app.pubProviders.clear();
10669 }
10670
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010671 // Take care of any launching providers waiting for this process.
10672 if (checkAppInLaunchingProvidersLocked(app, false)) {
10673 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010674 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 // Unregister from connected content providers.
10677 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010678 for (int i=0; i<app.conProviders.size(); i++) {
10679 ContentProviderConnection conn = app.conProviders.get(i);
10680 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 }
10682 app.conProviders.clear();
10683 }
10684
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010685 // At this point there may be remaining entries in mLaunchingProviders
10686 // where we were the only one waiting, so they are no longer of use.
10687 // Look for these and clean up if found.
10688 // XXX Commented out for now. Trying to figure out a way to reproduce
10689 // the actual situation to identify what is actually going on.
10690 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010691 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010692 ContentProviderRecord cpr = (ContentProviderRecord)
10693 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010694 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010695 synchronized (cpr) {
10696 cpr.launchingApp = null;
10697 cpr.notifyAll();
10698 }
10699 }
10700 }
10701 }
10702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010703 skipCurrentReceiverLocked(app);
10704
10705 // Unregister any receivers.
10706 if (app.receivers.size() > 0) {
10707 Iterator<ReceiverList> it = app.receivers.iterator();
10708 while (it.hasNext()) {
10709 removeReceiverLocked(it.next());
10710 }
10711 app.receivers.clear();
10712 }
10713
Christopher Tate181fafa2009-05-14 11:12:14 -070010714 // If the app is undergoing backup, tell the backup manager about it
10715 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010716 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010717 try {
10718 IBackupManager bm = IBackupManager.Stub.asInterface(
10719 ServiceManager.getService(Context.BACKUP_SERVICE));
10720 bm.agentDisconnected(app.info.packageName);
10721 } catch (RemoteException e) {
10722 // can't happen; backup manager is local
10723 }
10724 }
10725
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010726 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10727 ProcessChangeItem item = mPendingProcessChanges.get(i);
10728 if (item.pid == app.pid) {
10729 mPendingProcessChanges.remove(i);
10730 mAvailProcessChanges.add(item);
10731 }
10732 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010733 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010735 // If the caller is restarting this app, then leave it in its
10736 // current lists and let the caller take care of it.
10737 if (restarting) {
10738 return;
10739 }
10740
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010741 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010742 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010744 mProcessNames.remove(app.processName, app.uid);
10745 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010746 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010747 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10748 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010749 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010751 } else if (!app.removed) {
10752 // This app is persistent, so we need to keep its record around.
10753 // If it is not already on the pending app list, add it there
10754 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10756 mPersistentStartingProcesses.add(app);
10757 restart = true;
10758 }
10759 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010760 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10761 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 mProcessesOnHold.remove(app);
10763
The Android Open Source Project4df24232009-03-05 14:34:35 -080010764 if (app == mHomeProcess) {
10765 mHomeProcess = null;
10766 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010767 if (app == mPreviousProcess) {
10768 mPreviousProcess = null;
10769 }
10770
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010771 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 // We have components that still need to be running in the
10773 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010774 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 startProcessLocked(app, "restart", app.processName);
10776 } else if (app.pid > 0 && app.pid != MY_PID) {
10777 // Goodbye!
10778 synchronized (mPidsSelfLocked) {
10779 mPidsSelfLocked.remove(app.pid);
10780 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10781 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010782 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 }
10784 }
10785
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010786 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10787 // Look through the content providers we are waiting to have launched,
10788 // and if any run in this process then either schedule a restart of
10789 // the process or kill the client waiting for it if this process has
10790 // gone bad.
10791 int NL = mLaunchingProviders.size();
10792 boolean restart = false;
10793 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010794 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010795 if (cpr.launchingApp == app) {
10796 if (!alwaysBad && !app.bad) {
10797 restart = true;
10798 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010799 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010800 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010801 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010802 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010803 }
10804 }
10805 }
10806 return restart;
10807 }
10808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 // =========================================================
10810 // SERVICES
10811 // =========================================================
10812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10814 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010815 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010816 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010817 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 }
10819 }
10820
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010821 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010822 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010823 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010824 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010825 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010826 }
10827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010828 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010829 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010830 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 // Refuse possible leaked file descriptors
10832 if (service != null && service.hasFileDescriptors() == true) {
10833 throw new IllegalArgumentException("File descriptors passed in Intent");
10834 }
10835
Amith Yamasani742a6712011-05-04 14:49:28 -070010836 if (DEBUG_SERVICE)
10837 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 synchronized(this) {
10839 final int callingPid = Binder.getCallingPid();
10840 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010841 checkValidCaller(callingUid, userId);
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(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010844 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 Binder.restoreCallingIdentity(origId);
10846 return res;
10847 }
10848 }
10849
10850 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010851 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010853 if (DEBUG_SERVICE)
10854 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010856 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010857 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 Binder.restoreCallingIdentity(origId);
10859 return res;
10860 }
10861 }
10862
10863 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010864 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010865 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 // Refuse possible leaked file descriptors
10867 if (service != null && service.hasFileDescriptors() == true) {
10868 throw new IllegalArgumentException("File descriptors passed in Intent");
10869 }
10870
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010871 checkValidCaller(Binder.getCallingUid(), userId);
10872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010874 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010876 }
10877
10878 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010879 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 // Refuse possible leaked file descriptors
10881 if (service != null && service.hasFileDescriptors() == true) {
10882 throw new IllegalArgumentException("File descriptors passed in Intent");
10883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010884 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010885 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 }
10888
10889 public boolean stopServiceToken(ComponentName className, IBinder token,
10890 int startId) {
10891 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010892 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 }
10895
10896 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010897 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010898 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010899 mServices.setServiceForegroundLocked(className, token, id, notification,
10900 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 }
10902 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010903
Dianne Hackborn41203752012-08-31 14:05:51 -070010904 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10905 boolean requireFull, String name, String callerPackage) {
10906 synchronized(this) {
10907 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10908 requireFull, name, callerPackage);
10909 }
10910 }
10911
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010912 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10913 boolean requireFull, String name, String callerPackage) {
10914 final int callingUserId = UserHandle.getUserId(callingUid);
10915 if (callingUserId != userId) {
10916 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10917 if ((requireFull || checkComponentPermission(
10918 android.Manifest.permission.INTERACT_ACROSS_USERS,
10919 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10920 && checkComponentPermission(
10921 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10922 callingPid, callingUid, -1, true)
10923 != PackageManager.PERMISSION_GRANTED) {
10924 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10925 // In this case, they would like to just execute as their
10926 // owner user instead of failing.
10927 userId = callingUserId;
10928 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010929 StringBuilder builder = new StringBuilder(128);
10930 builder.append("Permission Denial: ");
10931 builder.append(name);
10932 if (callerPackage != null) {
10933 builder.append(" from ");
10934 builder.append(callerPackage);
10935 }
10936 builder.append(" asks to run as user ");
10937 builder.append(userId);
10938 builder.append(" but is calling from user ");
10939 builder.append(UserHandle.getUserId(callingUid));
10940 builder.append("; this requires ");
10941 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10942 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010943 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010944 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10945 }
10946 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010947 Slog.w(TAG, msg);
10948 throw new SecurityException(msg);
10949 }
10950 }
10951 }
10952 if (userId == UserHandle.USER_CURRENT
10953 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10954 userId = mCurrentUserId;
10955 }
10956 if (!allowAll && userId < 0) {
10957 throw new IllegalArgumentException(
10958 "Call does not support special user #" + userId);
10959 }
10960 }
10961 return userId;
10962 }
10963
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010964 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10965 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010966 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010967 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010968 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10969 if (ActivityManager.checkUidPermission(
10970 android.Manifest.permission.INTERACT_ACROSS_USERS,
10971 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10972 ComponentName comp = new ComponentName(aInfo.packageName, className);
10973 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10974 + " requests FLAG_SINGLE_USER, but app does not hold "
10975 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10976 Slog.w(TAG, msg);
10977 throw new SecurityException(msg);
10978 }
10979 result = true;
10980 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010981 } else if (componentProcessName == aInfo.packageName) {
10982 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10983 } else if ("system".equals(componentProcessName)) {
10984 result = true;
10985 }
10986 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010987 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10988 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010989 }
10990 return result;
10991 }
10992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010993 public int bindService(IApplicationThread caller, IBinder token,
10994 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010995 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010996 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 // Refuse possible leaked file descriptors
10998 if (service != null && service.hasFileDescriptors() == true) {
10999 throw new IllegalArgumentException("File descriptors passed in Intent");
11000 }
11001
11002 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011003 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11004 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011005 }
11006 }
11007
11008 public boolean unbindService(IServiceConnection connection) {
11009 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011010 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 }
11013
11014 public void publishService(IBinder token, Intent intent, IBinder service) {
11015 // Refuse possible leaked file descriptors
11016 if (intent != null && intent.hasFileDescriptors() == true) {
11017 throw new IllegalArgumentException("File descriptors passed in Intent");
11018 }
11019
11020 synchronized(this) {
11021 if (!(token instanceof ServiceRecord)) {
11022 throw new IllegalArgumentException("Invalid service token");
11023 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011024 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 }
11026 }
11027
11028 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11029 // Refuse possible leaked file descriptors
11030 if (intent != null && intent.hasFileDescriptors() == true) {
11031 throw new IllegalArgumentException("File descriptors passed in Intent");
11032 }
11033
11034 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011035 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 }
11037 }
11038
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011039 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 synchronized(this) {
11041 if (!(token instanceof ServiceRecord)) {
11042 throw new IllegalArgumentException("Invalid service token");
11043 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011044 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011046 }
11047
11048 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011049 // BACKUP AND RESTORE
11050 // =========================================================
11051
11052 // Cause the target app to be launched if necessary and its backup agent
11053 // instantiated. The backup agent will invoke backupAgentCreated() on the
11054 // activity manager to announce its creation.
11055 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011056 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011057 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11058
11059 synchronized(this) {
11060 // !!! TODO: currently no check here that we're already bound
11061 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11062 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11063 synchronized (stats) {
11064 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11065 }
11066
Dianne Hackborne7f97212011-02-24 14:40:20 -080011067 // Backup agent is now in use, its package can't be stopped.
11068 try {
11069 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011070 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011071 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011072 } catch (IllegalArgumentException e) {
11073 Slog.w(TAG, "Failed trying to unstop package "
11074 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011075 }
11076
Christopher Tate181fafa2009-05-14 11:12:14 -070011077 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011078 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11079 ? new ComponentName(app.packageName, app.backupAgentName)
11080 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011081 // startProcessLocked() returns existing proc's record if it's already running
11082 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011083 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011084 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011085 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011086 return false;
11087 }
11088
11089 r.app = proc;
11090 mBackupTarget = r;
11091 mBackupAppName = app.packageName;
11092
Christopher Tate6fa95972009-06-05 18:43:55 -070011093 // Try not to kill the process during backup
11094 updateOomAdjLocked(proc);
11095
Christopher Tate181fafa2009-05-14 11:12:14 -070011096 // If the process is already attached, schedule the creation of the backup agent now.
11097 // If it is not yet live, this will be done when it attaches to the framework.
11098 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011099 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011100 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011101 proc.thread.scheduleCreateBackupAgent(app,
11102 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011103 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011104 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011105 }
11106 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011107 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011108 }
11109 // Invariants: at this point, the target app process exists and the application
11110 // is either already running or in the process of coming up. mBackupTarget and
11111 // mBackupAppName describe the app, so that when it binds back to the AM we
11112 // know that it's scheduled for a backup-agent operation.
11113 }
11114
11115 return true;
11116 }
11117
11118 // A backup agent has just come up
11119 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011120 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011121 + " = " + agent);
11122
11123 synchronized(this) {
11124 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011125 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011126 return;
11127 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011128 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011129
Dianne Hackborn06740692010-09-22 22:46:21 -070011130 long oldIdent = Binder.clearCallingIdentity();
11131 try {
11132 IBackupManager bm = IBackupManager.Stub.asInterface(
11133 ServiceManager.getService(Context.BACKUP_SERVICE));
11134 bm.agentConnected(agentPackageName, agent);
11135 } catch (RemoteException e) {
11136 // can't happen; the backup manager service is local
11137 } catch (Exception e) {
11138 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11139 e.printStackTrace();
11140 } finally {
11141 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011142 }
11143 }
11144
11145 // done with this agent
11146 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011147 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011148 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011149 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011150 return;
11151 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011152
11153 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011154 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011155 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011156 return;
11157 }
11158
Christopher Tate181fafa2009-05-14 11:12:14 -070011159 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011160 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011161 return;
11162 }
11163
Christopher Tate6fa95972009-06-05 18:43:55 -070011164 ProcessRecord proc = mBackupTarget.app;
11165 mBackupTarget = null;
11166 mBackupAppName = null;
11167
11168 // Not backing this app up any more; reset its OOM adjustment
11169 updateOomAdjLocked(proc);
11170
Christopher Tatec7b31e32009-06-10 15:49:30 -070011171 // If the app crashed during backup, 'thread' will be null here
11172 if (proc.thread != null) {
11173 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011174 proc.thread.scheduleDestroyBackupAgent(appInfo,
11175 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011176 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011177 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011178 e.printStackTrace();
11179 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011180 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011181 }
11182 }
11183 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 // BROADCASTS
11185 // =========================================================
11186
Josh Bartel7f208742010-02-25 11:01:44 -060011187 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011188 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011189 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011190 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11191 if (stickies == null) {
11192 return cur;
11193 }
11194 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011195 if (list == null) {
11196 return cur;
11197 }
11198 int N = list.size();
11199 for (int i=0; i<N; i++) {
11200 Intent intent = list.get(i);
11201 if (filter.match(resolver, intent, true, TAG) >= 0) {
11202 if (cur == null) {
11203 cur = new ArrayList<Intent>();
11204 }
11205 cur.add(intent);
11206 }
11207 }
11208 return cur;
11209 }
11210
Christopher Tatef46723b2012-01-26 14:19:24 -080011211 boolean isPendingBroadcastProcessLocked(int pid) {
11212 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11213 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215
Christopher Tatef46723b2012-01-26 14:19:24 -080011216 void skipPendingBroadcastLocked(int pid) {
11217 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11218 for (BroadcastQueue queue : mBroadcastQueues) {
11219 queue.skipPendingBroadcastLocked(pid);
11220 }
11221 }
11222
11223 // The app just attached; send any pending broadcasts that it should receive
11224 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11225 boolean didSomething = false;
11226 for (BroadcastQueue queue : mBroadcastQueues) {
11227 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011228 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011229 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 }
11231
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011232 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011233 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011234 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011235 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011236 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 synchronized(this) {
11238 ProcessRecord callerApp = null;
11239 if (caller != null) {
11240 callerApp = getRecordForAppLocked(caller);
11241 if (callerApp == null) {
11242 throw new SecurityException(
11243 "Unable to find app for caller " + caller
11244 + " (pid=" + Binder.getCallingPid()
11245 + ") when registering receiver " + receiver);
11246 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011247 if (callerApp.info.uid != Process.SYSTEM_UID &&
11248 !callerApp.pkgList.contains(callerPackage)) {
11249 throw new SecurityException("Given caller package " + callerPackage
11250 + " is not running in process " + callerApp);
11251 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011252 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011253 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011254 } else {
11255 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011256 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011257 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011258 }
11259
Dianne Hackborn20e80982012-08-31 19:00:44 -070011260 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11261 true, true, "registerReceiver", callerPackage);
11262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011263 List allSticky = null;
11264
11265 // Look for any matching sticky broadcasts...
11266 Iterator actions = filter.actionsIterator();
11267 if (actions != null) {
11268 while (actions.hasNext()) {
11269 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011270 allSticky = getStickiesLocked(action, filter, allSticky,
11271 UserHandle.USER_ALL);
11272 allSticky = getStickiesLocked(action, filter, allSticky,
11273 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 }
11275 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011276 allSticky = getStickiesLocked(null, filter, allSticky,
11277 UserHandle.USER_ALL);
11278 allSticky = getStickiesLocked(null, filter, allSticky,
11279 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 }
11281
11282 // The first sticky in the list is returned directly back to
11283 // the client.
11284 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11285
Joe Onorato8a9b2202010-02-26 18:56:32 -080011286 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 + ": " + sticky);
11288
11289 if (receiver == null) {
11290 return sticky;
11291 }
11292
11293 ReceiverList rl
11294 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11295 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011296 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11297 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 if (rl.app != null) {
11299 rl.app.receivers.add(rl);
11300 } else {
11301 try {
11302 receiver.asBinder().linkToDeath(rl, 0);
11303 } catch (RemoteException e) {
11304 return sticky;
11305 }
11306 rl.linkedToDeath = true;
11307 }
11308 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011309 } else if (rl.uid != callingUid) {
11310 throw new IllegalArgumentException(
11311 "Receiver requested to register for uid " + callingUid
11312 + " was previously registered for uid " + rl.uid);
11313 } else if (rl.pid != callingPid) {
11314 throw new IllegalArgumentException(
11315 "Receiver requested to register for pid " + callingPid
11316 + " was previously registered for pid " + rl.pid);
11317 } else if (rl.userId != userId) {
11318 throw new IllegalArgumentException(
11319 "Receiver requested to register for user " + userId
11320 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011322 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011323 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324 rl.add(bf);
11325 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011326 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327 }
11328 mReceiverResolver.addFilter(bf);
11329
11330 // Enqueue broadcasts for all existing stickies that match
11331 // this filter.
11332 if (allSticky != null) {
11333 ArrayList receivers = new ArrayList();
11334 receivers.add(bf);
11335
11336 int N = allSticky.size();
11337 for (int i=0; i<N; i++) {
11338 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011339 BroadcastQueue queue = broadcastQueueForIntent(intent);
11340 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011342 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011343 queue.enqueueParallelBroadcastLocked(r);
11344 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011345 }
11346 }
11347
11348 return sticky;
11349 }
11350 }
11351
11352 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011353 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354
Christopher Tatef46723b2012-01-26 14:19:24 -080011355 final long origId = Binder.clearCallingIdentity();
11356 try {
11357 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358
Christopher Tatef46723b2012-01-26 14:19:24 -080011359 synchronized(this) {
11360 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011361 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011362 if (rl != null) {
11363 if (rl.curBroadcast != null) {
11364 BroadcastRecord r = rl.curBroadcast;
11365 final boolean doNext = finishReceiverLocked(
11366 receiver.asBinder(), r.resultCode, r.resultData,
11367 r.resultExtras, r.resultAbort, true);
11368 if (doNext) {
11369 doTrim = true;
11370 r.queue.processNextBroadcast(false);
11371 }
11372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373
Christopher Tatef46723b2012-01-26 14:19:24 -080011374 if (rl.app != null) {
11375 rl.app.receivers.remove(rl);
11376 }
11377 removeReceiverLocked(rl);
11378 if (rl.linkedToDeath) {
11379 rl.linkedToDeath = false;
11380 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 }
11383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384
Christopher Tatef46723b2012-01-26 14:19:24 -080011385 // If we actually concluded any broadcasts, we might now be able
11386 // to trim the recipients' apps from our working set
11387 if (doTrim) {
11388 trimApplications();
11389 return;
11390 }
11391
11392 } finally {
11393 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 }
11396
11397 void removeReceiverLocked(ReceiverList rl) {
11398 mRegisteredReceivers.remove(rl.receiver.asBinder());
11399 int N = rl.size();
11400 for (int i=0; i<N; i++) {
11401 mReceiverResolver.removeFilter(rl.get(i));
11402 }
11403 }
11404
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011405 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011406 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11407 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011408 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011409 try {
11410 r.thread.dispatchPackageBroadcast(cmd, packages);
11411 } catch (RemoteException ex) {
11412 }
11413 }
11414 }
11415 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011416
11417 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11418 int[] users) {
11419 List<ResolveInfo> receivers = null;
11420 try {
11421 HashSet<ComponentName> singleUserReceivers = null;
11422 boolean scannedFirstReceivers = false;
11423 for (int user : users) {
11424 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11425 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11426 if (newReceivers != null && newReceivers.size() == 0) {
11427 newReceivers = null;
11428 }
11429 if (receivers == null) {
11430 receivers = newReceivers;
11431 } else if (newReceivers != null) {
11432 // We need to concatenate the additional receivers
11433 // found with what we have do far. This would be easy,
11434 // but we also need to de-dup any receivers that are
11435 // singleUser.
11436 if (!scannedFirstReceivers) {
11437 // Collect any single user receivers we had already retrieved.
11438 scannedFirstReceivers = true;
11439 for (int i=0; i<receivers.size(); i++) {
11440 ResolveInfo ri = receivers.get(i);
11441 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11442 ComponentName cn = new ComponentName(
11443 ri.activityInfo.packageName, ri.activityInfo.name);
11444 if (singleUserReceivers == null) {
11445 singleUserReceivers = new HashSet<ComponentName>();
11446 }
11447 singleUserReceivers.add(cn);
11448 }
11449 }
11450 }
11451 // Add the new results to the existing results, tracking
11452 // and de-dupping single user receivers.
11453 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011454 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011455 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11456 ComponentName cn = new ComponentName(
11457 ri.activityInfo.packageName, ri.activityInfo.name);
11458 if (singleUserReceivers == null) {
11459 singleUserReceivers = new HashSet<ComponentName>();
11460 }
11461 if (!singleUserReceivers.contains(cn)) {
11462 singleUserReceivers.add(cn);
11463 receivers.add(ri);
11464 }
11465 } else {
11466 receivers.add(ri);
11467 }
11468 }
11469 }
11470 }
11471 } catch (RemoteException ex) {
11472 // pm is in same process, this will never happen.
11473 }
11474 return receivers;
11475 }
11476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 private final int broadcastIntentLocked(ProcessRecord callerApp,
11478 String callerPackage, Intent intent, String resolvedType,
11479 IIntentReceiver resultTo, int resultCode, String resultData,
11480 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011481 boolean ordered, boolean sticky, int callingPid, int callingUid,
11482 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 intent = new Intent(intent);
11484
Dianne Hackborne7f97212011-02-24 14:40:20 -080011485 // By default broadcasts do not go to stopped apps.
11486 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11487
Joe Onorato8a9b2202010-02-26 18:56:32 -080011488 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011490 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011492 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011494
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011495 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11496 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011497
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011498 // Make sure that the user who is receiving this broadcast is started
11499 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011500 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011501 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11502 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11503 Slog.w(TAG, "Skipping broadcast of " + intent
11504 + ": user " + userId + " is stopped");
11505 return ActivityManager.BROADCAST_SUCCESS;
11506 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011507 }
11508
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011509 /*
11510 * Prevent non-system code (defined here to be non-persistent
11511 * processes) from sending protected broadcasts.
11512 */
11513 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11514 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11515 callingUid == 0) {
11516 // Always okay.
11517 } else if (callerApp == null || !callerApp.persistent) {
11518 try {
11519 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11520 intent.getAction())) {
11521 String msg = "Permission Denial: not allowed to send broadcast "
11522 + intent.getAction() + " from pid="
11523 + callingPid + ", uid=" + callingUid;
11524 Slog.w(TAG, msg);
11525 throw new SecurityException(msg);
11526 }
11527 } catch (RemoteException e) {
11528 Slog.w(TAG, "Remote exception", e);
11529 return ActivityManager.BROADCAST_SUCCESS;
11530 }
11531 }
11532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533 // Handle special intents: if this broadcast is from the package
11534 // manager about a package being removed, we need to remove all of
11535 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011536 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011538 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11539 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011540 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011541 || uidRemoved) {
11542 if (checkComponentPermission(
11543 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011544 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011545 == PackageManager.PERMISSION_GRANTED) {
11546 if (uidRemoved) {
11547 final Bundle intentExtras = intent.getExtras();
11548 final int uid = intentExtras != null
11549 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11550 if (uid >= 0) {
11551 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11552 synchronized (bs) {
11553 bs.removeUidStatsLocked(uid);
11554 }
11555 }
11556 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011557 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011558 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011559 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011560 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11561 if (list != null && (list.length > 0)) {
11562 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011563 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011564 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011565 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011566 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011567 }
11568 } else {
11569 Uri data = intent.getData();
11570 String ssp;
11571 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11572 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11573 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011574 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11575 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011576 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011577 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011578 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011579 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011581 }
11582 }
11583 }
11584 } else {
11585 String msg = "Permission Denial: " + intent.getAction()
11586 + " broadcast from " + callerPackage + " (pid=" + callingPid
11587 + ", uid=" + callingUid + ")"
11588 + " requires "
11589 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011590 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 throw new SecurityException(msg);
11592 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011593
11594 // Special case for adding a package: by default turn on compatibility
11595 // mode.
11596 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011597 Uri data = intent.getData();
11598 String ssp;
11599 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11600 mCompatModePackages.handlePackageAddedLocked(ssp,
11601 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011603 }
11604
11605 /*
11606 * If this is the time zone changed action, queue up a message that will reset the timezone
11607 * of all currently running processes. This message will get queued up before the broadcast
11608 * happens.
11609 */
11610 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11611 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11612 }
11613
Robert Greenwalt03595d02010-11-02 14:08:23 -070011614 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11615 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11616 }
11617
Robert Greenwalt434203a2010-10-11 16:00:27 -070011618 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11619 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11620 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11621 }
11622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 // Add to the sticky list if requested.
11624 if (sticky) {
11625 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11626 callingPid, callingUid)
11627 != PackageManager.PERMISSION_GRANTED) {
11628 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11629 + callingPid + ", uid=" + callingUid
11630 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011631 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011632 throw new SecurityException(msg);
11633 }
11634 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011635 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011637 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638 }
11639 if (intent.getComponent() != null) {
11640 throw new SecurityException(
11641 "Sticky broadcasts can't target a specific component");
11642 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011643 // We use userId directly here, since the "all" target is maintained
11644 // as a separate set of sticky broadcasts.
11645 if (userId != UserHandle.USER_ALL) {
11646 // But first, if this is not a broadcast to all users, then
11647 // make sure it doesn't conflict with an existing broadcast to
11648 // all users.
11649 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11650 UserHandle.USER_ALL);
11651 if (stickies != null) {
11652 ArrayList<Intent> list = stickies.get(intent.getAction());
11653 if (list != null) {
11654 int N = list.size();
11655 int i;
11656 for (i=0; i<N; i++) {
11657 if (intent.filterEquals(list.get(i))) {
11658 throw new IllegalArgumentException(
11659 "Sticky broadcast " + intent + " for user "
11660 + userId + " conflicts with existing global broadcast");
11661 }
11662 }
11663 }
11664 }
11665 }
11666 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11667 if (stickies == null) {
11668 stickies = new HashMap<String, ArrayList<Intent>>();
11669 mStickyBroadcasts.put(userId, stickies);
11670 }
11671 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672 if (list == null) {
11673 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011674 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 }
11676 int N = list.size();
11677 int i;
11678 for (i=0; i<N; i++) {
11679 if (intent.filterEquals(list.get(i))) {
11680 // This sticky already exists, replace it.
11681 list.set(i, new Intent(intent));
11682 break;
11683 }
11684 }
11685 if (i >= N) {
11686 list.add(new Intent(intent));
11687 }
11688 }
11689
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011690 int[] users;
11691 if (userId == UserHandle.USER_ALL) {
11692 // Caller wants broadcast to go to all started users.
11693 users = new int[mStartedUsers.size()];
11694 for (int i=0; i<mStartedUsers.size(); i++) {
11695 users[i] = mStartedUsers.keyAt(i);
11696 }
11697 } else {
11698 // Caller wants broadcast to go to one specific user.
11699 users = new int[] {userId};
11700 }
11701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011702 // Figure out who all will receive this broadcast.
11703 List receivers = null;
11704 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011705 // Need to resolve the intent to interested receivers...
11706 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11707 == 0) {
11708 receivers = collectReceiverComponents(intent, resolvedType, users);
11709 }
11710 if (intent.getComponent() == null) {
11711 registeredReceivers = mReceiverResolver.queryIntent(intent,
11712 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 }
11714
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011715 final boolean replacePending =
11716 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11717
Joe Onorato8a9b2202010-02-26 18:56:32 -080011718 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011719 + " replacePending=" + replacePending);
11720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11722 if (!ordered && NR > 0) {
11723 // If we are not serializing this broadcast, then send the
11724 // registered receivers separately so they don't wait for the
11725 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011726 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11727 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011728 callerPackage, callingPid, callingUid, requiredPermission,
11729 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011730 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011731 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011732 TAG, "Enqueueing parallel broadcast " + r);
11733 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011734 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011735 queue.enqueueParallelBroadcastLocked(r);
11736 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011738 registeredReceivers = null;
11739 NR = 0;
11740 }
11741
11742 // Merge into one list.
11743 int ir = 0;
11744 if (receivers != null) {
11745 // A special case for PACKAGE_ADDED: do not allow the package
11746 // being added to see this broadcast. This prevents them from
11747 // using this as a back door to get run as soon as they are
11748 // installed. Maybe in the future we want to have a special install
11749 // broadcast or such for apps, but we'd like to deliberately make
11750 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011751 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011752 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11753 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11754 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011755 Uri data = intent.getData();
11756 if (data != null) {
11757 String pkgName = data.getSchemeSpecificPart();
11758 if (pkgName != null) {
11759 skipPackages = new String[] { pkgName };
11760 }
11761 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011762 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011763 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011764 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011765 if (skipPackages != null && (skipPackages.length > 0)) {
11766 for (String skipPackage : skipPackages) {
11767 if (skipPackage != null) {
11768 int NT = receivers.size();
11769 for (int it=0; it<NT; it++) {
11770 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11771 if (curt.activityInfo.packageName.equals(skipPackage)) {
11772 receivers.remove(it);
11773 it--;
11774 NT--;
11775 }
11776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777 }
11778 }
11779 }
11780
11781 int NT = receivers != null ? receivers.size() : 0;
11782 int it = 0;
11783 ResolveInfo curt = null;
11784 BroadcastFilter curr = null;
11785 while (it < NT && ir < NR) {
11786 if (curt == null) {
11787 curt = (ResolveInfo)receivers.get(it);
11788 }
11789 if (curr == null) {
11790 curr = registeredReceivers.get(ir);
11791 }
11792 if (curr.getPriority() >= curt.priority) {
11793 // Insert this broadcast record into the final list.
11794 receivers.add(it, curr);
11795 ir++;
11796 curr = null;
11797 it++;
11798 NT++;
11799 } else {
11800 // Skip to the next ResolveInfo in the final list.
11801 it++;
11802 curt = null;
11803 }
11804 }
11805 }
11806 while (ir < NR) {
11807 if (receivers == null) {
11808 receivers = new ArrayList();
11809 }
11810 receivers.add(registeredReceivers.get(ir));
11811 ir++;
11812 }
11813
11814 if ((receivers != null && receivers.size() > 0)
11815 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011816 BroadcastQueue queue = broadcastQueueForIntent(intent);
11817 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011819 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011820 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011821 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011823 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 if (DEBUG_BROADCAST) {
11825 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011826 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011828 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011829 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011830 queue.enqueueOrderedBroadcastLocked(r);
11831 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011833 }
11834
Dianne Hackborna4972e92012-03-14 10:38:05 -070011835 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 }
11837
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011838 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839 // Refuse possible leaked file descriptors
11840 if (intent != null && intent.hasFileDescriptors() == true) {
11841 throw new IllegalArgumentException("File descriptors passed in Intent");
11842 }
11843
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011844 int flags = intent.getFlags();
11845
11846 if (!mProcessesReady) {
11847 // if the caller really truly claims to know what they're doing, go
11848 // ahead and allow the broadcast without launching any receivers
11849 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11850 intent = new Intent(intent);
11851 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11852 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11853 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11854 + " before boot completion");
11855 throw new IllegalStateException("Cannot broadcast before boot completed");
11856 }
11857 }
11858
11859 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11860 throw new IllegalArgumentException(
11861 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11862 }
11863
11864 return intent;
11865 }
11866
11867 public final int broadcastIntent(IApplicationThread caller,
11868 Intent intent, String resolvedType, IIntentReceiver resultTo,
11869 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011870 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011871 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011872 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011873 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11876 final int callingPid = Binder.getCallingPid();
11877 final int callingUid = Binder.getCallingUid();
11878 final long origId = Binder.clearCallingIdentity();
11879 int res = broadcastIntentLocked(callerApp,
11880 callerApp != null ? callerApp.info.packageName : null,
11881 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011882 resultCode, resultData, map, requiredPermission, serialized, sticky,
11883 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 Binder.restoreCallingIdentity(origId);
11885 return res;
11886 }
11887 }
11888
11889 int broadcastIntentInPackage(String packageName, int uid,
11890 Intent intent, String resolvedType, IIntentReceiver resultTo,
11891 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011892 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011893 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011894 intent = verifyBroadcastLocked(intent);
11895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 final long origId = Binder.clearCallingIdentity();
11897 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11898 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011899 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 Binder.restoreCallingIdentity(origId);
11901 return res;
11902 }
11903 }
11904
Amith Yamasani742a6712011-05-04 14:49:28 -070011905 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011906 // Refuse possible leaked file descriptors
11907 if (intent != null && intent.hasFileDescriptors() == true) {
11908 throw new IllegalArgumentException("File descriptors passed in Intent");
11909 }
11910
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011911 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11912 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011914 synchronized(this) {
11915 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11916 != PackageManager.PERMISSION_GRANTED) {
11917 String msg = "Permission Denial: unbroadcastIntent() from pid="
11918 + Binder.getCallingPid()
11919 + ", uid=" + Binder.getCallingUid()
11920 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011921 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 throw new SecurityException(msg);
11923 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011924 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11925 if (stickies != null) {
11926 ArrayList<Intent> list = stickies.get(intent.getAction());
11927 if (list != null) {
11928 int N = list.size();
11929 int i;
11930 for (i=0; i<N; i++) {
11931 if (intent.filterEquals(list.get(i))) {
11932 list.remove(i);
11933 break;
11934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011935 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011936 if (list.size() <= 0) {
11937 stickies.remove(intent.getAction());
11938 }
11939 }
11940 if (stickies.size() <= 0) {
11941 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011942 }
11943 }
11944 }
11945 }
11946
11947 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11948 String resultData, Bundle resultExtras, boolean resultAbort,
11949 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011950 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11951 if (r == null) {
11952 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011953 return false;
11954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011955
Christopher Tatef46723b2012-01-26 14:19:24 -080011956 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11957 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011958 }
11959
11960 public void finishReceiver(IBinder who, int resultCode, String resultData,
11961 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011962 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011963
11964 // Refuse possible leaked file descriptors
11965 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11966 throw new IllegalArgumentException("File descriptors passed in Bundle");
11967 }
11968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011969 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011970 try {
11971 boolean doNext = false;
11972 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011973
Christopher Tatef46723b2012-01-26 14:19:24 -080011974 synchronized(this) {
11975 r = broadcastRecordForReceiverLocked(who);
11976 if (r != null) {
11977 doNext = r.queue.finishReceiverLocked(r, resultCode,
11978 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011980 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011981
Christopher Tatef46723b2012-01-26 14:19:24 -080011982 if (doNext) {
11983 r.queue.processNextBroadcast(false);
11984 }
11985 trimApplications();
11986 } finally {
11987 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 // =========================================================
11992 // INSTRUMENTATION
11993 // =========================================================
11994
11995 public boolean startInstrumentation(ComponentName className,
11996 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011997 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011998 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011999 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
12000 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001 // Refuse possible leaked file descriptors
12002 if (arguments != null && arguments.hasFileDescriptors()) {
12003 throw new IllegalArgumentException("File descriptors passed in Bundle");
12004 }
12005
12006 synchronized(this) {
12007 InstrumentationInfo ii = null;
12008 ApplicationInfo ai = null;
12009 try {
12010 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012011 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012012 ai = AppGlobals.getPackageManager().getApplicationInfo(
12013 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012015 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 }
12017 if (ii == null) {
12018 reportStartInstrumentationFailure(watcher, className,
12019 "Unable to find instrumentation info for: " + className);
12020 return false;
12021 }
12022 if (ai == null) {
12023 reportStartInstrumentationFailure(watcher, className,
12024 "Unable to find instrumentation target package: " + ii.targetPackage);
12025 return false;
12026 }
12027
12028 int match = mContext.getPackageManager().checkSignatures(
12029 ii.targetPackage, ii.packageName);
12030 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12031 String msg = "Permission Denial: starting instrumentation "
12032 + className + " from pid="
12033 + Binder.getCallingPid()
12034 + ", uid=" + Binder.getCallingPid()
12035 + " not allowed because package " + ii.packageName
12036 + " does not have a signature matching the target "
12037 + ii.targetPackage;
12038 reportStartInstrumentationFailure(watcher, className, msg);
12039 throw new SecurityException(msg);
12040 }
12041
12042 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012043 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012044 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012045 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012047 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012048 app.instrumentationProfileFile = profileFile;
12049 app.instrumentationArguments = arguments;
12050 app.instrumentationWatcher = watcher;
12051 app.instrumentationResultClass = className;
12052 Binder.restoreCallingIdentity(origId);
12053 }
12054
12055 return true;
12056 }
12057
12058 /**
12059 * Report errors that occur while attempting to start Instrumentation. Always writes the
12060 * error to the logs, but if somebody is watching, send the report there too. This enables
12061 * the "am" command to report errors with more information.
12062 *
12063 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12064 * @param cn The component name of the instrumentation.
12065 * @param report The error report.
12066 */
12067 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12068 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012069 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 try {
12071 if (watcher != null) {
12072 Bundle results = new Bundle();
12073 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12074 results.putString("Error", report);
12075 watcher.instrumentationStatus(cn, -1, results);
12076 }
12077 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012078 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012079 }
12080 }
12081
12082 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12083 if (app.instrumentationWatcher != null) {
12084 try {
12085 // NOTE: IInstrumentationWatcher *must* be oneway here
12086 app.instrumentationWatcher.instrumentationFinished(
12087 app.instrumentationClass,
12088 resultCode,
12089 results);
12090 } catch (RemoteException e) {
12091 }
12092 }
12093 app.instrumentationWatcher = null;
12094 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012095 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 app.instrumentationProfileFile = null;
12097 app.instrumentationArguments = null;
12098
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012099 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 }
12101
12102 public void finishInstrumentation(IApplicationThread target,
12103 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012104 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 // Refuse possible leaked file descriptors
12106 if (results != null && results.hasFileDescriptors()) {
12107 throw new IllegalArgumentException("File descriptors passed in Intent");
12108 }
12109
12110 synchronized(this) {
12111 ProcessRecord app = getRecordForAppLocked(target);
12112 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012113 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012114 return;
12115 }
12116 final long origId = Binder.clearCallingIdentity();
12117 finishInstrumentationLocked(app, resultCode, results);
12118 Binder.restoreCallingIdentity(origId);
12119 }
12120 }
12121
12122 // =========================================================
12123 // CONFIGURATION
12124 // =========================================================
12125
12126 public ConfigurationInfo getDeviceConfigurationInfo() {
12127 ConfigurationInfo config = new ConfigurationInfo();
12128 synchronized (this) {
12129 config.reqTouchScreen = mConfiguration.touchscreen;
12130 config.reqKeyboardType = mConfiguration.keyboard;
12131 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012132 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12133 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012134 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12135 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012136 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12137 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12139 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012140 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012141 }
12142 return config;
12143 }
12144
12145 public Configuration getConfiguration() {
12146 Configuration ci;
12147 synchronized(this) {
12148 ci = new Configuration(mConfiguration);
12149 }
12150 return ci;
12151 }
12152
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012153 public void updatePersistentConfiguration(Configuration values) {
12154 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12155 "updateConfiguration()");
12156 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12157 "updateConfiguration()");
12158 if (values == null) {
12159 throw new NullPointerException("Configuration must not be null");
12160 }
12161
12162 synchronized(this) {
12163 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012164 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012165 Binder.restoreCallingIdentity(origId);
12166 }
12167 }
12168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 public void updateConfiguration(Configuration values) {
12170 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12171 "updateConfiguration()");
12172
12173 synchronized(this) {
12174 if (values == null && mWindowManager != null) {
12175 // sentinel: fetch the current configuration from the window manager
12176 values = mWindowManager.computeNewConfiguration();
12177 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012178
12179 if (mWindowManager != null) {
12180 mProcessList.applyDisplaySize(mWindowManager);
12181 }
12182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012184 if (values != null) {
12185 Settings.System.clearConfiguration(values);
12186 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012187 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012188 Binder.restoreCallingIdentity(origId);
12189 }
12190 }
12191
12192 /**
12193 * Do either or both things: (1) change the current configuration, and (2)
12194 * make sure the given activity is running with the (now) current
12195 * configuration. Returns true if the activity has been left running, or
12196 * false if <var>starting</var> is being destroyed to match the new
12197 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012198 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012199 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012200 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012201 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012202 // do nothing if we are headless
12203 if (mHeadless) return true;
12204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012205 int changes = 0;
12206
12207 boolean kept = true;
12208
12209 if (values != null) {
12210 Configuration newConfig = new Configuration(mConfiguration);
12211 changes = newConfig.updateFrom(values);
12212 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012213 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012214 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 }
12216
Doug Zongker2bec3d42009-12-04 12:52:44 -080012217 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218
Dianne Hackborn813075a62011-11-14 17:45:19 -080012219 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220 saveLocaleLocked(values.locale,
12221 !values.locale.equals(mConfiguration.locale),
12222 values.userSetLocale);
12223 }
12224
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012225 mConfigurationSeq++;
12226 if (mConfigurationSeq <= 0) {
12227 mConfigurationSeq = 1;
12228 }
12229 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012231 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012232
12233 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012234
12235 // TODO: If our config changes, should we auto dismiss any currently
12236 // showing dialogs?
12237 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012238
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012239 AttributeCache ac = AttributeCache.instance();
12240 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012241 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012243
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012244 // Make sure all resources in our process are updated
12245 // right now, so that anyone who is going to retrieve
12246 // resource values after we return will be sure to get
12247 // the new ones. This is especially important during
12248 // boot, where the first config change needs to guarantee
12249 // all resources have that config before following boot
12250 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012251 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012252
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012253 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012254 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012255 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012256 mHandler.sendMessage(msg);
12257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012258
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012259 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12260 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012261 try {
12262 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012263 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012264 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012265 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012266 }
12267 } catch (Exception e) {
12268 }
12269 }
12270 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012271 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12272 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012273 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012274 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012275 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12276 broadcastIntentLocked(null, null,
12277 new Intent(Intent.ACTION_LOCALE_CHANGED),
12278 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012279 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012281 }
12282 }
12283
12284 if (changes != 0 && starting == null) {
12285 // If the configuration changed, and the caller is not already
12286 // in the process of starting an activity, then find the top
12287 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012288 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289 }
12290
12291 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012292 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012293 // And we need to make sure at this point that all other activities
12294 // are made visible with the correct configuration.
12295 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012296 }
12297
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012298 if (values != null && mWindowManager != null) {
12299 mWindowManager.setNewConfiguration(mConfiguration);
12300 }
12301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012302 return kept;
12303 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012304
12305 /**
12306 * Decide based on the configuration whether we should shouw the ANR,
12307 * crash, etc dialogs. The idea is that if there is no affordnace to
12308 * press the on-screen buttons, we shouldn't show the dialog.
12309 *
12310 * A thought: SystemUI might also want to get told about this, the Power
12311 * dialog / global actions also might want different behaviors.
12312 */
12313 private static final boolean shouldShowDialogs(Configuration config) {
12314 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12315 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012317
12318 /**
12319 * Save the locale. You must be inside a synchronized (this) block.
12320 */
12321 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12322 if(isDiff) {
12323 SystemProperties.set("user.language", l.getLanguage());
12324 SystemProperties.set("user.region", l.getCountry());
12325 }
12326
12327 if(isPersist) {
12328 SystemProperties.set("persist.sys.language", l.getLanguage());
12329 SystemProperties.set("persist.sys.country", l.getCountry());
12330 SystemProperties.set("persist.sys.localevar", l.getVariant());
12331 }
12332 }
12333
Adam Powelldd8fab22012-03-22 17:47:27 -070012334 @Override
12335 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12336 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012337 return srec != null && srec.task.affinity != null &&
12338 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012339 }
12340
12341 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12342 Intent resultData) {
12343 ComponentName dest = destIntent.getComponent();
12344
12345 synchronized (this) {
12346 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012347 if (srec == null) {
12348 return false;
12349 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012350 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12351 final int start = history.indexOf(srec);
12352 if (start < 0) {
12353 // Current activity is not in history stack; do nothing.
12354 return false;
12355 }
12356 int finishTo = start - 1;
12357 ActivityRecord parent = null;
12358 boolean foundParentInTask = false;
12359 if (dest != null) {
12360 TaskRecord tr = srec.task;
12361 for (int i = start - 1; i >= 0; i--) {
12362 ActivityRecord r = history.get(i);
12363 if (tr != r.task) {
12364 // Couldn't find parent in the same task; stop at the one above this.
12365 // (Root of current task; in-app "home" behavior)
12366 // Always at least finish the current activity.
12367 finishTo = Math.min(start - 1, i + 1);
12368 parent = history.get(finishTo);
12369 break;
12370 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12371 r.info.name.equals(dest.getClassName())) {
12372 finishTo = i;
12373 parent = r;
12374 foundParentInTask = true;
12375 break;
12376 }
12377 }
12378 }
12379
12380 if (mController != null) {
12381 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12382 if (next != null) {
12383 // ask watcher if this is allowed
12384 boolean resumeOK = true;
12385 try {
12386 resumeOK = mController.activityResuming(next.packageName);
12387 } catch (RemoteException e) {
12388 mController = null;
12389 }
12390
12391 if (!resumeOK) {
12392 return false;
12393 }
12394 }
12395 }
12396 final long origId = Binder.clearCallingIdentity();
12397 for (int i = start; i > finishTo; i--) {
12398 ActivityRecord r = history.get(i);
12399 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012400 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012401 // Only return the supplied result for the first activity finished
12402 resultCode = Activity.RESULT_CANCELED;
12403 resultData = null;
12404 }
12405
12406 if (parent != null && foundParentInTask) {
12407 final int parentLaunchMode = parent.info.launchMode;
12408 final int destIntentFlags = destIntent.getFlags();
12409 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12410 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12411 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12412 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012413 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012414 } else {
12415 try {
12416 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012417 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012418 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12419 null, aInfo, parent.appToken, null,
12420 0, -1, parent.launchedFromUid, 0, null, true, null);
12421 foundParentInTask = res == ActivityManager.START_SUCCESS;
12422 } catch (RemoteException e) {
12423 foundParentInTask = false;
12424 }
12425 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012426 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012427 }
12428 }
12429 Binder.restoreCallingIdentity(origId);
12430 return foundParentInTask;
12431 }
12432 }
12433
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012434 public int getLaunchedFromUid(IBinder activityToken) {
12435 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12436 if (srec == null) {
12437 return -1;
12438 }
12439 return srec.launchedFromUid;
12440 }
12441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442 // =========================================================
12443 // LIFETIME MANAGEMENT
12444 // =========================================================
12445
Christopher Tatef46723b2012-01-26 14:19:24 -080012446 // Returns which broadcast queue the app is the current [or imminent] receiver
12447 // on, or 'null' if the app is not an active broadcast recipient.
12448 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12449 BroadcastRecord r = app.curReceiver;
12450 if (r != null) {
12451 return r.queue;
12452 }
12453
12454 // It's not the current receiver, but it might be starting up to become one
12455 synchronized (this) {
12456 for (BroadcastQueue queue : mBroadcastQueues) {
12457 r = queue.mPendingBroadcast;
12458 if (r != null && r.curApp == app) {
12459 // found it; report which queue it's in
12460 return queue;
12461 }
12462 }
12463 }
12464
12465 return null;
12466 }
12467
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012468 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012469 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012471 // This adjustment has already been computed. If we are calling
12472 // from the top, we may have already computed our adjustment with
12473 // an earlier hidden adjustment that isn't really for us... if
12474 // so, use the new hidden adjustment.
12475 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012476 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12477 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012478 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012479 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012480 }
12481
12482 if (app.thread == null) {
12483 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012484 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012485 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 }
12487
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012488 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12489 app.adjSource = null;
12490 app.adjTarget = null;
12491 app.empty = false;
12492 app.hidden = false;
12493
12494 final int activitiesSize = app.activities.size();
12495
Dianne Hackborn7d608422011-08-07 16:24:18 -070012496 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012497 // The max adjustment doesn't allow this app to be anything
12498 // below foreground, so it is not worth doing work for it.
12499 app.adjType = "fixed";
12500 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012501 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012502 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012503 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012504 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012505 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012506 // System process can do UI, and when they do we want to have
12507 // them trim their memory after the user leaves the UI. To
12508 // facilitate this, here we need to determine whether or not it
12509 // is currently showing UI.
12510 app.systemNoUi = true;
12511 if (app == TOP_APP) {
12512 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012513 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012514 } else if (activitiesSize > 0) {
12515 for (int j = 0; j < activitiesSize; j++) {
12516 final ActivityRecord r = app.activities.get(j);
12517 if (r.visible) {
12518 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012519 }
12520 if (r.app == app) {
12521 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012522 }
12523 }
12524 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012525 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012526 }
12527
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012528 app.keeping = false;
12529 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012530 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531
The Android Open Source Project4df24232009-03-05 14:34:35 -080012532 // Determine the importance of the process, starting with most
12533 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012534 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012535 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012536 boolean foregroundActivities = false;
12537 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012538 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012539 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012540 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012541 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012542 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012543 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012544 foregroundActivities = true;
12545 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012546 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012547 } else if (app.instrumentationClass != null) {
12548 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012549 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012550 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012551 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012552 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012553 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012554 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012555 // counts as being in the foreground for OOM killer purposes.
12556 // It's placed in a sched group based on the nature of the
12557 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012558 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012559 schedGroup = (queue == mFgBroadcastQueue)
12560 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012561 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 } else if (app.executingServices.size() > 0) {
12563 // An app that is currently executing a service callback also
12564 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012565 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012566 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012567 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012568 } else {
12569 // Assume process is hidden (has activities); we will correct
12570 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012571 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012572 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012573 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012574 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012575 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012576
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012577 boolean hasStoppingActivities = false;
12578
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012579 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012580 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012581 for (int j = 0; j < activitiesSize; j++) {
12582 final ActivityRecord r = app.activities.get(j);
12583 if (r.visible) {
12584 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012585 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12586 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012587 app.adjType = "visible";
12588 }
12589 schedGroup = Process.THREAD_GROUP_DEFAULT;
12590 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012591 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012592 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012593 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012594 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012595 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12596 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012597 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012598 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012599 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012600 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012601 } else if (r.state == ActivityState.STOPPING) {
12602 // We will apply the actual adjustment later, because
12603 // we want to allow this process to immediately go through
12604 // any memory trimming that is in effect.
12605 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012606 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012607 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012608 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012609 if (r.app == app) {
12610 app.hasActivities = true;
12611 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012612 }
12613 }
12614
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012615 if (adj == hiddenAdj && !app.hasActivities) {
12616 // Whoops, this process is completely empty as far as we know
12617 // at this point.
12618 adj = emptyAdj;
12619 app.empty = true;
12620 app.adjType = "bg-empty";
12621 }
12622
Dianne Hackborn7d608422011-08-07 16:24:18 -070012623 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012624 if (app.foregroundServices) {
12625 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012626 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012627 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012628 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012629 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012630 } else if (app.forcingToForeground != null) {
12631 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012632 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012633 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012634 app.adjType = "force-foreground";
12635 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012636 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012637 }
12638 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012639
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012640 if (app.foregroundServices) {
12641 interesting = true;
12642 }
12643
Dianne Hackborn7d608422011-08-07 16:24:18 -070012644 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012645 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012646 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012647 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012648 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012649 app.adjType = "heavy";
12650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012651
Dianne Hackborn7d608422011-08-07 16:24:18 -070012652 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012653 // This process is hosting what we currently consider to be the
12654 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012655 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012656 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012657 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012658 app.adjType = "home";
12659 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012660
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012661 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12662 && app.activities.size() > 0) {
12663 // This was the previous process that showed UI to the user.
12664 // We want to try to keep it around more aggressively, to give
12665 // a good experience around switching between two apps.
12666 adj = ProcessList.PREVIOUS_APP_ADJ;
12667 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12668 app.hidden = false;
12669 app.adjType = "previous";
12670 }
12671
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012672 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12673 + " reason=" + app.adjType);
12674
The Android Open Source Project4df24232009-03-05 14:34:35 -080012675 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012676 // there are applications dependent on our services or providers, but
12677 // this gives us a baseline and makes sure we don't get into an
12678 // infinite recursion.
12679 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012680 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681
Christopher Tate6fa95972009-06-05 18:43:55 -070012682 if (mBackupTarget != null && app == mBackupTarget.app) {
12683 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012684 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012685 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012686 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012687 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012688 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012689 }
12690 }
12691
Dianne Hackborn7d608422011-08-07 16:24:18 -070012692 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012693 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012694 final long now = SystemClock.uptimeMillis();
12695 // This process is more important if the top activity is
12696 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012697 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012698 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012699 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012700 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012701 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012702 // If this process has shown some UI, let it immediately
12703 // go to the LRU list because it may be pretty heavy with
12704 // UI stuff. We'll tag it with a label just to help
12705 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012706 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012707 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012709 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012710 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012711 // This service has seen some activity within
12712 // recent memory, so we will keep its process ahead
12713 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012714 if (adj > ProcessList.SERVICE_ADJ) {
12715 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012716 app.adjType = "started-services";
12717 app.hidden = false;
12718 }
12719 }
12720 // If we have let the service slide into the background
12721 // state, still have some text describing what it is doing
12722 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012723 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012724 app.adjType = "started-bg-services";
12725 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012726 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012727 // Don't kill this process because it is doing work; it
12728 // has said it is doing work.
12729 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012730 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012731 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012732 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012733 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012734 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012735 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012736 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012737 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012738 // XXX should compute this based on the max of
12739 // all connected clients.
12740 ConnectionRecord cr = clist.get(i);
12741 if (cr.binding.client == app) {
12742 // Binding to ourself is not interesting.
12743 continue;
12744 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012745 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012746 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012747 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012748 int myHiddenAdj = hiddenAdj;
12749 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012750 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012751 myHiddenAdj = client.hiddenAdj;
12752 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012753 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012754 }
12755 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012756 int myEmptyAdj = emptyAdj;
12757 if (myEmptyAdj > client.emptyAdj) {
12758 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12759 myEmptyAdj = client.emptyAdj;
12760 } else {
12761 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12762 }
12763 }
12764 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12765 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012766 String adjType = null;
12767 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12768 // Not doing bind OOM management, so treat
12769 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012770 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012771 // If this process has shown some UI, let it immediately
12772 // go to the LRU list because it may be pretty heavy with
12773 // UI stuff. We'll tag it with a label just to help
12774 // debug and understand what is going on.
12775 if (adj > clientAdj) {
12776 adjType = "bound-bg-ui-services";
12777 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012778 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012779 clientAdj = adj;
12780 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012781 if (now >= (s.lastActivity
12782 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012783 // This service has not seen activity within
12784 // recent memory, so allow it to drop to the
12785 // LRU list if there is no other reason to keep
12786 // it around. We'll also tag it with a label just
12787 // to help debug and undertand what is going on.
12788 if (adj > clientAdj) {
12789 adjType = "bound-bg-services";
12790 }
12791 clientAdj = adj;
12792 }
12793 }
12794 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012795 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012796 // If this process has recently shown UI, and
12797 // the process that is binding to it is less
12798 // important than being visible, then we don't
12799 // care about the binding as much as we care
12800 // about letting this process get into the LRU
12801 // list to be killed and restarted if needed for
12802 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012803 if (app.hasShownUi && app != mHomeProcess
12804 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012805 adjType = "bound-bg-ui-services";
12806 } else {
12807 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12808 |Context.BIND_IMPORTANT)) != 0) {
12809 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012810 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12811 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12812 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12813 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12814 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012815 adj = clientAdj;
12816 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012817 app.pendingUiClean = true;
12818 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12819 adj = ProcessList.VISIBLE_APP_ADJ;
12820 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012821 }
12822 if (!client.hidden) {
12823 app.hidden = false;
12824 }
12825 if (client.keeping) {
12826 app.keeping = true;
12827 }
12828 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012829 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012830 }
12831 if (adjType != null) {
12832 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012833 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12834 .REASON_SERVICE_IN_USE;
12835 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012836 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012837 app.adjTarget = s.name;
12838 }
12839 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12840 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12841 schedGroup = Process.THREAD_GROUP_DEFAULT;
12842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 }
12844 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012845 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12846 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012847 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012848 (a.visible || a.state == ActivityState.RESUMED
12849 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012850 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012851 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12852 schedGroup = Process.THREAD_GROUP_DEFAULT;
12853 }
12854 app.hidden = false;
12855 app.adjType = "service";
12856 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12857 .REASON_SERVICE_IN_USE;
12858 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012859 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012860 app.adjTarget = s.name;
12861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012863 }
12864 }
12865 }
12866 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012867
Dianne Hackborn287952c2010-09-22 22:34:31 -070012868 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012869 // would like to avoid killing it unless it would prevent the current
12870 // application from running. By default we put the process in
12871 // with the rest of the background processes; as we scan through
12872 // its services we may bump it up from there.
12873 if (adj > hiddenAdj) {
12874 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012875 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012876 app.adjType = "bg-services";
12877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012878 }
12879
Dianne Hackborn7d608422011-08-07 16:24:18 -070012880 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012881 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012882 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012883 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012884 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012885 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012886 for (int i = cpr.connections.size()-1;
12887 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12888 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12889 i--) {
12890 ContentProviderConnection conn = cpr.connections.get(i);
12891 ProcessRecord client = conn.client;
12892 if (client == app) {
12893 // Being our own client is not interesting.
12894 continue;
12895 }
12896 int myHiddenAdj = hiddenAdj;
12897 if (myHiddenAdj > client.hiddenAdj) {
12898 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12899 myHiddenAdj = client.hiddenAdj;
12900 } else {
12901 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012902 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012903 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012904 int myEmptyAdj = emptyAdj;
12905 if (myEmptyAdj > client.emptyAdj) {
12906 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12907 myEmptyAdj = client.emptyAdj;
12908 } else {
12909 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12910 }
12911 }
12912 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12913 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012914 if (adj > clientAdj) {
12915 if (app.hasShownUi && app != mHomeProcess
12916 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12917 app.adjType = "bg-ui-provider";
12918 } else {
12919 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12920 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12921 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012922 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012923 if (!client.hidden) {
12924 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012925 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012926 if (client.keeping) {
12927 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012928 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012929 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12930 .REASON_PROVIDER_IN_USE;
12931 app.adjSource = client;
12932 app.adjSourceOom = clientAdj;
12933 app.adjTarget = cpr.name;
12934 }
12935 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12936 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012937 }
12938 }
12939 // If the provider has external (non-framework) process
12940 // dependencies, ensure that its adjustment is at least
12941 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012942 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012943 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12944 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012945 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012946 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012947 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012948 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012949 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012950 }
12951 }
12952 }
12953 }
12954
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012955 if (adj == ProcessList.SERVICE_ADJ) {
12956 if (doingAll) {
12957 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12958 mNewNumServiceProcs++;
12959 }
12960 if (app.serviceb) {
12961 adj = ProcessList.SERVICE_B_ADJ;
12962 }
12963 } else {
12964 app.serviceb = false;
12965 }
12966
12967 app.nonStoppingAdj = adj;
12968
12969 if (hasStoppingActivities) {
12970 // Only upgrade adjustment.
12971 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12972 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12973 app.adjType = "stopping";
12974 }
12975 }
12976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 app.curRawAdj = adj;
12978
Joe Onorato8a9b2202010-02-26 18:56:32 -080012979 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012980 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12981 if (adj > app.maxAdj) {
12982 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012983 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012984 schedGroup = Process.THREAD_GROUP_DEFAULT;
12985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012986 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012987 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012988 app.keeping = true;
12989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012990
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012991 if (app.hasAboveClient) {
12992 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12993 // then we need to drop its adjustment to be lower than the service's
12994 // in order to honor the request. We want to drop it by one adjustment
12995 // level... but there is special meaning applied to various levels so
12996 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012997 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012998 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012999 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13000 adj = ProcessList.VISIBLE_APP_ADJ;
13001 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13002 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13003 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13004 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013005 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013006 adj++;
13007 }
13008 }
13009
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013010 int importance = app.memImportance;
13011 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13012 app.curAdj = adj;
13013 app.curSchedGroup = schedGroup;
13014 if (!interesting) {
13015 // For this reporting, if there is not something explicitly
13016 // interesting in this process then we will push it to the
13017 // background importance.
13018 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13019 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13020 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13021 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13022 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13023 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13024 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13025 } else if (adj >= ProcessList.SERVICE_ADJ) {
13026 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13027 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13028 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13029 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13030 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13031 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13032 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13033 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13034 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13035 } else {
13036 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13037 }
13038 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013039
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013040 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13041 if (foregroundActivities != app.foregroundActivities) {
13042 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13043 }
13044 if (changes != 0) {
13045 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13046 app.memImportance = importance;
13047 app.foregroundActivities = foregroundActivities;
13048 int i = mPendingProcessChanges.size()-1;
13049 ProcessChangeItem item = null;
13050 while (i >= 0) {
13051 item = mPendingProcessChanges.get(i);
13052 if (item.pid == app.pid) {
13053 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13054 break;
13055 }
13056 i--;
13057 }
13058 if (i < 0) {
13059 // No existing item in pending changes; need a new one.
13060 final int NA = mAvailProcessChanges.size();
13061 if (NA > 0) {
13062 item = mAvailProcessChanges.remove(NA-1);
13063 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13064 } else {
13065 item = new ProcessChangeItem();
13066 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13067 }
13068 item.changes = 0;
13069 item.pid = app.pid;
13070 item.uid = app.info.uid;
13071 if (mPendingProcessChanges.size() == 0) {
13072 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13073 "*** Enqueueing dispatch processes changed!");
13074 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13075 }
13076 mPendingProcessChanges.add(item);
13077 }
13078 item.changes |= changes;
13079 item.importance = importance;
13080 item.foregroundActivities = foregroundActivities;
13081 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13082 + Integer.toHexString(System.identityHashCode(item))
13083 + " " + app.toShortString() + ": changes=" + item.changes
13084 + " importance=" + item.importance
13085 + " foreground=" + item.foregroundActivities
13086 + " type=" + app.adjType + " source=" + app.adjSource
13087 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013088 }
13089
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013090 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013091 }
13092
13093 /**
13094 * Ask a given process to GC right now.
13095 */
13096 final void performAppGcLocked(ProcessRecord app) {
13097 try {
13098 app.lastRequestedGc = SystemClock.uptimeMillis();
13099 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013100 if (app.reportLowMemory) {
13101 app.reportLowMemory = false;
13102 app.thread.scheduleLowMemory();
13103 } else {
13104 app.thread.processInBackground();
13105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 }
13107 } catch (Exception e) {
13108 // whatever.
13109 }
13110 }
13111
13112 /**
13113 * Returns true if things are idle enough to perform GCs.
13114 */
Josh Bartel7f208742010-02-25 11:01:44 -060013115 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013116 boolean processingBroadcasts = false;
13117 for (BroadcastQueue q : mBroadcastQueues) {
13118 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13119 processingBroadcasts = true;
13120 }
13121 }
13122 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013123 && (mSleeping || (mMainStack.mResumedActivity != null &&
13124 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013125 }
13126
13127 /**
13128 * Perform GCs on all processes that are waiting for it, but only
13129 * if things are idle.
13130 */
13131 final void performAppGcsLocked() {
13132 final int N = mProcessesToGc.size();
13133 if (N <= 0) {
13134 return;
13135 }
Josh Bartel7f208742010-02-25 11:01:44 -060013136 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 while (mProcessesToGc.size() > 0) {
13138 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013139 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013140 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13141 <= SystemClock.uptimeMillis()) {
13142 // To avoid spamming the system, we will GC processes one
13143 // at a time, waiting a few seconds between each.
13144 performAppGcLocked(proc);
13145 scheduleAppGcsLocked();
13146 return;
13147 } else {
13148 // It hasn't been long enough since we last GCed this
13149 // process... put it in the list to wait for its time.
13150 addProcessToGcListLocked(proc);
13151 break;
13152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 }
13154 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013155
13156 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013157 }
13158 }
13159
13160 /**
13161 * If all looks good, perform GCs on all processes waiting for them.
13162 */
13163 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013164 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013165 performAppGcsLocked();
13166 return;
13167 }
13168 // Still not idle, wait some more.
13169 scheduleAppGcsLocked();
13170 }
13171
13172 /**
13173 * Schedule the execution of all pending app GCs.
13174 */
13175 final void scheduleAppGcsLocked() {
13176 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013177
13178 if (mProcessesToGc.size() > 0) {
13179 // Schedule a GC for the time to the next process.
13180 ProcessRecord proc = mProcessesToGc.get(0);
13181 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13182
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013183 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013184 long now = SystemClock.uptimeMillis();
13185 if (when < (now+GC_TIMEOUT)) {
13186 when = now + GC_TIMEOUT;
13187 }
13188 mHandler.sendMessageAtTime(msg, when);
13189 }
13190 }
13191
13192 /**
13193 * Add a process to the array of processes waiting to be GCed. Keeps the
13194 * list in sorted order by the last GC time. The process can't already be
13195 * on the list.
13196 */
13197 final void addProcessToGcListLocked(ProcessRecord proc) {
13198 boolean added = false;
13199 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13200 if (mProcessesToGc.get(i).lastRequestedGc <
13201 proc.lastRequestedGc) {
13202 added = true;
13203 mProcessesToGc.add(i+1, proc);
13204 break;
13205 }
13206 }
13207 if (!added) {
13208 mProcessesToGc.add(0, proc);
13209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 }
13211
13212 /**
13213 * Set up to ask a process to GC itself. This will either do it
13214 * immediately, or put it on the list of processes to gc the next
13215 * time things are idle.
13216 */
13217 final void scheduleAppGcLocked(ProcessRecord app) {
13218 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013219 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 return;
13221 }
13222 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013223 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013224 scheduleAppGcsLocked();
13225 }
13226 }
13227
Dianne Hackborn287952c2010-09-22 22:34:31 -070013228 final void checkExcessivePowerUsageLocked(boolean doKills) {
13229 updateCpuStatsNow();
13230
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013231 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013232 boolean doWakeKills = doKills;
13233 boolean doCpuKills = doKills;
13234 if (mLastPowerCheckRealtime == 0) {
13235 doWakeKills = false;
13236 }
13237 if (mLastPowerCheckUptime == 0) {
13238 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013239 }
13240 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013241 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013242 }
13243 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013244 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13245 final long curUptime = SystemClock.uptimeMillis();
13246 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13247 mLastPowerCheckRealtime = curRealtime;
13248 mLastPowerCheckUptime = curUptime;
13249 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13250 doWakeKills = false;
13251 }
13252 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13253 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013254 }
13255 int i = mLruProcesses.size();
13256 while (i > 0) {
13257 i--;
13258 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013259 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013260 long wtime;
13261 synchronized (stats) {
13262 wtime = stats.getProcessWakeTime(app.info.uid,
13263 app.pid, curRealtime);
13264 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013265 long wtimeUsed = wtime - app.lastWakeTime;
13266 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13267 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013268 StringBuilder sb = new StringBuilder(128);
13269 sb.append("Wake for ");
13270 app.toShortString(sb);
13271 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013272 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013273 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013274 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013275 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013276 sb.append((wtimeUsed*100)/realtimeSince);
13277 sb.append("%)");
13278 Slog.i(TAG, sb.toString());
13279 sb.setLength(0);
13280 sb.append("CPU for ");
13281 app.toShortString(sb);
13282 sb.append(": over ");
13283 TimeUtils.formatDuration(uptimeSince, sb);
13284 sb.append(" used ");
13285 TimeUtils.formatDuration(cputimeUsed, sb);
13286 sb.append(" (");
13287 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013288 sb.append("%)");
13289 Slog.i(TAG, sb.toString());
13290 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013291 // If a process has held a wake lock for more
13292 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013293 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013294 if (doWakeKills && realtimeSince > 0
13295 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13296 synchronized (stats) {
13297 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13298 realtimeSince, wtimeUsed);
13299 }
13300 Slog.w(TAG, "Excessive wake lock in " + app.processName
13301 + " (pid " + app.pid + "): held " + wtimeUsed
13302 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013303 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13304 app.processName, app.setAdj, "excessive wake lock");
13305 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013306 } else if (doCpuKills && uptimeSince > 0
13307 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13308 synchronized (stats) {
13309 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13310 uptimeSince, cputimeUsed);
13311 }
13312 Slog.w(TAG, "Excessive CPU in " + app.processName
13313 + " (pid " + app.pid + "): used " + cputimeUsed
13314 + " during " + uptimeSince);
13315 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13316 app.processName, app.setAdj, "excessive cpu");
13317 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013318 } else {
13319 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013320 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013321 }
13322 }
13323 }
13324 }
13325
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013326 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13327 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013328 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013329 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013330
13331 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013332 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333 }
13334
Dianne Hackborn287952c2010-09-22 22:34:31 -070013335 final boolean wasKeeping = app.keeping;
13336
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013337 boolean success = true;
13338
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013339 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340
Jeff Brown10e89712011-07-08 18:52:57 -070013341 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013342 if (wasKeeping && !app.keeping) {
13343 // This app is no longer something we want to keep. Note
13344 // its current wake lock time to later know to kill it if
13345 // it is not behaving well.
13346 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13347 synchronized (stats) {
13348 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13349 app.pid, SystemClock.elapsedRealtime());
13350 }
13351 app.lastCpuTime = app.curCpuTime;
13352 }
13353
13354 app.setRawAdj = app.curRawAdj;
13355 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013356
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013357 if (app.curAdj != app.setAdj) {
13358 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013359 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013360 TAG, "Set " + app.pid + " " + app.processName +
13361 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013362 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013363 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013364 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013365 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013366 }
13367 }
13368 if (app.setSchedGroup != app.curSchedGroup) {
13369 app.setSchedGroup = app.curSchedGroup;
13370 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13371 "Setting process group of " + app.processName
13372 + " to " + app.curSchedGroup);
13373 if (app.waitingToKill != null &&
13374 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13375 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13376 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13377 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013378 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013379 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013380 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013381 } else {
13382 if (true) {
13383 long oldId = Binder.clearCallingIdentity();
13384 try {
13385 Process.setProcessGroup(app.pid, app.curSchedGroup);
13386 } catch (Exception e) {
13387 Slog.w(TAG, "Failed setting process group of " + app.pid
13388 + " to " + app.curSchedGroup);
13389 e.printStackTrace();
13390 } finally {
13391 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013392 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013393 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013394 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013395 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013396 app.thread.setSchedulingGroup(app.curSchedGroup);
13397 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013398 }
13399 }
13400 }
13401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013402 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013403 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404 }
13405
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013406 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013407 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013408 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013409 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013410 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013411 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013412 }
13413 }
13414 return resumedActivity;
13415 }
13416
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013417 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013418 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013419 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13420 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013421 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13422 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013423
13424 mAdjSeq++;
13425
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013426 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13427 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013428 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13429 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013430 if (nowHidden != wasHidden) {
13431 // Changed to/from hidden state, so apps after it in the LRU
13432 // list may also be changed.
13433 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013434 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013435 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013436 }
13437
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013438 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013439 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013440 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13441
13442 if (false) {
13443 RuntimeException e = new RuntimeException();
13444 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013445 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013446 }
13447
13448 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013449 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013450
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013451 // Let's determine how many processes we have running vs.
13452 // how many slots we have for background processes; we may want
13453 // to put multiple processes in a slot of there are enough of
13454 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013455 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13456 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13457 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13458 if (emptyFactor < 1) emptyFactor = 1;
13459 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13460 if (hiddenFactor < 1) hiddenFactor = 1;
13461 int stepHidden = 0;
13462 int stepEmpty = 0;
13463 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13464 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013465 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013466 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013467 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013468
13469 mNumNonHiddenProcs = 0;
13470 mNumHiddenProcs = 0;
13471
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013472 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013473 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013474 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013475 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013476 int nextHiddenAdj = curHiddenAdj+1;
13477 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13478 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479 while (i > 0) {
13480 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013481 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013482 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013483 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013484 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013485 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13486 // This process was assigned as a hidden process... step the
13487 // hidden level.
13488 mNumHiddenProcs++;
13489 if (curHiddenAdj != nextHiddenAdj) {
13490 stepHidden++;
13491 if (stepHidden >= hiddenFactor) {
13492 stepHidden = 0;
13493 curHiddenAdj = nextHiddenAdj;
13494 nextHiddenAdj += 2;
13495 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13496 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13497 }
13498 }
13499 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013500 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013501 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013502 Slog.i(TAG, "No longer want " + app.processName
13503 + " (pid " + app.pid + "): hidden #" + numHidden);
13504 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13505 app.processName, app.setAdj, "too many background");
13506 app.killedBackground = true;
13507 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013508 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013509 } else {
13510 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13511 // This process was assigned as an empty process... step the
13512 // empty level.
13513 if (curEmptyAdj != nextEmptyAdj) {
13514 stepEmpty++;
13515 if (stepEmpty >= emptyFactor) {
13516 stepEmpty = 0;
13517 curEmptyAdj = nextEmptyAdj;
13518 nextEmptyAdj += 2;
13519 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13520 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13521 }
13522 }
13523 }
13524 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13525 mNumNonHiddenProcs++;
13526 }
13527 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13528 numEmpty++;
13529 if (numEmpty > emptyProcessLimit) {
13530 Slog.i(TAG, "No longer want " + app.processName
13531 + " (pid " + app.pid + "): empty #" + numEmpty);
13532 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13533 app.processName, app.setAdj, "too many background");
13534 app.killedBackground = true;
13535 Process.killProcessQuiet(app.pid);
13536 }
13537 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013538 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013539 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013540 // If this is an isolated process, and there are no
13541 // services running in it, then the process is no longer
13542 // needed. We agressively kill these because we can by
13543 // definition not re-use the same process again, and it is
13544 // good to avoid having whatever code was running in them
13545 // left sitting around after no longer needed.
13546 Slog.i(TAG, "Isolated process " + app.processName
13547 + " (pid " + app.pid + ") no longer needed");
13548 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13549 app.processName, app.setAdj, "isolated not needed");
13550 app.killedBackground = true;
13551 Process.killProcessQuiet(app.pid);
13552 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013553 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13554 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13555 && !app.killedBackground) {
13556 numTrimming++;
13557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013558 }
13559 }
13560
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013561 mNumServiceProcs = mNewNumServiceProcs;
13562
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013563 // Now determine the memory trimming level of background processes.
13564 // Unfortunately we need to start at the back of the list to do this
13565 // properly. We only do this if the number of background apps we
13566 // are managing to keep around is less than half the maximum we desire;
13567 // if we are keeping a good number around, we'll let them use whatever
13568 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013569 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13570 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13571 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013572 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013573 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013574 int minFactor = 2;
13575 if (mHomeProcess != null) minFactor++;
13576 if (mPreviousProcess != null) minFactor++;
13577 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013578 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013579 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013580 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013581 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013582 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013583 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13584 } else {
13585 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13586 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013587 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013588 for (i=0; i<N; i++) {
13589 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013590 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13591 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013592 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013593 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13594 try {
13595 app.thread.scheduleTrimMemory(curLevel);
13596 } catch (RemoteException e) {
13597 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013598 if (false) {
13599 // For now we won't do this; our memory trimming seems
13600 // to be good enough at this point that destroying
13601 // activities causes more harm than good.
13602 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13603 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013604 // Need to do this on its own message because the stack may not
13605 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013606 // For these apps we will also finish their activities
13607 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013608 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013609 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013610 }
13611 }
13612 app.trimMemoryLevel = curLevel;
13613 step++;
13614 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013615 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013616 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013617 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13618 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013619 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013620 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13621 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013622 break;
13623 }
13624 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013625 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013626 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013627 && app.thread != null) {
13628 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013629 app.thread.scheduleTrimMemory(
13630 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013631 } catch (RemoteException e) {
13632 }
13633 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013634 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013635 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013636 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013637 && app.pendingUiClean) {
13638 // If this application is now in the background and it
13639 // had done UI, then give it the special trim level to
13640 // have it free UI resources.
13641 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13642 if (app.trimMemoryLevel < level && app.thread != null) {
13643 try {
13644 app.thread.scheduleTrimMemory(level);
13645 } catch (RemoteException e) {
13646 }
13647 }
13648 app.pendingUiClean = false;
13649 }
13650 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013651 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013652 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013653 } catch (RemoteException e) {
13654 }
13655 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013656 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013657 }
13658 }
13659 } else {
13660 final int N = mLruProcesses.size();
13661 for (i=0; i<N; i++) {
13662 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013663 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013664 && app.pendingUiClean) {
13665 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13666 && app.thread != null) {
13667 try {
13668 app.thread.scheduleTrimMemory(
13669 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13670 } catch (RemoteException e) {
13671 }
13672 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013673 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013674 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013675 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013676 }
13677 }
13678
13679 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013680 // Need to do this on its own message because the stack may not
13681 // be in a consistent state at this point.
13682 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013684 }
13685
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013686 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 synchronized (this) {
13688 int i;
13689
13690 // First remove any unused application processes whose package
13691 // has been removed.
13692 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13693 final ProcessRecord app = mRemovedProcesses.get(i);
13694 if (app.activities.size() == 0
13695 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013696 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 TAG, "Exiting empty application process "
13698 + app.processName + " ("
13699 + (app.thread != null ? app.thread.asBinder() : null)
13700 + ")\n");
13701 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013702 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13703 app.processName, app.setAdj, "empty");
13704 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013705 } else {
13706 try {
13707 app.thread.scheduleExit();
13708 } catch (Exception e) {
13709 // Ignore exceptions.
13710 }
13711 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013712 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013713 mRemovedProcesses.remove(i);
13714
13715 if (app.persistent) {
13716 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013717 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013718 }
13719 }
13720 }
13721 }
13722
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013723 // Now update the oom adj for all processes.
13724 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725 }
13726 }
13727
13728 /** This method sends the specified signal to each of the persistent apps */
13729 public void signalPersistentProcesses(int sig) throws RemoteException {
13730 if (sig != Process.SIGNAL_USR1) {
13731 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13732 }
13733
13734 synchronized (this) {
13735 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13736 != PackageManager.PERMISSION_GRANTED) {
13737 throw new SecurityException("Requires permission "
13738 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13739 }
13740
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013741 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13742 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013743 if (r.thread != null && r.persistent) {
13744 Process.sendSignal(r.pid, sig);
13745 }
13746 }
13747 }
13748 }
13749
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013750 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13751 if (proc == null || proc == mProfileProc) {
13752 proc = mProfileProc;
13753 path = mProfileFile;
13754 profileType = mProfileType;
13755 clearProfilerLocked();
13756 }
13757 if (proc == null) {
13758 return;
13759 }
13760 try {
13761 proc.thread.profilerControl(false, path, null, profileType);
13762 } catch (RemoteException e) {
13763 throw new IllegalStateException("Process disappeared");
13764 }
13765 }
13766
13767 private void clearProfilerLocked() {
13768 if (mProfileFd != null) {
13769 try {
13770 mProfileFd.close();
13771 } catch (IOException e) {
13772 }
13773 }
13774 mProfileApp = null;
13775 mProfileProc = null;
13776 mProfileFile = null;
13777 mProfileType = 0;
13778 mAutoStopProfiler = false;
13779 }
13780
Dianne Hackborn1676c852012-09-10 14:52:30 -070013781 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013782 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013783
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013784 try {
13785 synchronized (this) {
13786 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13787 // its own permission.
13788 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13789 != PackageManager.PERMISSION_GRANTED) {
13790 throw new SecurityException("Requires permission "
13791 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013792 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013793
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013794 if (start && fd == null) {
13795 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013796 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013797
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013798 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013799 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013800 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013801 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013802
13803 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013804 throw new IllegalArgumentException("Unknown process: " + process);
13805 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013806
13807 if (start) {
13808 stopProfilerLocked(null, null, 0);
13809 setProfileApp(proc.info, proc.processName, path, fd, false);
13810 mProfileProc = proc;
13811 mProfileType = profileType;
13812 try {
13813 fd = fd.dup();
13814 } catch (IOException e) {
13815 fd = null;
13816 }
13817 proc.thread.profilerControl(start, path, fd, profileType);
13818 fd = null;
13819 mProfileFd = null;
13820 } else {
13821 stopProfilerLocked(proc, path, profileType);
13822 if (fd != null) {
13823 try {
13824 fd.close();
13825 } catch (IOException e) {
13826 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013827 }
13828 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013829
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013830 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013831 }
13832 } catch (RemoteException e) {
13833 throw new IllegalStateException("Process disappeared");
13834 } finally {
13835 if (fd != null) {
13836 try {
13837 fd.close();
13838 } catch (IOException e) {
13839 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013840 }
13841 }
13842 }
Andy McFadden824c5102010-07-09 16:26:57 -070013843
Dianne Hackborn1676c852012-09-10 14:52:30 -070013844 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
13845 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
13846 userId, true, true, callName, null);
13847 ProcessRecord proc = null;
13848 try {
13849 int pid = Integer.parseInt(process);
13850 synchronized (mPidsSelfLocked) {
13851 proc = mPidsSelfLocked.get(pid);
13852 }
13853 } catch (NumberFormatException e) {
13854 }
13855
13856 if (proc == null) {
13857 HashMap<String, SparseArray<ProcessRecord>> all
13858 = mProcessNames.getMap();
13859 SparseArray<ProcessRecord> procs = all.get(process);
13860 if (procs != null && procs.size() > 0) {
13861 proc = procs.valueAt(0);
13862 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13863 for (int i=1; i<procs.size(); i++) {
13864 ProcessRecord thisProc = procs.valueAt(i);
13865 if (thisProc.userId == userId) {
13866 proc = thisProc;
13867 break;
13868 }
13869 }
13870 }
13871 }
13872 }
13873
13874 return proc;
13875 }
13876
13877 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013878 String path, ParcelFileDescriptor fd) throws RemoteException {
13879
13880 try {
13881 synchronized (this) {
13882 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13883 // its own permission (same as profileControl).
13884 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13885 != PackageManager.PERMISSION_GRANTED) {
13886 throw new SecurityException("Requires permission "
13887 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13888 }
13889
13890 if (fd == null) {
13891 throw new IllegalArgumentException("null fd");
13892 }
13893
Dianne Hackborn1676c852012-09-10 14:52:30 -070013894 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013895 if (proc == null || proc.thread == null) {
13896 throw new IllegalArgumentException("Unknown process: " + process);
13897 }
13898
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013899 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13900 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013901 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13902 throw new SecurityException("Process not debuggable: " + proc);
13903 }
13904 }
13905
13906 proc.thread.dumpHeap(managed, path, fd);
13907 fd = null;
13908 return true;
13909 }
13910 } catch (RemoteException e) {
13911 throw new IllegalStateException("Process disappeared");
13912 } finally {
13913 if (fd != null) {
13914 try {
13915 fd.close();
13916 } catch (IOException e) {
13917 }
13918 }
13919 }
13920 }
13921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013922 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13923 public void monitor() {
13924 synchronized (this) { }
13925 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013926
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013927 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013928 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13929 ProcessRecord processRecord = mLruProcesses.get(i);
13930 try {
13931 if (processRecord.thread != null) {
13932 processRecord.thread.setCoreSettings(settings);
13933 }
13934 } catch (RemoteException re) {
13935 /* ignore */
13936 }
13937 }
13938 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013939
13940 // Multi-user methods
13941
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013942 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013943 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013944 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13945 != PackageManager.PERMISSION_GRANTED) {
13946 String msg = "Permission Denial: switchUser() from pid="
13947 + Binder.getCallingPid()
13948 + ", uid=" + Binder.getCallingUid()
13949 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13950 Slog.w(TAG, msg);
13951 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013952 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013953
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013954 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013955 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013956 synchronized (this) {
13957 final int oldUserId = mCurrentUserId;
13958 if (oldUserId == userId) {
13959 return true;
13960 }
13961
13962 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
13963 if (userInfo == null) {
13964 Slog.w(TAG, "No user info for user #" + userId);
13965 return false;
13966 }
13967
13968 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
13969 R.anim.screen_user_enter);
13970
13971 // If the user we are switching to is not currently started, then
13972 // we need to start it now.
13973 if (mStartedUsers.get(userId) == null) {
13974 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
13975 }
13976
13977 mCurrentUserId = userId;
13978 final Integer userIdInt = Integer.valueOf(userId);
13979 mUserLru.remove(userIdInt);
13980 mUserLru.add(userIdInt);
13981
13982 final UserStartedState uss = mStartedUsers.get(userId);
13983
13984 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
13985 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
13986 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
13987 oldUserId, userId, uss));
13988 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
13989 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
13990 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
13991 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13992 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13993 broadcastIntentLocked(null, null, intent,
13994 null, null, 0, null, null, null,
13995 false, false, MY_PID, Process.SYSTEM_UID, userId);
13996
13997 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
13998 if (userId != 0) {
13999 intent = new Intent(Intent.ACTION_USER_INITIALIZE);
14000 broadcastIntentLocked(null, null, intent, null,
14001 new IIntentReceiver.Stub() {
14002 public void performReceive(Intent intent, int resultCode,
14003 String data, Bundle extras, boolean ordered,
14004 boolean sticky, int sendingUser) {
14005 synchronized (ActivityManagerService.this) {
14006 getUserManagerLocked().makeInitialized(userInfo.id);
14007 }
14008 }
14009 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14010 userId);
14011 } else {
14012 getUserManagerLocked().makeInitialized(userInfo.id);
14013 }
14014 }
14015
14016 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14017 if (!haveActivities) {
14018 startHomeActivityLocked(userId);
14019 }
14020
14021 sendUserSwitchBroadcastsLocked(oldUserId, userId);
14022 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014023 } finally {
14024 Binder.restoreCallingIdentity(ident);
14025 }
Amith Yamasani13593602012-03-22 16:16:17 -070014026
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014027 return true;
14028 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014029
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014030 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14031 long ident = Binder.clearCallingIdentity();
14032 try {
14033 Intent intent;
14034 if (oldUserId >= 0) {
14035 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
14036 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14037 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14038 broadcastIntentLocked(null, null, intent,
14039 null, null, 0, null, null, null,
14040 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14041 }
14042 if (newUserId >= 0) {
14043 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
14044 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14045 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14046 broadcastIntentLocked(null, null, intent,
14047 null, null, 0, null, null, null,
14048 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14049 intent = new Intent(Intent.ACTION_USER_SWITCHED);
14050 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14051 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14052 broadcastIntentLocked(null, null, intent,
14053 null, null, 0, null, null,
14054 android.Manifest.permission.MANAGE_USERS,
14055 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14056 }
14057 } finally {
14058 Binder.restoreCallingIdentity(ident);
14059 }
14060 }
14061
14062 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14063 final int newUserId) {
14064 final int N = mUserSwitchObservers.beginBroadcast();
14065 if (N > 0) {
14066 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14067 int mCount = 0;
14068 @Override
14069 public void sendResult(Bundle data) throws RemoteException {
14070 synchronized (ActivityManagerService.this) {
14071 if (mCurUserSwitchCallback == this) {
14072 mCount++;
14073 if (mCount == N) {
14074 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14075 }
14076 }
14077 }
14078 }
14079 };
14080 synchronized (this) {
14081 mCurUserSwitchCallback = callback;
14082 }
14083 for (int i=0; i<N; i++) {
14084 try {
14085 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14086 newUserId, callback);
14087 } catch (RemoteException e) {
14088 }
14089 }
14090 } else {
14091 synchronized (this) {
14092 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14093 }
14094 }
14095 mUserSwitchObservers.finishBroadcast();
14096 }
14097
14098 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14099 synchronized (this) {
14100 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14101 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14102 }
14103 }
14104
14105 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14106 mCurUserSwitchCallback = null;
14107 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14108 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14109 oldUserId, newUserId, uss));
14110 }
14111
14112 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14113 final int N = mUserSwitchObservers.beginBroadcast();
14114 for (int i=0; i<N; i++) {
14115 try {
14116 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14117 } catch (RemoteException e) {
14118 }
14119 }
14120 mUserSwitchObservers.finishBroadcast();
14121 synchronized (this) {
14122 mWindowManager.stopFreezingScreen();
14123 }
14124 }
14125
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014126 void finishUserSwitch(UserStartedState uss) {
14127 synchronized (this) {
14128 if (uss.mState == UserStartedState.STATE_BOOTING
14129 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14130 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014131 final int userId = uss.mHandle.getIdentifier();
14132 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14133 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14134 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014135 null, null, 0, null, null,
14136 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014137 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014138 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014139 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014140 }
14141
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014142 @Override
14143 public int stopUser(final int userId, final IStopUserCallback callback) {
14144 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14145 != PackageManager.PERMISSION_GRANTED) {
14146 String msg = "Permission Denial: switchUser() from pid="
14147 + Binder.getCallingPid()
14148 + ", uid=" + Binder.getCallingUid()
14149 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14150 Slog.w(TAG, msg);
14151 throw new SecurityException(msg);
14152 }
14153 if (userId <= 0) {
14154 throw new IllegalArgumentException("Can't stop primary user " + userId);
14155 }
Amith Yamasani13593602012-03-22 16:16:17 -070014156 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014157 if (mCurrentUserId == userId) {
14158 return ActivityManager.USER_OP_IS_CURRENT;
14159 }
14160
14161 final UserStartedState uss = mStartedUsers.get(userId);
14162 if (uss == null) {
14163 // User is not started, nothing to do... but we do need to
14164 // callback if requested.
14165 if (callback != null) {
14166 mHandler.post(new Runnable() {
14167 @Override
14168 public void run() {
14169 try {
14170 callback.userStopped(userId);
14171 } catch (RemoteException e) {
14172 }
14173 }
14174 });
14175 }
14176 return ActivityManager.USER_OP_SUCCESS;
14177 }
14178
14179 if (callback != null) {
14180 uss.mStopCallbacks.add(callback);
14181 }
14182
14183 if (uss.mState != UserStartedState.STATE_STOPPING) {
14184 uss.mState = UserStartedState.STATE_STOPPING;
14185
14186 long ident = Binder.clearCallingIdentity();
14187 try {
14188 // Inform of user switch
14189 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
14190 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
14191 @Override
14192 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070014193 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014194 finishUserStop(uss);
14195 }
14196 };
14197 broadcastIntentLocked(null, null, intent,
14198 null, resultReceiver, 0, null, null, null,
14199 true, false, MY_PID, Process.SYSTEM_UID, userId);
14200 } finally {
14201 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014202 }
14203 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014204 }
Amith Yamasani13593602012-03-22 16:16:17 -070014205
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014206 return ActivityManager.USER_OP_SUCCESS;
14207 }
14208
14209 void finishUserStop(UserStartedState uss) {
14210 final int userId = uss.mHandle.getIdentifier();
14211 boolean stopped;
14212 ArrayList<IStopUserCallback> callbacks;
14213 synchronized (this) {
14214 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
14215 if (uss.mState != UserStartedState.STATE_STOPPING
14216 || mStartedUsers.get(userId) != uss) {
14217 stopped = false;
14218 } else {
14219 stopped = true;
14220 // User can no longer run.
14221 mStartedUsers.remove(userId);
14222
14223 // Clean up all state and processes associated with the user.
14224 // Kill all the processes for the user.
14225 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014226 }
14227 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014228
14229 for (int i=0; i<callbacks.size(); i++) {
14230 try {
14231 if (stopped) callbacks.get(i).userStopped(userId);
14232 else callbacks.get(i).userStopAborted(userId);
14233 } catch (RemoteException e) {
14234 }
14235 }
14236 }
14237
14238 @Override
14239 public UserInfo getCurrentUser() {
14240 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14241 != PackageManager.PERMISSION_GRANTED) {
14242 String msg = "Permission Denial: getCurrentUser() from pid="
14243 + Binder.getCallingPid()
14244 + ", uid=" + Binder.getCallingUid()
14245 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14246 Slog.w(TAG, msg);
14247 throw new SecurityException(msg);
14248 }
14249 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014250 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014251 }
Amith Yamasani13593602012-03-22 16:16:17 -070014252 }
14253
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014254 @Override
14255 public boolean isUserRunning(int userId) {
14256 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14257 != PackageManager.PERMISSION_GRANTED) {
14258 String msg = "Permission Denial: isUserRunning() from pid="
14259 + Binder.getCallingPid()
14260 + ", uid=" + Binder.getCallingUid()
14261 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14262 Slog.w(TAG, msg);
14263 throw new SecurityException(msg);
14264 }
14265 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014266 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014267 }
14268 }
14269
Dianne Hackborn1676c852012-09-10 14:52:30 -070014270 boolean isUserRunningLocked(int userId) {
14271 UserStartedState state = mStartedUsers.get(userId);
14272 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014273 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014274
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014275 @Override
14276 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14277 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14278 != PackageManager.PERMISSION_GRANTED) {
14279 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14280 + Binder.getCallingPid()
14281 + ", uid=" + Binder.getCallingUid()
14282 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14283 Slog.w(TAG, msg);
14284 throw new SecurityException(msg);
14285 }
14286
14287 mUserSwitchObservers.register(observer);
14288 }
14289
14290 @Override
14291 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14292 mUserSwitchObservers.unregister(observer);
14293 }
14294
Dianne Hackborn1676c852012-09-10 14:52:30 -070014295 private boolean userExists(int userId) {
14296 if (userId == 0) {
14297 return true;
14298 }
14299 UserManagerService ums = getUserManagerLocked();
14300 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14301 }
14302
14303 int[] getUsersLocked() {
14304 UserManagerService ums = getUserManagerLocked();
14305 return ums != null ? ums.getUserIds() : new int[] { 0 };
14306 }
14307
14308 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014309 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014310 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14311 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014312 }
14313 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014314 }
14315
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014316 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014317 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014318
14319 throw new SecurityException("Caller uid=" + uid
14320 + " is not privileged to communicate with user=" + userId);
14321 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014322
14323 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014324 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014325 }
14326
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014327 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014328 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014329 ApplicationInfo newInfo = new ApplicationInfo(info);
14330 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014331 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14332 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014333 return newInfo;
14334 }
14335
14336 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014337 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014338 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014339 return aInfo;
14340 }
14341
14342 ActivityInfo info = new ActivityInfo(aInfo);
14343 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14344 return info;
14345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014346}