blob: 9b7ed22e47527d8b05d5987eb8a9c451b7b512af [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborn1676c852012-09-10 14:52:30 -070030import com.android.server.pm.UserManagerService;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080031import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032
Dianne Hackborndd71fc82009-12-16 19:24:32 -080033import dalvik.system.Zygote;
34
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.app.Activity;
36import android.app.ActivityManager;
37import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070038import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.ActivityThread;
40import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070041import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020042import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070044import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.IApplicationThread;
46import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070047import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070048import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070050import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.app.IThumbnailReceiver;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070052import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070054import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070055import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080057import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020058import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080059import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080060import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070061import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070063import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.ContentResolver;
65import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020066import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070067import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070068import android.content.IIntentReceiver;
69import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070070import android.content.Intent;
71import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070072import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.content.pm.ActivityInfo;
74import android.content.pm.ApplicationInfo;
75import android.content.pm.ConfigurationInfo;
76import android.content.pm.IPackageDataObserver;
77import android.content.pm.IPackageManager;
78import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080079import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070081import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070082import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070083import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.pm.ProviderInfo;
85import android.content.pm.ResolveInfo;
86import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040087import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.content.res.Configuration;
89import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070090import android.net.Proxy;
91import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.net.Uri;
93import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080095import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070096import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080097import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080099import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.FileUtils;
101import android.os.Handler;
102import android.os.IBinder;
103import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700104import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700105import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.Looper;
107import android.os.Message;
108import android.os.Parcel;
109import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700111import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400113import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700115import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.os.SystemClock;
117import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700118import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700120import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800122import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700123import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700125import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700127import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import android.view.Gravity;
129import android.view.LayoutInflater;
130import android.view.View;
131import android.view.WindowManager;
132import android.view.WindowManagerPolicy;
133
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700134import java.io.BufferedInputStream;
135import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700136import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.DataInputStream;
138import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.File;
140import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700141import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700143import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200144import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800145import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700147import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.lang.ref.WeakReference;
149import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700150import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700151import java.util.Collections;
152import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.util.HashMap;
154import java.util.HashSet;
155import java.util.Iterator;
156import java.util.List;
157import java.util.Locale;
158import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700159import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700160import java.util.concurrent.atomic.AtomicBoolean;
161import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700163public final class ActivityManagerService extends ActivityManagerNative
164 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700165 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700167 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400169 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean DEBUG_SWITCH = localLOGV || false;
171 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700172 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final boolean DEBUG_PAUSE = localLOGV || false;
174 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
175 static final boolean DEBUG_TRANSITION = localLOGV || false;
176 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800177 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700178 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700180 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final boolean DEBUG_VISBILITY = localLOGV || false;
182 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700183 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700184 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800185 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700187 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700188 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700189 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700190 static final boolean DEBUG_POWER = localLOGV || false;
191 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700192 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 static final boolean VALIDATE_TOKENS = false;
194 static final boolean SHOW_ACTIVITY_START_TIME = true;
195
196 // Control over CPU and battery monitoring.
197 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
198 static final boolean MONITOR_CPU_USAGE = true;
199 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
200 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
201 static final boolean MONITOR_THREAD_CPU_USAGE = false;
202
Dianne Hackborn1655be42009-05-08 14:29:01 -0700203 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700204 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700205
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800206 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700208 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // Maximum number of recent tasks that we can remember.
211 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700212
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700213 // Amount of time after a call to stopAppSwitches() during which we will
214 // prevent further untrusted switches from happening.
215 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 // How long we wait for a launched process to attach to the activity manager
218 // before we decide it's never going to come up for real.
219 static final int PROC_START_TIMEOUT = 10*1000;
220
Jeff Brown3f9dd282011-07-08 20:02:19 -0700221 // How long we wait for a launched process to attach to the activity manager
222 // before we decide it's never going to come up for real, when the process was
223 // started with a wrapper for instrumentation (such as Valgrind) because it
224 // could take much longer than usual.
225 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 // How long to wait after going idle before forcing apps to GC.
228 static final int GC_TIMEOUT = 5*1000;
229
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700230 // The minimum amount of time between successive GC requests for a process.
231 static final int GC_MIN_INTERVAL = 60*1000;
232
Dianne Hackborn287952c2010-09-22 22:34:31 -0700233 // The rate at which we check for apps using excessive power -- 15 mins.
234 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
235
236 // The minimum sample duration we will allow before deciding we have
237 // enough data on wake locks to start killing things.
238 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
239
240 // The minimum sample duration we will allow before deciding we have
241 // enough data on CPU usage to start killing things.
242 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800245 static final int BROADCAST_FG_TIMEOUT = 10*1000;
246 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // How long we wait until we timeout on key dispatching.
249 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // How long we wait until we timeout on key dispatching during instrumentation.
252 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
253
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700254 // Amount of time we wait for observers to handle a user switch before
255 // giving up on them and unfreezing the screen.
256 static final int USER_SWITCH_TIMEOUT = 2*1000;
257
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700258 // Maximum number of users we allow to be running at a time.
259 static final int MAX_RUNNING_USERS = 3;
260
Dan Egnor42471dd2010-01-07 17:25:22 -0800261 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 static final String[] EMPTY_STRING_ARRAY = new String[0];
264
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700265 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700266
267 private final boolean mHeadless;
268
Joe Onorato54a4a412011-11-02 20:50:08 -0700269 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
270 // default actuion automatically. Important for devices without direct input
271 // devices.
272 private boolean mShowDialogs = true;
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700275 * Description of a request to start a new activity, which has been held
276 * due to app switches being disabled.
277 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700278 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700279 ActivityRecord r;
280 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700281 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700282 }
283
284 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
285 = new ArrayList<PendingActivityLaunch>();
286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800288 BroadcastQueue mFgBroadcastQueue;
289 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800290 // Convenient for easy iteration over the queues. Foreground is first
291 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800292 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800293
294 BroadcastQueue broadcastQueueForIntent(Intent intent) {
295 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
296 if (DEBUG_BACKGROUND_BROADCAST) {
297 Slog.i(TAG, "Broadcast intent " + intent + " on "
298 + (isFg ? "foreground" : "background")
299 + " queue");
300 }
301 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
302 }
303
304 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
305 for (BroadcastQueue queue : mBroadcastQueues) {
306 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
307 if (r != null) {
308 return r;
309 }
310 }
311 return null;
312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
314 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 * Activity we have told the window manager to have key focus.
316 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700317 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * List of intents that were used to start the most recent tasks.
320 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700321 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322
323 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700324 * Process management.
325 */
326 final ProcessList mProcessList = new ProcessList();
327
328 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 * All of the applications we currently have running organized by name.
330 * The keys are strings of the application package name (as
331 * returned by the package manager), and the keys are ApplicationRecord
332 * objects.
333 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700334 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335
336 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800337 * The currently running isolated processes.
338 */
339 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
340
341 /**
342 * Counter for assigning isolated process uids, to avoid frequently reusing the
343 * same ones.
344 */
345 int mNextIsolatedProcessUid = 0;
346
347 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700348 * The currently running heavy-weight process, if any.
349 */
350 ProcessRecord mHeavyWeightProcess = null;
351
352 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 * The last time that various processes have crashed.
354 */
355 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
356
357 /**
358 * Set of applications that we consider to be bad, and will reject
359 * incoming broadcasts from (which the user has no control over).
360 * Processes are added to this set when they have crashed twice within
361 * a minimum amount of time; they are removed from it when they are
362 * later restarted (hopefully due to some user action). The value is the
363 * time it was added to the list.
364 */
365 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
366
367 /**
368 * All of the processes we currently have running organized by pid.
369 * The keys are the pid running the application.
370 *
371 * <p>NOTE: This object is protected by its own lock, NOT the global
372 * activity manager lock!
373 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700374 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375
376 /**
377 * All of the processes that have been forced to be foreground. The key
378 * is the pid of the caller who requested it (we hold a death
379 * link on it).
380 */
381 abstract class ForegroundToken implements IBinder.DeathRecipient {
382 int pid;
383 IBinder token;
384 }
385 final SparseArray<ForegroundToken> mForegroundProcesses
386 = new SparseArray<ForegroundToken>();
387
388 /**
389 * List of records for processes that someone had tried to start before the
390 * system was ready. We don't start them at that point, but ensure they
391 * are started by the time booting is complete.
392 */
393 final ArrayList<ProcessRecord> mProcessesOnHold
394 = new ArrayList<ProcessRecord>();
395
396 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 * List of persistent applications that are in the process
398 * of being started.
399 */
400 final ArrayList<ProcessRecord> mPersistentStartingProcesses
401 = new ArrayList<ProcessRecord>();
402
403 /**
404 * Processes that are being forcibly torn down.
405 */
406 final ArrayList<ProcessRecord> mRemovedProcesses
407 = new ArrayList<ProcessRecord>();
408
409 /**
410 * List of running applications, sorted by recent usage.
411 * The first entry in the list is the least recently used.
412 * It contains ApplicationRecord objects. This list does NOT include
413 * any persistent application records (since we never want to exit them).
414 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800415 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 = new ArrayList<ProcessRecord>();
417
418 /**
419 * List of processes that should gc as soon as things are idle.
420 */
421 final ArrayList<ProcessRecord> mProcessesToGc
422 = new ArrayList<ProcessRecord>();
423
424 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800425 * This is the process holding what we currently consider to be
426 * the "home" activity.
427 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700428 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800429
430 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700431 * This is the process holding the activity the user last visited that
432 * is in a different process from the one they are currently in.
433 */
434 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800435
436 /**
437 * The time at which the previous process was last visible.
438 */
439 long mPreviousProcessVisibleTime;
440
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700441 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700442 * Which uses have been started, so are allowed to run code.
443 */
444 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
445
446 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700447 * LRU list of history of current users. Most recently current is at the end.
448 */
449 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
450
451 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700452 * Constant array of the users that are currently started.
453 */
454 int[] mStartedUserArray = new int[] { 0 };
455
456 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700457 * Registered observers of the user switching mechanics.
458 */
459 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
460 = new RemoteCallbackList<IUserSwitchObserver>();
461
462 /**
463 * Currently active user switch.
464 */
465 Object mCurUserSwitchCallback;
466
467 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400468 * Packages that the user has asked to have run in screen size
469 * compatibility mode instead of filling the screen.
470 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700471 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400472
473 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 * Set of PendingResultRecord objects that are currently active.
475 */
476 final HashSet mPendingResultRecords = new HashSet();
477
478 /**
479 * Set of IntentSenderRecord objects that are currently active.
480 */
481 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
482 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
483
484 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800485 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700486 * already logged DropBox entries for. Guarded by itself. If
487 * something (rogue user app) forces this over
488 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
489 */
490 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
491 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
492
493 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700494 * Strict Mode background batched logging state.
495 *
496 * The string buffer is guarded by itself, and its lock is also
497 * used to determine if another batched write is already
498 * in-flight.
499 */
500 private final StringBuilder mStrictModeBuffer = new StringBuilder();
501
502 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 * Keeps track of all IIntentReceivers that have been registered for
504 * broadcasts. Hash keys are the receiver IBinder, hash value is
505 * a ReceiverList.
506 */
507 final HashMap mRegisteredReceivers = new HashMap();
508
509 /**
510 * Resolver for broadcast intents to registered receivers.
511 * Holds BroadcastFilter (subclass of IntentFilter).
512 */
513 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
514 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
515 @Override
516 protected boolean allowFilterResult(
517 BroadcastFilter filter, List<BroadcastFilter> dest) {
518 IBinder target = filter.receiverList.receiver.asBinder();
519 for (int i=dest.size()-1; i>=0; i--) {
520 if (dest.get(i).receiverList.receiver.asBinder() == target) {
521 return false;
522 }
523 }
524 return true;
525 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700526
527 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700528 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700529 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
530 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700531 return super.newResult(filter, match, userId);
532 }
533 return null;
534 }
535
536 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700537 protected BroadcastFilter[] newArray(int size) {
538 return new BroadcastFilter[size];
539 }
540
541 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700542 protected String packageForFilter(BroadcastFilter filter) {
543 return filter.packageName;
544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 };
546
547 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700548 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700550 * that action (which should usually be one). The SparseArray is keyed
551 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
552 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700554 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
555 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700557 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
559 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700560 * Backup/restore process management
561 */
562 String mBackupAppName = null;
563 BackupRecord mBackupTarget = null;
564
565 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 * List of PendingThumbnailsRecord objects of clients who are still
567 * waiting to receive all of the thumbnails for a task.
568 */
569 final ArrayList mPendingThumbnails = new ArrayList();
570
571 /**
572 * List of HistoryRecord objects that have been finished and must
573 * still report back to a pending thumbnail receiver.
574 */
575 final ArrayList mCancelledThumbnails = new ArrayList();
576
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700577 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 /**
580 * List of content providers who have clients waiting for them. The
581 * application is currently being launched and the provider will be
582 * removed from this list once it is published.
583 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700584 final ArrayList<ContentProviderRecord> mLaunchingProviders
585 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 /**
588 * Global set of specific Uri permissions that have been granted.
589 */
590 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
591 = new SparseArray<HashMap<Uri, UriPermission>>();
592
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800593 CoreSettingsObserver mCoreSettingsObserver;
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 /**
596 * Thread-local storage used to carry caller permissions over through
597 * indirect content-provider access.
598 * @see #ActivityManagerService.openContentUri()
599 */
600 private class Identity {
601 public int pid;
602 public int uid;
603
604 Identity(int _pid, int _uid) {
605 pid = _pid;
606 uid = _uid;
607 }
608 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
611
612 /**
613 * All information we have collected about the runtime performance of
614 * any user id that can impact battery performance.
615 */
616 final BatteryStatsService mBatteryStatsService;
617
618 /**
619 * information about component usage
620 */
621 final UsageStatsService mUsageStatsService;
622
623 /**
624 * Current configuration information. HistoryRecord objects are given
625 * a reference to this object to indicate which configuration they are
626 * currently running in, so this object must be kept immutable.
627 */
628 Configuration mConfiguration = new Configuration();
629
630 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800631 * Current sequencing integer of the configuration, for skipping old
632 * configurations.
633 */
634 int mConfigurationSeq = 0;
635
636 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700637 * Hardware-reported OpenGLES version.
638 */
639 final int GL_ES_VERSION;
640
641 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 * List of initialization arguments to pass to all processes when binding applications to them.
643 * For example, references to the commonly used services.
644 */
645 HashMap<String, IBinder> mAppBindArgs;
646
647 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700648 * Temporary to avoid allocations. Protected by main lock.
649 */
650 final StringBuilder mStringBuilder = new StringBuilder(256);
651
652 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 * Used to control how we initialize the service.
654 */
655 boolean mStartRunning = false;
656 ComponentName mTopComponent;
657 String mTopAction;
658 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700659 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 boolean mSystemReady = false;
661 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700662 boolean mWaitingUpdate = false;
663 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700664 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700665 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
667 Context mContext;
668
669 int mFactoryTest;
670
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700671 boolean mCheckedForSetup;
672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700674 * The time at which we will allow normal application switches again,
675 * after a call to {@link #stopAppSwitches()}.
676 */
677 long mAppSwitchesAllowedTime;
678
679 /**
680 * This is set to true after the first switch after mAppSwitchesAllowedTime
681 * is set; any switches after that will clear the time.
682 */
683 boolean mDidAppSwitch;
684
685 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700687 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700688 long mLastPowerCheckRealtime;
689
690 /**
691 * Last time (in uptime) at which we checked for power usage.
692 */
693 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700694
695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 * Set while we are wanting to sleep, to prevent any
697 * activities from being started/resumed.
698 */
699 boolean mSleeping = false;
700
701 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700702 * State of external calls telling us if the device is asleep.
703 */
704 boolean mWentToSleep = false;
705
706 /**
707 * State of external call telling us if the lock screen is shown.
708 */
709 boolean mLockScreenShown = false;
710
711 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700712 * Set if we are shutting down the system, similar to sleeping.
713 */
714 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715
716 /**
717 * Task identifier that activities are currently being started
718 * in. Incremented each time a new task is created.
719 * todo: Replace this with a TokenSpace class that generates non-repeating
720 * integers that won't wrap.
721 */
722 int mCurTask = 1;
723
724 /**
725 * Current sequence id for oom_adj computation traversal.
726 */
727 int mAdjSeq = 0;
728
729 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700730 * Current sequence id for process LRU updating.
731 */
732 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733
734 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700735 * Keep track of the non-hidden/empty process we last found, to help
736 * determine how to distribute hidden/empty processes next time.
737 */
738 int mNumNonHiddenProcs = 0;
739
740 /**
741 * Keep track of the number of hidden procs, to balance oom adj
742 * distribution between those and empty procs.
743 */
744 int mNumHiddenProcs = 0;
745
746 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700747 * Keep track of the number of service processes we last found, to
748 * determine on the next iteration which should be B services.
749 */
750 int mNumServiceProcs = 0;
751 int mNewNumServiceProcs = 0;
752
753 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 * System monitoring: number of processes that died since the last
755 * N procs were started.
756 */
757 int[] mProcDeaths = new int[20];
758
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700759 /**
760 * This is set if we had to do a delayed dexopt of an app before launching
761 * it, to increasing the ANR timeouts in that case.
762 */
763 boolean mDidDexOpt;
764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 String mDebugApp = null;
766 boolean mWaitForDebugger = false;
767 boolean mDebugTransient = false;
768 String mOrigDebugApp = null;
769 boolean mOrigWaitForDebugger = false;
770 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700771 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700772 String mProfileApp = null;
773 ProcessRecord mProfileProc = null;
774 String mProfileFile;
775 ParcelFileDescriptor mProfileFd;
776 int mProfileType = 0;
777 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800778 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700780 static class ProcessChangeItem {
781 static final int CHANGE_ACTIVITIES = 1<<0;
782 static final int CHANGE_IMPORTANCE= 1<<1;
783 int changes;
784 int uid;
785 int pid;
786 int importance;
787 boolean foregroundActivities;
788 }
789
Jeff Sharkeya4620792011-05-20 15:29:23 -0700790 final RemoteCallbackList<IProcessObserver> mProcessObservers
791 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700792 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
793
794 final ArrayList<ProcessChangeItem> mPendingProcessChanges
795 = new ArrayList<ProcessChangeItem>();
796 final ArrayList<ProcessChangeItem> mAvailProcessChanges
797 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 /**
800 * Callback of last caller to {@link #requestPss}.
801 */
802 Runnable mRequestPssCallback;
803
804 /**
805 * Remaining processes for which we are waiting results from the last
806 * call to {@link #requestPss}.
807 */
808 final ArrayList<ProcessRecord> mRequestPssList
809 = new ArrayList<ProcessRecord>();
810
811 /**
812 * Runtime statistics collection thread. This object's lock is used to
813 * protect all related state.
814 */
815 final Thread mProcessStatsThread;
816
817 /**
818 * Used to collect process stats when showing not responding dialog.
819 * Protected by mProcessStatsThread.
820 */
821 final ProcessStats mProcessStats = new ProcessStats(
822 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700823 final AtomicLong mLastCpuTime = new AtomicLong(0);
824 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 long mLastWriteTime = 0;
827
828 /**
829 * Set to true after the system has finished booting.
830 */
831 boolean mBooted = false;
832
Dianne Hackborn7d608422011-08-07 16:24:18 -0700833 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700834 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835
836 WindowManagerService mWindowManager;
837
838 static ActivityManagerService mSelf;
839 static ActivityThread mSystemThread;
840
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700841 private int mCurrentUserId = 0;
842 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700843 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 private final class AppDeathRecipient implements IBinder.DeathRecipient {
846 final ProcessRecord mApp;
847 final int mPid;
848 final IApplicationThread mAppThread;
849
850 AppDeathRecipient(ProcessRecord app, int pid,
851 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800852 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 TAG, "New death recipient " + this
854 + " for thread " + thread.asBinder());
855 mApp = app;
856 mPid = pid;
857 mAppThread = thread;
858 }
859
860 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800861 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 TAG, "Death received in " + this
863 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 synchronized(ActivityManagerService.this) {
865 appDiedLocked(mApp, mPid, mAppThread);
866 }
867 }
868 }
869
870 static final int SHOW_ERROR_MSG = 1;
871 static final int SHOW_NOT_RESPONDING_MSG = 2;
872 static final int SHOW_FACTORY_ERROR_MSG = 3;
873 static final int UPDATE_CONFIGURATION_MSG = 4;
874 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
875 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 static final int SERVICE_TIMEOUT_MSG = 12;
877 static final int UPDATE_TIME_ZONE = 13;
878 static final int SHOW_UID_ERROR_MSG = 14;
879 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700881 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700882 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800883 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700884 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
885 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700886 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700887 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700888 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700889 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700890 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700891 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700892 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700893 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700894 static final int REPORT_USER_SWITCH_MSG = 34;
895 static final int CONTINUE_USER_SWITCH_MSG = 35;
896 static final int USER_SWITCH_TIMEOUT_MSG = 36;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800898 static final int FIRST_ACTIVITY_STACK_MSG = 100;
899 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
900 static final int FIRST_COMPAT_MODE_MSG = 300;
901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700903 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700904 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
906 final Handler mHandler = new Handler() {
907 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 //}
910
911 public void handleMessage(Message msg) {
912 switch (msg.what) {
913 case SHOW_ERROR_MSG: {
914 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 synchronized (ActivityManagerService.this) {
916 ProcessRecord proc = (ProcessRecord)data.get("app");
917 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800918 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 return;
920 }
921 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700922 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800923 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 d.show();
925 proc.crashDialog = d;
926 } else {
927 // The device is asleep, so just pretend that the user
928 // saw a crash dialog and hit "force quit".
929 res.set(0);
930 }
931 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700932
933 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 } break;
935 case SHOW_NOT_RESPONDING_MSG: {
936 synchronized (ActivityManagerService.this) {
937 HashMap data = (HashMap) msg.obj;
938 ProcessRecord proc = (ProcessRecord)data.get("app");
939 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800940 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 return;
942 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800943
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700944 Intent intent = new Intent("android.intent.action.ANR");
945 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800946 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
947 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700948 }
949 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800950 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700951 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800952
Justin Kohbc52ca22012-03-29 15:11:44 -0700953 if (mShowDialogs) {
954 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700955 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700956 d.show();
957 proc.anrDialog = d;
958 } else {
959 // Just kill the app if there is no dialog to be shown.
960 killAppAtUsersRequest(proc, null);
961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700963
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700964 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700966 case SHOW_STRICT_MODE_VIOLATION_MSG: {
967 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
968 synchronized (ActivityManagerService.this) {
969 ProcessRecord proc = (ProcessRecord) data.get("app");
970 if (proc == null) {
971 Slog.e(TAG, "App not found when showing strict mode dialog.");
972 break;
973 }
974 if (proc.crashDialog != null) {
975 Slog.e(TAG, "App already has strict mode dialog: " + proc);
976 return;
977 }
978 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700979 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700980 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
981 d.show();
982 proc.crashDialog = d;
983 } else {
984 // The device is asleep, so just pretend that the user
985 // saw a crash dialog and hit "force quit".
986 res.set(0);
987 }
988 }
989 ensureBootCompleted();
990 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 case SHOW_FACTORY_ERROR_MSG: {
992 Dialog d = new FactoryErrorDialog(
993 mContext, msg.getData().getCharSequence("msg"));
994 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700995 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 } break;
997 case UPDATE_CONFIGURATION_MSG: {
998 final ContentResolver resolver = mContext.getContentResolver();
999 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1000 } break;
1001 case GC_BACKGROUND_PROCESSES_MSG: {
1002 synchronized (ActivityManagerService.this) {
1003 performAppGcsIfAppropriateLocked();
1004 }
1005 } break;
1006 case WAIT_FOR_DEBUGGER_MSG: {
1007 synchronized (ActivityManagerService.this) {
1008 ProcessRecord app = (ProcessRecord)msg.obj;
1009 if (msg.arg1 != 0) {
1010 if (!app.waitedForDebugger) {
1011 Dialog d = new AppWaitingForDebuggerDialog(
1012 ActivityManagerService.this,
1013 mContext, app);
1014 app.waitDialog = d;
1015 app.waitedForDebugger = true;
1016 d.show();
1017 }
1018 } else {
1019 if (app.waitDialog != null) {
1020 app.waitDialog.dismiss();
1021 app.waitDialog = null;
1022 }
1023 }
1024 }
1025 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001027 if (mDidDexOpt) {
1028 mDidDexOpt = false;
1029 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1030 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001031 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001032 return;
1033 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001034 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 } break;
1036 case UPDATE_TIME_ZONE: {
1037 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 if (r.thread != null) {
1041 try {
1042 r.thread.updateTimeZone();
1043 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001044 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 }
1047 }
1048 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001049 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001050 case CLEAR_DNS_CACHE: {
1051 synchronized (ActivityManagerService.this) {
1052 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1053 ProcessRecord r = mLruProcesses.get(i);
1054 if (r.thread != null) {
1055 try {
1056 r.thread.clearDnsCache();
1057 } catch (RemoteException ex) {
1058 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1059 }
1060 }
1061 }
1062 }
1063 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001064 case UPDATE_HTTP_PROXY: {
1065 ProxyProperties proxy = (ProxyProperties)msg.obj;
1066 String host = "";
1067 String port = "";
1068 String exclList = "";
1069 if (proxy != null) {
1070 host = proxy.getHost();
1071 port = Integer.toString(proxy.getPort());
1072 exclList = proxy.getExclusionList();
1073 }
1074 synchronized (ActivityManagerService.this) {
1075 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1076 ProcessRecord r = mLruProcesses.get(i);
1077 if (r.thread != null) {
1078 try {
1079 r.thread.setHttpProxy(host, port, exclList);
1080 } catch (RemoteException ex) {
1081 Slog.w(TAG, "Failed to update http proxy for: " +
1082 r.info.processName);
1083 }
1084 }
1085 }
1086 }
1087 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001089 String title = "System UIDs Inconsistent";
1090 String text = "UIDs on the system are inconsistent, you need to wipe your"
1091 + " data partition or your device will be unstable.";
1092 Log.e(TAG, title + ": " + text);
1093 if (mShowDialogs) {
1094 // XXX This is a temporary dialog, no need to localize.
1095 AlertDialog d = new BaseErrorDialog(mContext);
1096 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1097 d.setCancelable(false);
1098 d.setTitle(title);
1099 d.setMessage(text);
1100 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1101 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1102 mUidAlert = d;
1103 d.show();
1104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 } break;
1106 case IM_FEELING_LUCKY_MSG: {
1107 if (mUidAlert != null) {
1108 mUidAlert.dismiss();
1109 mUidAlert = null;
1110 }
1111 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001113 if (mDidDexOpt) {
1114 mDidDexOpt = false;
1115 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1116 nmsg.obj = msg.obj;
1117 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1118 return;
1119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 ProcessRecord app = (ProcessRecord)msg.obj;
1121 synchronized (ActivityManagerService.this) {
1122 processStartTimedOutLocked(app);
1123 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001124 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001125 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1126 synchronized (ActivityManagerService.this) {
1127 doPendingActivityLaunchesLocked(true);
1128 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001129 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001130 case KILL_APPLICATION_MSG: {
1131 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001132 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001133 boolean restart = (msg.arg2 == 1);
1134 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001135 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1136 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001137 }
1138 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001139 case FINALIZE_PENDING_INTENT_MSG: {
1140 ((PendingIntentRecord)msg.obj).completeFinalize();
1141 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001142 case POST_HEAVY_NOTIFICATION_MSG: {
1143 INotificationManager inm = NotificationManager.getService();
1144 if (inm == null) {
1145 return;
1146 }
1147
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001148 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001149 ProcessRecord process = root.app;
1150 if (process == null) {
1151 return;
1152 }
1153
1154 try {
1155 Context context = mContext.createPackageContext(process.info.packageName, 0);
1156 String text = mContext.getString(R.string.heavy_weight_notification,
1157 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1158 Notification notification = new Notification();
1159 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1160 notification.when = 0;
1161 notification.flags = Notification.FLAG_ONGOING_EVENT;
1162 notification.tickerText = text;
1163 notification.defaults = 0; // please be quiet
1164 notification.sound = null;
1165 notification.vibrate = null;
1166 notification.setLatestEventInfo(context, text,
1167 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001168 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1169 PendingIntent.FLAG_CANCEL_CURRENT, null,
1170 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001171
1172 try {
1173 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001174 inm.enqueueNotificationWithTag("android", null,
1175 R.string.heavy_weight_notification,
1176 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001177 } catch (RuntimeException e) {
1178 Slog.w(ActivityManagerService.TAG,
1179 "Error showing notification for heavy-weight app", e);
1180 } catch (RemoteException e) {
1181 }
1182 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001183 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001184 }
1185 } break;
1186 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1187 INotificationManager inm = NotificationManager.getService();
1188 if (inm == null) {
1189 return;
1190 }
1191 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001192 inm.cancelNotificationWithTag("android", null,
1193 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001194 } catch (RuntimeException e) {
1195 Slog.w(ActivityManagerService.TAG,
1196 "Error canceling notification for service", e);
1197 } catch (RemoteException e) {
1198 }
1199 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001200 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1201 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001202 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001203 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001204 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1205 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001206 }
1207 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001208 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1209 synchronized (ActivityManagerService.this) {
1210 ActivityRecord ar = (ActivityRecord)msg.obj;
1211 if (mCompatModeDialog != null) {
1212 if (mCompatModeDialog.mAppInfo.packageName.equals(
1213 ar.info.applicationInfo.packageName)) {
1214 return;
1215 }
1216 mCompatModeDialog.dismiss();
1217 mCompatModeDialog = null;
1218 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001219 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001220 if (mCompatModePackages.getPackageAskCompatModeLocked(
1221 ar.packageName)) {
1222 int mode = mCompatModePackages.computeCompatModeLocked(
1223 ar.info.applicationInfo);
1224 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1225 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1226 mCompatModeDialog = new CompatModeDialog(
1227 ActivityManagerService.this, mContext,
1228 ar.info.applicationInfo);
1229 mCompatModeDialog.show();
1230 }
1231 }
1232 }
1233 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001234 break;
1235 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001236 case DISPATCH_PROCESSES_CHANGED: {
1237 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001238 break;
1239 }
1240 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001241 final int pid = msg.arg1;
1242 final int uid = msg.arg2;
1243 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001244 break;
1245 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001246 case REPORT_MEM_USAGE: {
1247 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1248 if (!isDebuggable) {
1249 return;
1250 }
1251 synchronized (ActivityManagerService.this) {
1252 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1254 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001255 // avoid spamming.
1256 return;
1257 }
1258 mLastMemUsageReportTime = now;
1259 }
1260 Thread thread = new Thread() {
1261 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001262 StringBuilder dropBuilder = new StringBuilder(1024);
1263 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001264 StringWriter oomSw = new StringWriter();
1265 PrintWriter oomPw = new PrintWriter(oomSw);
1266 StringWriter catSw = new StringWriter();
1267 PrintWriter catPw = new PrintWriter(catSw);
1268 String[] emptyArgs = new String[] { };
1269 StringBuilder tag = new StringBuilder(128);
1270 StringBuilder stack = new StringBuilder(128);
1271 tag.append("Low on memory -- ");
1272 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1273 tag, stack);
1274 dropBuilder.append(stack);
1275 dropBuilder.append('\n');
1276 dropBuilder.append('\n');
1277 String oomString = oomSw.toString();
1278 dropBuilder.append(oomString);
1279 dropBuilder.append('\n');
1280 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001281 try {
1282 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1283 "procrank", });
1284 final InputStreamReader converter = new InputStreamReader(
1285 proc.getInputStream());
1286 BufferedReader in = new BufferedReader(converter);
1287 String line;
1288 while (true) {
1289 line = in.readLine();
1290 if (line == null) {
1291 break;
1292 }
1293 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001294 logBuilder.append(line);
1295 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001296 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001297 dropBuilder.append(line);
1298 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001299 }
1300 converter.close();
1301 } catch (IOException e) {
1302 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001303 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001304 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001305 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001306 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001307 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1308 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001309 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001310 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001311 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001312 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001313 addErrorToDropBox("lowmem", null, "system_server", null,
1314 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001315 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001316 synchronized (ActivityManagerService.this) {
1317 long now = SystemClock.uptimeMillis();
1318 if (mLastMemUsageReportTime < now) {
1319 mLastMemUsageReportTime = now;
1320 }
1321 }
1322 }
1323 };
1324 thread.start();
1325 break;
1326 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001327 case REPORT_USER_SWITCH_MSG: {
1328 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1329 break;
1330 }
1331 case CONTINUE_USER_SWITCH_MSG: {
1332 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1333 break;
1334 }
1335 case USER_SWITCH_TIMEOUT_MSG: {
1336 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1337 break;
1338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340 }
1341 };
1342
1343 public static void setSystemProcess() {
1344 try {
1345 ActivityManagerService m = mSelf;
1346
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001347 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001349 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001350 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 if (MONITOR_CPU_USAGE) {
1352 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 ServiceManager.addService("permission", new PermissionController(m));
1355
1356 ApplicationInfo info =
1357 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001358 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001359 mSystemThread.installSystemApplicationInfo(info);
1360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 synchronized (mSelf) {
1362 ProcessRecord app = mSelf.newProcessRecordLocked(
1363 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001364 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001366 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001367 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001368 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 synchronized (mSelf.mPidsSelfLocked) {
1370 mSelf.mPidsSelfLocked.put(app.pid, app);
1371 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001372 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374 } catch (PackageManager.NameNotFoundException e) {
1375 throw new RuntimeException(
1376 "Unable to find android system package", e);
1377 }
1378 }
1379
1380 public void setWindowManager(WindowManagerService wm) {
1381 mWindowManager = wm;
1382 }
1383
1384 public static final Context main(int factoryTest) {
1385 AThread thr = new AThread();
1386 thr.start();
1387
1388 synchronized (thr) {
1389 while (thr.mService == null) {
1390 try {
1391 thr.wait();
1392 } catch (InterruptedException e) {
1393 }
1394 }
1395 }
1396
1397 ActivityManagerService m = thr.mService;
1398 mSelf = m;
1399 ActivityThread at = ActivityThread.systemMain();
1400 mSystemThread = at;
1401 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001402 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 m.mContext = context;
1404 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001405 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406
1407 m.mBatteryStatsService.publish(context);
1408 m.mUsageStatsService.publish(context);
1409
1410 synchronized (thr) {
1411 thr.mReady = true;
1412 thr.notifyAll();
1413 }
1414
1415 m.startRunning(null, null, null, null);
1416
1417 return context;
1418 }
1419
1420 public static ActivityManagerService self() {
1421 return mSelf;
1422 }
1423
1424 static class AThread extends Thread {
1425 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001426 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 boolean mReady = false;
1428
1429 public AThread() {
1430 super("ActivityManager");
1431 }
1432
1433 public void run() {
1434 Looper.prepare();
1435
1436 android.os.Process.setThreadPriority(
1437 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001438 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439
1440 ActivityManagerService m = new ActivityManagerService();
1441
1442 synchronized (this) {
1443 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001444 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 notifyAll();
1446 }
1447
1448 synchronized (this) {
1449 while (!mReady) {
1450 try {
1451 wait();
1452 } catch (InterruptedException e) {
1453 }
1454 }
1455 }
1456
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001457 // For debug builds, log event loop stalls to dropbox for analysis.
1458 if (StrictMode.conditionallyEnableDebugLogging()) {
1459 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1460 }
1461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 Looper.loop();
1463 }
1464 }
1465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 static class MemBinder extends Binder {
1467 ActivityManagerService mActivityManagerService;
1468 MemBinder(ActivityManagerService activityManagerService) {
1469 mActivityManagerService = activityManagerService;
1470 }
1471
1472 @Override
1473 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001474 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1475 != PackageManager.PERMISSION_GRANTED) {
1476 pw.println("Permission Denial: can't dump meminfo from from pid="
1477 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1478 + " without permission " + android.Manifest.permission.DUMP);
1479 return;
1480 }
1481
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001482 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001483 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
1485 }
1486
Chet Haase9c1e23b2011-03-24 10:51:31 -07001487 static class GraphicsBinder extends Binder {
1488 ActivityManagerService mActivityManagerService;
1489 GraphicsBinder(ActivityManagerService activityManagerService) {
1490 mActivityManagerService = activityManagerService;
1491 }
1492
1493 @Override
1494 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001495 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1496 != PackageManager.PERMISSION_GRANTED) {
1497 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1498 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1499 + " without permission " + android.Manifest.permission.DUMP);
1500 return;
1501 }
1502
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001503 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001504 }
1505 }
1506
Jeff Brown6754ba22011-12-14 20:20:01 -08001507 static class DbBinder extends Binder {
1508 ActivityManagerService mActivityManagerService;
1509 DbBinder(ActivityManagerService activityManagerService) {
1510 mActivityManagerService = activityManagerService;
1511 }
1512
1513 @Override
1514 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1515 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1516 != PackageManager.PERMISSION_GRANTED) {
1517 pw.println("Permission Denial: can't dump dbinfo from from pid="
1518 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1519 + " without permission " + android.Manifest.permission.DUMP);
1520 return;
1521 }
1522
1523 mActivityManagerService.dumpDbInfo(fd, pw, args);
1524 }
1525 }
1526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 static class CpuBinder extends Binder {
1528 ActivityManagerService mActivityManagerService;
1529 CpuBinder(ActivityManagerService activityManagerService) {
1530 mActivityManagerService = activityManagerService;
1531 }
1532
1533 @Override
1534 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001535 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1536 != PackageManager.PERMISSION_GRANTED) {
1537 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1538 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1539 + " without permission " + android.Manifest.permission.DUMP);
1540 return;
1541 }
1542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001544 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1545 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1546 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549 }
1550
1551 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001552 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001553
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001554 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1555 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1556 mBroadcastQueues[0] = mFgBroadcastQueue;
1557 mBroadcastQueues[1] = mBgBroadcastQueue;
1558
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001559 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001560 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 File dataDir = Environment.getDataDirectory();
1563 File systemDir = new File(dataDir, "system");
1564 systemDir.mkdirs();
1565 mBatteryStatsService = new BatteryStatsService(new File(
1566 systemDir, "batterystats.bin").toString());
1567 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001568 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001569 mOnBattery = DEBUG_POWER ? true
1570 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001571 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001573 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001574 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001575 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001577 // User 0 is the first and only user that runs at boot.
1578 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001579 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001580 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001581
Jack Palevichb90d28c2009-07-22 15:35:24 -07001582 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1583 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1584
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001585 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001586 mConfiguration.setLocale(Locale.getDefault());
1587
Dianne Hackborn813075a62011-11-14 17:45:19 -08001588 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 mProcessStats.init();
1590
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001591 mCompatModePackages = new CompatModePackages(this, systemDir);
1592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 // Add ourself to the Watchdog monitors.
1594 Watchdog.getInstance().addMonitor(this);
1595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 mProcessStatsThread = new Thread("ProcessStats") {
1597 public void run() {
1598 while (true) {
1599 try {
1600 try {
1601 synchronized(this) {
1602 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001603 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 // + ", write delay=" + nextWriteDelay);
1607 if (nextWriteDelay < nextCpuDelay) {
1608 nextCpuDelay = nextWriteDelay;
1609 }
1610 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001611 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 this.wait(nextCpuDelay);
1613 }
1614 }
1615 } catch (InterruptedException e) {
1616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 updateCpuStatsNow();
1618 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001619 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 }
1621 }
1622 }
1623 };
1624 mProcessStatsThread.start();
1625 }
1626
1627 @Override
1628 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1629 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001630 if (code == SYSPROPS_TRANSACTION) {
1631 // We need to tell all apps about the system property change.
1632 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1633 synchronized(this) {
1634 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1635 final int NA = apps.size();
1636 for (int ia=0; ia<NA; ia++) {
1637 ProcessRecord app = apps.valueAt(ia);
1638 if (app.thread != null) {
1639 procs.add(app.thread.asBinder());
1640 }
1641 }
1642 }
1643 }
1644
1645 int N = procs.size();
1646 for (int i=0; i<N; i++) {
1647 Parcel data2 = Parcel.obtain();
1648 try {
1649 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1650 } catch (RemoteException e) {
1651 }
1652 data2.recycle();
1653 }
1654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 try {
1656 return super.onTransact(code, data, reply, flags);
1657 } catch (RuntimeException e) {
1658 // The activity manager only throws security exceptions, so let's
1659 // log all others.
1660 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663 throw e;
1664 }
1665 }
1666
1667 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001668 final long now = SystemClock.uptimeMillis();
1669 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1670 return;
1671 }
1672 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1673 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 mProcessStatsThread.notify();
1675 }
1676 }
1677 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 void updateCpuStatsNow() {
1680 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001681 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 final long now = SystemClock.uptimeMillis();
1683 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001686 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1687 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 haveNewCpuStats = true;
1689 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001690 //Slog.i(TAG, mProcessStats.printCurrentState());
1691 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 // + mProcessStats.getTotalCpuPercent() + "%");
1693
Joe Onorato8a9b2202010-02-26 18:56:32 -08001694 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 if ("true".equals(SystemProperties.get("events.cpu"))) {
1696 int user = mProcessStats.getLastUserTime();
1697 int system = mProcessStats.getLastSystemTime();
1698 int iowait = mProcessStats.getLastIoWaitTime();
1699 int irq = mProcessStats.getLastIrqTime();
1700 int softIrq = mProcessStats.getLastSoftIrqTime();
1701 int idle = mProcessStats.getLastIdleTime();
1702
1703 int total = user + system + iowait + irq + softIrq + idle;
1704 if (total == 0) total = 1;
1705
Doug Zongker2bec3d42009-12-04 12:52:44 -08001706 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 ((user+system+iowait+irq+softIrq) * 100) / total,
1708 (user * 100) / total,
1709 (system * 100) / total,
1710 (iowait * 100) / total,
1711 (irq * 100) / total,
1712 (softIrq * 100) / total);
1713 }
1714 }
1715
Amith Yamasanie43530a2009-08-21 13:11:37 -07001716 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001717 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001718 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 synchronized(mPidsSelfLocked) {
1720 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001721 if (mOnBattery) {
1722 int perc = bstats.startAddingCpuLocked();
1723 int totalUTime = 0;
1724 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001725 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001727 ProcessStats.Stats st = mProcessStats.getStats(i);
1728 if (!st.working) {
1729 continue;
1730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001732 int otherUTime = (st.rel_utime*perc)/100;
1733 int otherSTime = (st.rel_stime*perc)/100;
1734 totalUTime += otherUTime;
1735 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 if (pr != null) {
1737 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001738 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1739 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001740 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001741 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001742 } else {
1743 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001744 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001745 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001746 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1747 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001748 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001752 bstats.finishAddingCpuLocked(perc, totalUTime,
1753 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755 }
1756 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1759 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001760 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762 }
1763 }
1764 }
1765
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001766 @Override
1767 public void batteryNeedsCpuUpdate() {
1768 updateCpuStatsNow();
1769 }
1770
1771 @Override
1772 public void batteryPowerChanged(boolean onBattery) {
1773 // When plugging in, update the CPU stats first before changing
1774 // the plug state.
1775 updateCpuStatsNow();
1776 synchronized (this) {
1777 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001778 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001779 }
1780 }
1781 }
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 /**
1784 * Initialize the application bind args. These are passed to each
1785 * process when the bindApplication() IPC is sent to the process. They're
1786 * lazily setup to make sure the services are running when they're asked for.
1787 */
1788 private HashMap<String, IBinder> getCommonServicesLocked() {
1789 if (mAppBindArgs == null) {
1790 mAppBindArgs = new HashMap<String, IBinder>();
1791
1792 // Setup the application init args
1793 mAppBindArgs.put("package", ServiceManager.getService("package"));
1794 mAppBindArgs.put("window", ServiceManager.getService("window"));
1795 mAppBindArgs.put(Context.ALARM_SERVICE,
1796 ServiceManager.getService(Context.ALARM_SERVICE));
1797 }
1798 return mAppBindArgs;
1799 }
1800
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001801 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 if (mFocusedActivity != r) {
1803 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001804 if (r != null) {
1805 mWindowManager.setFocusedApp(r.appToken, true);
1806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
1808 }
1809
Dianne Hackborn906497c2010-05-10 15:57:38 -07001810 private final void updateLruProcessInternalLocked(ProcessRecord app,
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001811 boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001813 int lrui = mLruProcesses.indexOf(app);
1814 if (lrui >= 0) mLruProcesses.remove(lrui);
1815
1816 int i = mLruProcesses.size()-1;
1817 int skipTop = 0;
1818
Dianne Hackborn906497c2010-05-10 15:57:38 -07001819 app.lruSeq = mLruSeq;
1820
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001821 // compute the new weight for this process.
1822 if (updateActivityTime) {
1823 app.lastActivityTime = SystemClock.uptimeMillis();
1824 }
1825 if (app.activities.size() > 0) {
1826 // If this process has activities, we more strongly want to keep
1827 // it around.
1828 app.lruWeight = app.lastActivityTime;
1829 } else if (app.pubProviders.size() > 0) {
1830 // If this process contains content providers, we want to keep
1831 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001832 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001833 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001834 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001835 } else {
1836 // If this process doesn't have activities, we less strongly
1837 // want to keep it around, and generally want to avoid getting
1838 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001839 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001840 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001841 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001842 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001843
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001844 while (i >= 0) {
1845 ProcessRecord p = mLruProcesses.get(i);
1846 // If this app shouldn't be in front of the first N background
1847 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001848 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001849 skipTop--;
1850 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001851 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001852 mLruProcesses.add(i+1, app);
1853 break;
1854 }
1855 i--;
1856 }
1857 if (i < 0) {
1858 mLruProcesses.add(0, app);
1859 }
1860
Dianne Hackborn906497c2010-05-10 15:57:38 -07001861 // If the app is currently using a content provider or service,
1862 // bump those processes as well.
1863 if (app.connections.size() > 0) {
1864 for (ConnectionRecord cr : app.connections) {
1865 if (cr.binding != null && cr.binding.service != null
1866 && cr.binding.service.app != null
1867 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001868 updateLruProcessInternalLocked(cr.binding.service.app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001869 updateActivityTime, i+1);
1870 }
1871 }
1872 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001873 for (int j=app.conProviders.size()-1; j>=0; j--) {
1874 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1875 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001876 updateLruProcessInternalLocked(cpr.proc,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001877 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001878 }
1879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
1881
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001882 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001883 boolean oomAdj, boolean updateActivityTime) {
1884 mLruSeq++;
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001885 updateLruProcessInternalLocked(app, updateActivityTime, 0);
1886
1887 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1888 if (oomAdj) {
1889 updateOomAdjLocked();
1890 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001891 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001892
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001893 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001895 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001896 // The system gets to run in any process. If there are multiple
1897 // processes with the same uid, just pick the first (this
1898 // should never happen).
1899 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1900 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001901 if (procs == null) return null;
1902 final int N = procs.size();
1903 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001904 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907 ProcessRecord proc = mProcessNames.get(processName, uid);
1908 return proc;
1909 }
1910
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001912 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001913 try {
1914 if (pm.performDexOpt(packageName)) {
1915 mDidDexOpt = true;
1916 }
1917 } catch (RemoteException e) {
1918 }
1919 }
1920
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001921 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 int transit = mWindowManager.getPendingAppTransition();
1923 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1924 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1925 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1926 }
1927
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001928 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001930 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1931 boolean isolated) {
1932 ProcessRecord app;
1933 if (!isolated) {
1934 app = getProcessRecordLocked(processName, info.uid);
1935 } else {
1936 // If this is an isolated process, it can't re-use an existing process.
1937 app = null;
1938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 // We don't have to do anything more if:
1940 // (1) There is an existing application record; and
1941 // (2) The caller doesn't think it is dead, OR there is no thread
1942 // object attached to it so we know it couldn't have crashed; and
1943 // (3) There is a pid assigned to it, so it is either starting or
1944 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001945 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 + " app=" + app + " knownToBeDead=" + knownToBeDead
1947 + " thread=" + (app != null ? app.thread : null)
1948 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001949 if (app != null && app.pid > 0) {
1950 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001951 // We already have the app running, or are waiting for it to
1952 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001953 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001954 // If this is a new package in the process, add the package to the list
1955 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001956 return app;
1957 } else {
1958 // An application record is attached to a previous process,
1959 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001960 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001961 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 String hostingNameStr = hostingName != null
1966 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001967
1968 if (!isolated) {
1969 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1970 // If we are in the background, then check to see if this process
1971 // is bad. If so, we will just silently fail.
1972 if (mBadProcesses.get(info.processName, info.uid) != null) {
1973 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1974 + "/" + info.processName);
1975 return null;
1976 }
1977 } else {
1978 // When the user is explicitly starting a process, then clear its
1979 // crash count so that we won't make it bad until they see at
1980 // least one crash dialog again, and make the process good again
1981 // if it had been bad.
1982 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001983 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001984 mProcessCrashTimes.remove(info.processName, info.uid);
1985 if (mBadProcesses.get(info.processName, info.uid) != null) {
1986 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1987 info.processName);
1988 mBadProcesses.remove(info.processName, info.uid);
1989 if (app != null) {
1990 app.bad = false;
1991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993 }
1994 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001997 app = newProcessRecordLocked(null, info, processName, isolated);
1998 if (app == null) {
1999 Slog.w(TAG, "Failed making new process record for "
2000 + processName + "/" + info.uid + " isolated=" + isolated);
2001 return null;
2002 }
2003 mProcessNames.put(processName, app.uid, app);
2004 if (isolated) {
2005 mIsolatedProcesses.put(app.uid, app);
2006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 } else {
2008 // If this is a new package in the process, add the package to the list
2009 app.addPackage(info.packageName);
2010 }
2011
2012 // If the system is not ready yet, then hold off on starting this
2013 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002014 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002015 && !isAllowedWhileBooting(info)
2016 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 if (!mProcessesOnHold.contains(app)) {
2018 mProcessesOnHold.add(app);
2019 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002020 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 return app;
2022 }
2023
2024 startProcessLocked(app, hostingType, hostingNameStr);
2025 return (app.pid != 0) ? app : null;
2026 }
2027
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002028 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2029 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2030 }
2031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 private final void startProcessLocked(ProcessRecord app,
2033 String hostingType, String hostingNameStr) {
2034 if (app.pid > 0 && app.pid != MY_PID) {
2035 synchronized (mPidsSelfLocked) {
2036 mPidsSelfLocked.remove(app.pid);
2037 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2038 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002039 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002042 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2043 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 mProcessesOnHold.remove(app);
2045
2046 updateCpuStats();
2047
2048 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2049 mProcDeaths[0] = 0;
2050
2051 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002052 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002055 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002056 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002057 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002058 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002059 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002060 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002061
2062 if (Environment.isExternalStorageEmulated()) {
2063 if (pm.checkPermission(
2064 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2065 app.info.packageName) == PERMISSION_GRANTED) {
2066 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2067 } else {
2068 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2069 }
2070 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002071 } catch (PackageManager.NameNotFoundException e) {
2072 Slog.w(TAG, "Unable to retrieve gids", e);
2073 }
Kenny Roote091f222012-09-11 15:01:26 -07002074
2075 /*
2076 * Add shared application GID so applications can share some
2077 * resources like shared libraries
2078 */
2079 if (permGids == null) {
2080 gids = new int[1];
2081 } else {
2082 gids = new int[permGids.length + 1];
2083 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2084 }
2085 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
2087 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2088 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2089 && mTopComponent != null
2090 && app.processName.equals(mTopComponent.getPackageName())) {
2091 uid = 0;
2092 }
2093 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2094 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2095 uid = 0;
2096 }
2097 }
2098 int debugFlags = 0;
2099 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2100 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002101 // Also turn on CheckJNI for debuggable apps. It's quite
2102 // awkward to turn on otherwise.
2103 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002105 // Run the app in safe mode if its manifest requests so or the
2106 // system is booted in safe mode.
2107 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2108 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002109 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2112 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2113 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002114 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2115 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 if ("1".equals(SystemProperties.get("debug.assert"))) {
2118 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2119 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002120
2121 // Start the process. It will either succeed and return a result containing
2122 // the PID of the new process, or else throw a RuntimeException.
2123 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002124 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002125 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2128 synchronized (bs) {
2129 if (bs.isOnBattery()) {
2130 app.batteryStats.incStartsLocked();
2131 }
2132 }
2133
Jeff Brown3f9dd282011-07-08 20:02:19 -07002134 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 app.processName, hostingType,
2136 hostingNameStr != null ? hostingNameStr : "");
2137
2138 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002139 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 }
2141
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002142 StringBuilder buf = mStringBuilder;
2143 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 buf.append("Start proc ");
2145 buf.append(app.processName);
2146 buf.append(" for ");
2147 buf.append(hostingType);
2148 if (hostingNameStr != null) {
2149 buf.append(" ");
2150 buf.append(hostingNameStr);
2151 }
2152 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002153 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 buf.append(" uid=");
2155 buf.append(uid);
2156 buf.append(" gids={");
2157 if (gids != null) {
2158 for (int gi=0; gi<gids.length; gi++) {
2159 if (gi != 0) buf.append(", ");
2160 buf.append(gids[gi]);
2161
2162 }
2163 }
2164 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002165 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002166 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002167 app.usingWrapper = startResult.usingWrapper;
2168 app.removed = false;
2169 synchronized (mPidsSelfLocked) {
2170 this.mPidsSelfLocked.put(startResult.pid, app);
2171 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2172 msg.obj = app;
2173 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2174 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 }
2176 } catch (RuntimeException e) {
2177 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002178 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002179 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 }
2181 }
2182
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002183 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 if (resumed) {
2185 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2186 } else {
2187 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2188 }
2189 }
2190
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002191 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002192 if (mHeadless) {
2193 // Added because none of the other calls to ensureBootCompleted seem to fire
2194 // when running headless.
2195 ensureBootCompleted();
2196 return false;
2197 }
2198
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002199 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2200 && mTopAction == null) {
2201 // We are running in factory test mode, but unable to find
2202 // the factory test app, so just sit around displaying the
2203 // error message and don't try to start anything.
2204 return false;
2205 }
2206 Intent intent = new Intent(
2207 mTopAction,
2208 mTopData != null ? Uri.parse(mTopData) : null);
2209 intent.setComponent(mTopComponent);
2210 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2211 intent.addCategory(Intent.CATEGORY_HOME);
2212 }
2213 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002214 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002215 if (aInfo != null) {
2216 intent.setComponent(new ComponentName(
2217 aInfo.applicationInfo.packageName, aInfo.name));
2218 // Don't do this if the home app is currently being
2219 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002220 aInfo = new ActivityInfo(aInfo);
2221 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002222 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2223 aInfo.applicationInfo.uid);
2224 if (app == null || app.instrumentationClass == null) {
2225 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002226 mMainStack.startActivityLocked(null, intent, null, aInfo,
2227 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002228 }
2229 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002230
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002231 return true;
2232 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002233
Amith Yamasani259d5e52012-08-31 15:11:01 -07002234 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2235 ActivityInfo ai = null;
2236 ComponentName comp = intent.getComponent();
2237 try {
2238 if (comp != null) {
2239 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2240 } else {
2241 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2242 intent,
2243 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2244 flags, userId);
2245
2246 if (info != null) {
2247 ai = info.activityInfo;
2248 }
2249 }
2250 } catch (RemoteException e) {
2251 // ignore
2252 }
2253
2254 return ai;
2255 }
2256
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002257 /**
2258 * Starts the "new version setup screen" if appropriate.
2259 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002260 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002261 // Only do this once per boot.
2262 if (mCheckedForSetup) {
2263 return;
2264 }
2265
2266 // We will show this screen if the current one is a different
2267 // version than the last one shown, and we are not running in
2268 // low-level factory test mode.
2269 final ContentResolver resolver = mContext.getContentResolver();
2270 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2271 Settings.Secure.getInt(resolver,
2272 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2273 mCheckedForSetup = true;
2274
2275 // See if we should be showing the platform update setup UI.
2276 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2277 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2278 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2279
2280 // We don't allow third party apps to replace this.
2281 ResolveInfo ri = null;
2282 for (int i=0; ris != null && i<ris.size(); i++) {
2283 if ((ris.get(i).activityInfo.applicationInfo.flags
2284 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2285 ri = ris.get(i);
2286 break;
2287 }
2288 }
2289
2290 if (ri != null) {
2291 String vers = ri.activityInfo.metaData != null
2292 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2293 : null;
2294 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2295 vers = ri.activityInfo.applicationInfo.metaData.getString(
2296 Intent.METADATA_SETUP_VERSION);
2297 }
2298 String lastVers = Settings.Secure.getString(
2299 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2300 if (vers != null && !vers.equals(lastVers)) {
2301 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2302 intent.setComponent(new ComponentName(
2303 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002304 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2305 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002306 }
2307 }
2308 }
2309 }
2310
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002311 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002312 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002313 }
2314
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002316 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002317 throw new SecurityException("Isolated process not allowed to call " + caller);
2318 }
2319 }
2320
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002321 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002322 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002323 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002324 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2325 }
2326 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002327
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002328 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002329 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2330 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002331 synchronized (this) {
2332 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2333 }
2334 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002335
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002336 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002337 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002338 synchronized (this) {
2339 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2340 }
2341 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002342
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002343 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002344 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2345 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002346 synchronized (this) {
2347 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002348 }
2349 }
2350
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002351 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002352 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002353 synchronized (this) {
2354 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2355 }
2356 }
2357
2358 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002359 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2360 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002361 synchronized (this) {
2362 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2363 }
2364 }
2365
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002366 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002367 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002368 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002371 private void dispatchProcessesChanged() {
2372 int N;
2373 synchronized (this) {
2374 N = mPendingProcessChanges.size();
2375 if (mActiveProcessChanges.length < N) {
2376 mActiveProcessChanges = new ProcessChangeItem[N];
2377 }
2378 mPendingProcessChanges.toArray(mActiveProcessChanges);
2379 mAvailProcessChanges.addAll(mPendingProcessChanges);
2380 mPendingProcessChanges.clear();
2381 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2382 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002383 int i = mProcessObservers.beginBroadcast();
2384 while (i > 0) {
2385 i--;
2386 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2387 if (observer != null) {
2388 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002389 for (int j=0; j<N; j++) {
2390 ProcessChangeItem item = mActiveProcessChanges[j];
2391 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2392 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2393 + item.pid + " uid=" + item.uid + ": "
2394 + item.foregroundActivities);
2395 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2396 item.foregroundActivities);
2397 }
2398 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2399 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2400 + item.pid + " uid=" + item.uid + ": " + item.importance);
2401 observer.onImportanceChanged(item.pid, item.uid,
2402 item.importance);
2403 }
2404 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002405 } catch (RemoteException e) {
2406 }
2407 }
2408 }
2409 mProcessObservers.finishBroadcast();
2410 }
2411
2412 private void dispatchProcessDied(int pid, int uid) {
2413 int i = mProcessObservers.beginBroadcast();
2414 while (i > 0) {
2415 i--;
2416 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2417 if (observer != null) {
2418 try {
2419 observer.onProcessDied(pid, uid);
2420 } catch (RemoteException e) {
2421 }
2422 }
2423 }
2424 mProcessObservers.finishBroadcast();
2425 }
2426
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002427 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002428 final int N = mPendingActivityLaunches.size();
2429 if (N <= 0) {
2430 return;
2431 }
2432 for (int i=0; i<N; i++) {
2433 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002434 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002435 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002436 }
2437 mPendingActivityLaunches.clear();
2438 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002439
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002440 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002441 Intent intent, String resolvedType, IBinder resultTo,
2442 String resultWho, int requestCode, int startFlags,
2443 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002444 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002445 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002446 }
2447
2448 public final int startActivityAsUser(IApplicationThread caller,
2449 Intent intent, String resolvedType, IBinder resultTo,
2450 String resultWho, int requestCode, int startFlags,
2451 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002452 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002453 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002454 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002455 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002456 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2457 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002458 }
2459
2460 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002461 Intent intent, String resolvedType, IBinder resultTo,
2462 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002463 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002464 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002465 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002466 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002467 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002468 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002469 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002470 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002471 return res;
2472 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002473
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002474 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 Intent intent, String resolvedType, IBinder resultTo,
2476 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002477 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002478 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002479 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002480 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002481 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002482 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002483 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002484 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002485 }
2486
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002487 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002488 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002489 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002490 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002491 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002492 // Refuse possible leaked file descriptors
2493 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2494 throw new IllegalArgumentException("File descriptors passed in Intent");
2495 }
2496
2497 IIntentSender sender = intent.getTarget();
2498 if (!(sender instanceof PendingIntentRecord)) {
2499 throw new IllegalArgumentException("Bad PendingIntent object");
2500 }
2501
2502 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002503
2504 synchronized (this) {
2505 // If this is coming from the currently resumed activity, it is
2506 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002507 if (mMainStack.mResumedActivity != null
2508 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002509 Binder.getCallingUid()) {
2510 mAppSwitchesAllowedTime = 0;
2511 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002512 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002513 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2514 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002515 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002516 }
2517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002519 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 // Refuse possible leaked file descriptors
2521 if (intent != null && intent.hasFileDescriptors() == true) {
2522 throw new IllegalArgumentException("File descriptors passed in Intent");
2523 }
2524
2525 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002526 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2527 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002528 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 return false;
2530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 if (r.app == null || r.app.thread == null) {
2532 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002533 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 return false;
2535 }
2536 intent = new Intent(intent);
2537 // The caller is not allowed to change the data.
2538 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2539 // And we are resetting to find the next component...
2540 intent.setComponent(null);
2541
2542 ActivityInfo aInfo = null;
2543 try {
2544 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002545 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002547 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002548 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549
2550 // Look for the original activity in the list...
2551 final int N = resolves != null ? resolves.size() : 0;
2552 for (int i=0; i<N; i++) {
2553 ResolveInfo rInfo = resolves.get(i);
2554 if (rInfo.activityInfo.packageName.equals(r.packageName)
2555 && rInfo.activityInfo.name.equals(r.info.name)) {
2556 // We found the current one... the next matching is
2557 // after it.
2558 i++;
2559 if (i<N) {
2560 aInfo = resolves.get(i).activityInfo;
2561 }
2562 break;
2563 }
2564 }
2565 } catch (RemoteException e) {
2566 }
2567
2568 if (aInfo == null) {
2569 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002570 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 return false;
2572 }
2573
2574 intent.setComponent(new ComponentName(
2575 aInfo.applicationInfo.packageName, aInfo.name));
2576 intent.setFlags(intent.getFlags()&~(
2577 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2578 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2579 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2580 Intent.FLAG_ACTIVITY_NEW_TASK));
2581
2582 // Okay now we need to start the new activity, replacing the
2583 // currently running activity. This is a little tricky because
2584 // we want to start the new one as if the current one is finished,
2585 // but not finish the current one first so that there is no flicker.
2586 // And thus...
2587 final boolean wasFinishing = r.finishing;
2588 r.finishing = true;
2589
2590 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002591 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 final String resultWho = r.resultWho;
2593 final int requestCode = r.requestCode;
2594 r.resultTo = null;
2595 if (resultTo != null) {
2596 resultTo.removeResultsLocked(r, resultWho, requestCode);
2597 }
2598
2599 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002600 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002601 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2602 resultWho, requestCode, -1, r.launchedFromUid, 0,
2603 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 Binder.restoreCallingIdentity(origId);
2605
2606 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002607 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 return false;
2609 }
2610 return true;
2611 }
2612 }
2613
Dianne Hackborn41203752012-08-31 14:05:51 -07002614 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002616 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2617
Dianne Hackborn139748f2012-09-24 11:36:57 -07002618 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002619 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620
Amith Yamasani742a6712011-05-04 14:49:28 -07002621 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002622 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002623 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002624 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002625 }
2626
2627 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002628 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2629 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002630 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002631 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002632 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002633 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002634 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002635 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002636 }
2637
Dianne Hackborn41203752012-08-31 14:05:51 -07002638 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002639 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002640 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002641
Dianne Hackborn139748f2012-09-24 11:36:57 -07002642 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002643 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002644 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002645 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002646 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002649 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002651 // Quick case: check if the top-most recent task is the same.
2652 if (N > 0 && mRecentTasks.get(0) == task) {
2653 return;
2654 }
2655 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 for (int i=0; i<N; i++) {
2657 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002658 if (task.userId == tr.userId
2659 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2660 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 mRecentTasks.remove(i);
2662 i--;
2663 N--;
2664 if (task.intent == null) {
2665 // If the new recent task we are adding is not fully
2666 // specified, then replace it with the existing recent task.
2667 task = tr;
2668 }
2669 }
2670 }
2671 if (N >= MAX_RECENT_TASKS) {
2672 mRecentTasks.remove(N-1);
2673 }
2674 mRecentTasks.add(0, task);
2675 }
2676
2677 public void setRequestedOrientation(IBinder token,
2678 int requestedOrientation) {
2679 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002680 ActivityRecord r = mMainStack.isInStackLocked(token);
2681 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 return;
2683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002685 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002687 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002688 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 if (config != null) {
2690 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002691 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002692 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 }
2694 }
2695 Binder.restoreCallingIdentity(origId);
2696 }
2697 }
2698
2699 public int getRequestedOrientation(IBinder token) {
2700 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002701 ActivityRecord r = mMainStack.isInStackLocked(token);
2702 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2704 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002705 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
2707 }
2708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 /**
2710 * This is the internal entry point for handling Activity.finish().
2711 *
2712 * @param token The Binder token referencing the Activity we want to finish.
2713 * @param resultCode Result code, if any, from this Activity.
2714 * @param resultData Result data (Intent), if any, from this Activity.
2715 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002716 * @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 -08002717 */
2718 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2719 // Refuse possible leaked file descriptors
2720 if (resultData != null && resultData.hasFileDescriptors() == true) {
2721 throw new IllegalArgumentException("File descriptors passed in Intent");
2722 }
2723
2724 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002725 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002727 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 if (next != null) {
2729 // ask watcher if this is allowed
2730 boolean resumeOK = true;
2731 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002732 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002734 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 }
2736
2737 if (!resumeOK) {
2738 return false;
2739 }
2740 }
2741 }
2742 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002743 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002744 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 Binder.restoreCallingIdentity(origId);
2746 return res;
2747 }
2748 }
2749
Dianne Hackborn860755f2010-06-03 18:47:52 -07002750 public final void finishHeavyWeightApp() {
2751 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2752 != PackageManager.PERMISSION_GRANTED) {
2753 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2754 + Binder.getCallingPid()
2755 + ", uid=" + Binder.getCallingUid()
2756 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2757 Slog.w(TAG, msg);
2758 throw new SecurityException(msg);
2759 }
2760
2761 synchronized(this) {
2762 if (mHeavyWeightProcess == null) {
2763 return;
2764 }
2765
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002766 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002767 mHeavyWeightProcess.activities);
2768 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002769 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002770 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002771 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002772 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002773 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002774 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002775 }
2776 }
2777 }
2778
Dianne Hackborn41203752012-08-31 14:05:51 -07002779 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2780 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002781 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002782 }
2783 }
2784
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002785 public void crashApplication(int uid, int initialPid, String packageName,
2786 String message) {
2787 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2788 != PackageManager.PERMISSION_GRANTED) {
2789 String msg = "Permission Denial: crashApplication() from pid="
2790 + Binder.getCallingPid()
2791 + ", uid=" + Binder.getCallingUid()
2792 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2793 Slog.w(TAG, msg);
2794 throw new SecurityException(msg);
2795 }
2796
2797 synchronized(this) {
2798 ProcessRecord proc = null;
2799
2800 // Figure out which process to kill. We don't trust that initialPid
2801 // still has any relation to current pids, so must scan through the
2802 // list.
2803 synchronized (mPidsSelfLocked) {
2804 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2805 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002806 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002807 continue;
2808 }
2809 if (p.pid == initialPid) {
2810 proc = p;
2811 break;
2812 }
2813 for (String str : p.pkgList) {
2814 if (str.equals(packageName)) {
2815 proc = p;
2816 }
2817 }
2818 }
2819 }
2820
2821 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002822 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002823 + " initialPid=" + initialPid
2824 + " packageName=" + packageName);
2825 return;
2826 }
2827
2828 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002829 if (proc.pid == Process.myPid()) {
2830 Log.w(TAG, "crashApplication: trying to crash self!");
2831 return;
2832 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002833 long ident = Binder.clearCallingIdentity();
2834 try {
2835 proc.thread.scheduleCrash(message);
2836 } catch (RemoteException e) {
2837 }
2838 Binder.restoreCallingIdentity(ident);
2839 }
2840 }
2841 }
2842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 public final void finishSubActivity(IBinder token, String resultWho,
2844 int requestCode) {
2845 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002847 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 Binder.restoreCallingIdentity(origId);
2849 }
2850 }
2851
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002852 public boolean finishActivityAffinity(IBinder token) {
2853 synchronized(this) {
2854 final long origId = Binder.clearCallingIdentity();
2855 boolean res = mMainStack.finishActivityAffinityLocked(token);
2856 Binder.restoreCallingIdentity(origId);
2857 return res;
2858 }
2859 }
2860
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002861 public boolean willActivityBeVisible(IBinder token) {
2862 synchronized(this) {
2863 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002864 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2865 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002866 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002867 return true;
2868 }
2869 if (r.fullscreen && !r.finishing) {
2870 return false;
2871 }
2872 }
2873 return true;
2874 }
2875 }
2876
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002877 public void overridePendingTransition(IBinder token, String packageName,
2878 int enterAnim, int exitAnim) {
2879 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002880 ActivityRecord self = mMainStack.isInStackLocked(token);
2881 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002882 return;
2883 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002884
2885 final long origId = Binder.clearCallingIdentity();
2886
2887 if (self.state == ActivityState.RESUMED
2888 || self.state == ActivityState.PAUSING) {
2889 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002890 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002891 }
2892
2893 Binder.restoreCallingIdentity(origId);
2894 }
2895 }
2896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 * Main function for removing an existing process from the activity manager
2899 * as a result of that process going away. Clears out all connections
2900 * to the process.
2901 */
2902 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002903 boolean restarting, boolean allowRestart) {
2904 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002906 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 }
2908
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002909 if (mProfileProc == app) {
2910 clearProfilerLocked();
2911 }
2912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002914 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2915 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2916 mMainStack.mPausingActivity = null;
2917 }
2918 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2919 mMainStack.mLastPausedActivity = null;
2920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921
2922 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002923 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924
2925 boolean atTop = true;
2926 boolean hasVisibleActivities = false;
2927
2928 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002929 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002930 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 TAG, "Removing app " + app + " from history with " + i + " entries");
2932 while (i > 0) {
2933 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002934 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002935 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2937 if (r.app == app) {
2938 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002939 if (ActivityStack.DEBUG_ADD_REMOVE) {
2940 RuntimeException here = new RuntimeException("here");
2941 here.fillInStackTrace();
2942 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2943 + ": haveState=" + r.haveState
2944 + " stateNotNeeded=" + r.stateNotNeeded
2945 + " finishing=" + r.finishing
2946 + " state=" + r.state, here);
2947 }
2948 if (!r.finishing) {
2949 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002950 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2951 System.identityHashCode(r),
2952 r.task.taskId, r.shortComponentName,
2953 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002954 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002955 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956
2957 } else {
2958 // We have the current state for this activity, so
2959 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002960 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 TAG, "Keeping entry, setting app to null");
2962 if (r.visible) {
2963 hasVisibleActivities = true;
2964 }
2965 r.app = null;
2966 r.nowVisible = false;
2967 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002968 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2969 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 r.icicle = null;
2971 }
2972 }
2973
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002974 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 }
2976 atTop = false;
2977 }
2978
2979 app.activities.clear();
2980
2981 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002982 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 + " running instrumentation " + app.instrumentationClass);
2984 Bundle info = new Bundle();
2985 info.putString("shortMsg", "Process crashed.");
2986 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2987 }
2988
2989 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002990 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 // If there was nothing to resume, and we are not already
2992 // restarting this process, but there is a visible activity that
2993 // is hosted by the process... then make sure all visible
2994 // activities are running, taking care of restarting this
2995 // process.
2996 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002997 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 }
2999 }
3000 }
3001 }
3002
3003 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3004 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003006 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3007 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3009 return i;
3010 }
3011 }
3012 return -1;
3013 }
3014
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003015 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 IApplicationThread thread) {
3017 if (thread == null) {
3018 return null;
3019 }
3020
3021 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003022 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 }
3024
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003025 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 IApplicationThread thread) {
3027
3028 mProcDeaths[0]++;
3029
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003030 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3031 synchronized (stats) {
3032 stats.noteProcessDiedLocked(app.info.uid, pid);
3033 }
3034
Magnus Edlund7bb25812010-02-24 15:45:06 +01003035 // Clean up already done if the process has been re-started.
3036 if (app.pid == pid && app.thread != null &&
3037 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003038 if (!app.killedBackground) {
3039 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3040 + ") has died.");
3041 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08003042 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08003043 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 TAG, "Dying app: " + app + ", pid: " + pid
3045 + ", thread: " + thread.asBinder());
3046 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003047 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048
3049 if (doLowMem) {
3050 // If there are no longer any background processes running,
3051 // and the app that died was not running instrumentation,
3052 // then tell everyone we are now low on memory.
3053 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003054 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3055 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003056 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 haveBg = true;
3058 break;
3059 }
3060 }
3061
3062 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003063 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003064 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003065 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3066 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003067 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003068 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3069 // The low memory report is overriding any current
3070 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003071 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003072 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003073 rec.lastRequestedGc = 0;
3074 } else {
3075 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003077 rec.reportLowMemory = true;
3078 rec.lastLowMemory = now;
3079 mProcessesToGc.remove(rec);
3080 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 }
3082 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003083 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003084 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003087 } else if (app.pid != pid) {
3088 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003089 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003090 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003091 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003092 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003093 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 + thread.asBinder());
3095 }
3096 }
3097
Dan Egnor42471dd2010-01-07 17:25:22 -08003098 /**
3099 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003100 * @param clearTraces causes the dump file to be erased prior to the new
3101 * traces being written, if true; when false, the new traces will be
3102 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003103 * @param firstPids of dalvik VM processes to dump stack traces for first
3104 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003105 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003106 * @return file containing stack traces, or null if no dump file is configured
3107 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003108 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003109 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003110 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3111 if (tracesPath == null || tracesPath.length() == 0) {
3112 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003114
3115 File tracesFile = new File(tracesPath);
3116 try {
3117 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003118 if (!tracesDir.exists()) {
3119 tracesFile.mkdirs();
3120 if (!SELinux.restorecon(tracesDir)) {
3121 return null;
3122 }
3123 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003124 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3125
Christopher Tate6ee412d2010-05-28 12:01:56 -07003126 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003127 tracesFile.createNewFile();
3128 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3129 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003130 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003131 return null;
3132 }
3133
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003134 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003135 return tracesFile;
3136 }
3137
3138 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003139 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003140 // Use a FileObserver to detect when traces finish writing.
3141 // The order of traces is considered important to maintain for legibility.
3142 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3143 public synchronized void onEvent(int event, String path) { notify(); }
3144 };
3145
3146 try {
3147 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003148
3149 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003150 if (firstPids != null) {
3151 try {
3152 int num = firstPids.size();
3153 for (int i = 0; i < num; i++) {
3154 synchronized (observer) {
3155 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3156 observer.wait(200); // Wait for write-close, give up after 200msec
3157 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003158 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003159 } catch (InterruptedException e) {
3160 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003161 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003162 }
3163
3164 // Next measure CPU usage.
3165 if (processStats != null) {
3166 processStats.init();
3167 System.gc();
3168 processStats.update();
3169 try {
3170 synchronized (processStats) {
3171 processStats.wait(500); // measure over 1/2 second.
3172 }
3173 } catch (InterruptedException e) {
3174 }
3175 processStats.update();
3176
3177 // We'll take the stack crawls of just the top apps using CPU.
3178 final int N = processStats.countWorkingStats();
3179 int numProcs = 0;
3180 for (int i=0; i<N && numProcs<5; i++) {
3181 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3182 if (lastPids.indexOfKey(stats.pid) >= 0) {
3183 numProcs++;
3184 try {
3185 synchronized (observer) {
3186 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3187 observer.wait(200); // Wait for write-close, give up after 200msec
3188 }
3189 } catch (InterruptedException e) {
3190 Log.wtf(TAG, e);
3191 }
3192
3193 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003194 }
3195 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003196
Dan Egnor42471dd2010-01-07 17:25:22 -08003197 } finally {
3198 observer.stopWatching();
3199 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003200
3201 if (nativeProcs != null) {
3202 int[] pids = Process.getPidsForCommands(nativeProcs);
3203 if (pids != null) {
3204 for (int pid : pids) {
3205 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3206 }
3207 }
3208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
3210
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003211 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003212 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003213 return;
3214 }
3215 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3216 if (tracesPath == null || tracesPath.length() == 0) {
3217 return;
3218 }
3219
3220 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3221 StrictMode.allowThreadDiskWrites();
3222 try {
3223 final File tracesFile = new File(tracesPath);
3224 final File tracesDir = tracesFile.getParentFile();
3225 final File tracesTmp = new File(tracesDir, "__tmp__");
3226 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003227 if (!tracesDir.exists()) {
3228 tracesFile.mkdirs();
3229 if (!SELinux.restorecon(tracesDir.getPath())) {
3230 return;
3231 }
3232 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003233 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3234
3235 if (tracesFile.exists()) {
3236 tracesTmp.delete();
3237 tracesFile.renameTo(tracesTmp);
3238 }
3239 StringBuilder sb = new StringBuilder();
3240 Time tobj = new Time();
3241 tobj.set(System.currentTimeMillis());
3242 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3243 sb.append(": ");
3244 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3245 sb.append(" since ");
3246 sb.append(msg);
3247 FileOutputStream fos = new FileOutputStream(tracesFile);
3248 fos.write(sb.toString().getBytes());
3249 if (app == null) {
3250 fos.write("\n*** No application process!".getBytes());
3251 }
3252 fos.close();
3253 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3254 } catch (IOException e) {
3255 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3256 return;
3257 }
3258
3259 if (app != null) {
3260 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3261 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003262 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003263 }
3264
3265 File lastTracesFile = null;
3266 File curTracesFile = null;
3267 for (int i=9; i>=0; i--) {
3268 String name = String.format("slow%02d.txt", i);
3269 curTracesFile = new File(tracesDir, name);
3270 if (curTracesFile.exists()) {
3271 if (lastTracesFile != null) {
3272 curTracesFile.renameTo(lastTracesFile);
3273 } else {
3274 curTracesFile.delete();
3275 }
3276 }
3277 lastTracesFile = curTracesFile;
3278 }
3279 tracesFile.renameTo(curTracesFile);
3280 if (tracesTmp.exists()) {
3281 tracesTmp.renameTo(tracesFile);
3282 }
3283 } finally {
3284 StrictMode.setThreadPolicy(oldPolicy);
3285 }
3286 }
3287
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003288 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3289 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003290 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3291 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3292
Dianne Hackborn287952c2010-09-22 22:34:31 -07003293 if (mController != null) {
3294 try {
3295 // 0 == continue, -1 = kill process immediately
3296 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3297 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3298 } catch (RemoteException e) {
3299 mController = null;
3300 }
3301 }
3302
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003303 long anrTime = SystemClock.uptimeMillis();
3304 if (MONITOR_CPU_USAGE) {
3305 updateCpuStatsNow();
3306 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003307
3308 synchronized (this) {
3309 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3310 if (mShuttingDown) {
3311 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3312 return;
3313 } else if (app.notResponding) {
3314 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3315 return;
3316 } else if (app.crashing) {
3317 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3318 return;
3319 }
3320
3321 // In case we come through here for the same app before completing
3322 // this one, mark as anring now so we will bail out.
3323 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003324
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003325 // Log the ANR to the event log.
3326 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3327 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003328
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003329 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003330 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003331
3332 int parentPid = app.pid;
3333 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003334 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003335
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003336 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003337
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003338 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3339 ProcessRecord r = mLruProcesses.get(i);
3340 if (r != null && r.thread != null) {
3341 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003342 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3343 if (r.persistent) {
3344 firstPids.add(pid);
3345 } else {
3346 lastPids.put(pid, Boolean.TRUE);
3347 }
3348 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 }
3351 }
3352
Dan Egnor42471dd2010-01-07 17:25:22 -08003353 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003354 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003355 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003356 info.append("ANR in ").append(app.processName);
3357 if (activity != null && activity.shortComponentName != null) {
3358 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003359 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003360 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003362 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003364 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003365 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367
Dianne Hackborn287952c2010-09-22 22:34:31 -07003368 final ProcessStats processStats = new ProcessStats(true);
3369
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003370 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003371
Dan Egnor42471dd2010-01-07 17:25:22 -08003372 String cpuInfo = null;
3373 if (MONITOR_CPU_USAGE) {
3374 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003375 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003376 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003377 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003378 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003379 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
3381
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003382 info.append(processStats.printCurrentState(anrTime));
3383
Joe Onorato8a9b2202010-02-26 18:56:32 -08003384 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003385 if (tracesFile == null) {
3386 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3387 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3388 }
3389
Jeff Sharkeya353d262011-10-28 11:12:06 -07003390 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3391 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003392
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003393 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003395 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3396 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003398 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3399 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
3401 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003402 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 }
3404 }
3405
Dan Egnor42471dd2010-01-07 17:25:22 -08003406 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3407 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3408 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003409
3410 synchronized (this) {
3411 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003412 Slog.w(TAG, "Killing " + app + ": background ANR");
3413 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3414 app.processName, app.setAdj, "background ANR");
3415 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003416 return;
3417 }
3418
3419 // Set the app's notResponding state, and look up the errorReportReceiver
3420 makeAppNotRespondingLocked(app,
3421 activity != null ? activity.shortComponentName : null,
3422 annotation != null ? "ANR " + annotation : "ANR",
3423 info.toString());
3424
3425 // Bring up the infamous App Not Responding dialog
3426 Message msg = Message.obtain();
3427 HashMap map = new HashMap();
3428 msg.what = SHOW_NOT_RESPONDING_MSG;
3429 msg.obj = map;
3430 map.put("app", app);
3431 if (activity != null) {
3432 map.put("activity", activity);
3433 }
3434
3435 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 }
3438
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003439 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3440 if (!mLaunchWarningShown) {
3441 mLaunchWarningShown = true;
3442 mHandler.post(new Runnable() {
3443 @Override
3444 public void run() {
3445 synchronized (ActivityManagerService.this) {
3446 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3447 d.show();
3448 mHandler.postDelayed(new Runnable() {
3449 @Override
3450 public void run() {
3451 synchronized (ActivityManagerService.this) {
3452 d.dismiss();
3453 mLaunchWarningShown = false;
3454 }
3455 }
3456 }, 4000);
3457 }
3458 }
3459 });
3460 }
3461 }
3462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003464 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003465 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 int uid = Binder.getCallingUid();
3467 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003468 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003469 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 long callingId = Binder.clearCallingIdentity();
3471 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003472 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 int pkgUid = -1;
3474 synchronized(this) {
3475 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003476 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 } catch (RemoteException e) {
3478 }
3479 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003480 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 return false;
3482 }
3483 if (uid == pkgUid || checkComponentPermission(
3484 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003485 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003487 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 } else {
3489 throw new SecurityException(pid+" does not have permission:"+
3490 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3491 "for process:"+packageName);
3492 }
3493 }
3494
3495 try {
3496 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003497 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3499 Uri.fromParts("package", packageName, null));
3500 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003501 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003502 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 } catch (RemoteException e) {
3504 }
3505 } finally {
3506 Binder.restoreCallingIdentity(callingId);
3507 }
3508 return true;
3509 }
3510
Dianne Hackborn1676c852012-09-10 14:52:30 -07003511 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003512 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3513 != PackageManager.PERMISSION_GRANTED &&
3514 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3515 != PackageManager.PERMISSION_GRANTED) {
3516 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 + Binder.getCallingPid()
3518 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003519 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003520 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 throw new SecurityException(msg);
3522 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003523
Dianne Hackborn139748f2012-09-24 11:36:57 -07003524 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003525 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 long callingId = Binder.clearCallingIdentity();
3527 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003528 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003530 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003532 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 } catch (RemoteException e) {
3534 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003535 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003536 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 return;
3538 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003539 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003540 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3541 }
3542 } finally {
3543 Binder.restoreCallingIdentity(callingId);
3544 }
3545 }
3546
3547 public void killAllBackgroundProcesses() {
3548 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3549 != PackageManager.PERMISSION_GRANTED) {
3550 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3551 + Binder.getCallingPid()
3552 + ", uid=" + Binder.getCallingUid()
3553 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3554 Slog.w(TAG, msg);
3555 throw new SecurityException(msg);
3556 }
3557
3558 long callingId = Binder.clearCallingIdentity();
3559 try {
3560 synchronized(this) {
3561 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3562 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3563 final int NA = apps.size();
3564 for (int ia=0; ia<NA; ia++) {
3565 ProcessRecord app = apps.valueAt(ia);
3566 if (app.persistent) {
3567 // we don't kill persistent processes
3568 continue;
3569 }
3570 if (app.removed) {
3571 procs.add(app);
3572 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3573 app.removed = true;
3574 procs.add(app);
3575 }
3576 }
3577 }
3578
3579 int N = procs.size();
3580 for (int i=0; i<N; i++) {
3581 removeProcessLocked(procs.get(i), false, true, "kill all background");
3582 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003583 }
3584 } finally {
3585 Binder.restoreCallingIdentity(callingId);
3586 }
3587 }
3588
Dianne Hackborn1676c852012-09-10 14:52:30 -07003589 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003590 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3591 != PackageManager.PERMISSION_GRANTED) {
3592 String msg = "Permission Denial: forceStopPackage() from pid="
3593 + Binder.getCallingPid()
3594 + ", uid=" + Binder.getCallingUid()
3595 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003596 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003597 throw new SecurityException(msg);
3598 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003599 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003600 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003601 long callingId = Binder.clearCallingIdentity();
3602 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003603 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003604 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003605 int[] users = userId == UserHandle.USER_ALL
3606 ? getUsersLocked() : new int[] { userId };
3607 for (int user : users) {
3608 int pkgUid = -1;
3609 try {
3610 pkgUid = pm.getPackageUid(packageName, user);
3611 } catch (RemoteException e) {
3612 }
3613 if (pkgUid == -1) {
3614 Slog.w(TAG, "Invalid packageName: " + packageName);
3615 continue;
3616 }
3617 try {
3618 pm.setPackageStoppedState(packageName, true, user);
3619 } catch (RemoteException e) {
3620 } catch (IllegalArgumentException e) {
3621 Slog.w(TAG, "Failed trying to unstop package "
3622 + packageName + ": " + e);
3623 }
3624 if (isUserRunningLocked(user)) {
3625 forceStopPackageLocked(packageName, pkgUid);
3626 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 }
3629 } finally {
3630 Binder.restoreCallingIdentity(callingId);
3631 }
3632 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003633
3634 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003635 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003636 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003637 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003638 if (pkg == null) {
3639 return;
3640 }
3641 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003642 if (appid < 0) {
3643 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003644 return;
3645 }
3646 int callerUid = Binder.getCallingUid();
3647 // Only the system server can kill an application
3648 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003649 // Post an aysnc message to kill the application
3650 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003651 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003652 msg.arg2 = 0;
3653 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003654 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003655 } else {
3656 throw new SecurityException(callerUid + " cannot kill pkg: " +
3657 pkg);
3658 }
3659 }
3660
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003661 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003662 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003663
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003664 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003665 final int uid = Binder.getCallingUid();
3666 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003667 try {
3668 synchronized (this) {
3669 // Only allow this from foreground processes, so that background
3670 // applications can't abuse it to prevent system UI from being shown.
3671 if (uid >= Process.FIRST_APPLICATION_UID) {
3672 ProcessRecord proc;
3673 synchronized (mPidsSelfLocked) {
3674 proc = mPidsSelfLocked.get(pid);
3675 }
3676 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3677 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3678 + " from background process " + proc);
3679 return;
3680 }
3681 }
3682 closeSystemDialogsLocked(reason);
3683 }
3684 } finally {
3685 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003686 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003687 }
3688
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003689 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003690 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003691 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003692 if (reason != null) {
3693 intent.putExtra("reason", reason);
3694 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003695 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003696
Dianne Hackborne302a162012-05-15 14:58:32 -07003697 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3698 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003699 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003700 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003701 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003702 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003703 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003704
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003705 broadcastIntentLocked(null, null, intent, null,
3706 null, 0, null, null, null, false, false, -1,
3707 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003708 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003709
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003710 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003711 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003712 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003713 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3714 for (int i=pids.length-1; i>=0; i--) {
3715 infos[i] = new Debug.MemoryInfo();
3716 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003717 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003718 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003719 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003720
Dianne Hackbornb437e092011-08-05 17:50:29 -07003721 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003722 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003723 long[] pss = new long[pids.length];
3724 for (int i=pids.length-1; i>=0; i--) {
3725 pss[i] = Debug.getPss(pids[i]);
3726 }
3727 return pss;
3728 }
3729
Christopher Tate5e1ab332009-09-01 20:32:49 -07003730 public void killApplicationProcess(String processName, int uid) {
3731 if (processName == null) {
3732 return;
3733 }
3734
3735 int callerUid = Binder.getCallingUid();
3736 // Only the system server can kill an application
3737 if (callerUid == Process.SYSTEM_UID) {
3738 synchronized (this) {
3739 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003740 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003741 try {
3742 app.thread.scheduleSuicide();
3743 } catch (RemoteException e) {
3744 // If the other end already died, then our work here is done.
3745 }
3746 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003747 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003748 + processName + " / " + uid);
3749 }
3750 }
3751 } else {
3752 throw new SecurityException(callerUid + " cannot kill app process: " +
3753 processName);
3754 }
3755 }
3756
Dianne Hackborn03abb812010-01-04 18:43:19 -08003757 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003758 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3759 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3761 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003762 if (!mProcessesReady) {
3763 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003766 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 broadcastIntentLocked(null, null, intent,
3768 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003769 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003770 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003772
3773 private void forceStopUserLocked(int userId) {
3774 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3775 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3776 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3777 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3778 broadcastIntentLocked(null, null, intent,
3779 null, null, 0, null, null, null,
3780 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003781 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003782 }
3783
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003784 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003785 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3786 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003787 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788
Dianne Hackborn03abb812010-01-04 18:43:19 -08003789 // Remove all processes this package may have touched: all with the
3790 // same UID (except for the system or root user), and all whose name
3791 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003792 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003793 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3794 final int NA = apps.size();
3795 for (int ia=0; ia<NA; ia++) {
3796 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003797 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003798 // we don't kill persistent processes
3799 continue;
3800 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003801 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003802 if (doit) {
3803 procs.add(app);
3804 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003805 continue;
3806 }
3807
3808 // Skip process if it doesn't meet our oom adj requirement.
3809 if (app.setAdj < minOomAdj) {
3810 continue;
3811 }
3812
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003813 // If no package is specified, we call all processes under the
3814 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003815 if (packageName == null) {
3816 if (app.userId != userId) {
3817 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003818 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003819 // Package has been specified, we want to hit all processes
3820 // that match it. We need to qualify this by the processes
3821 // that are running under the specified app and user ID.
3822 } else {
3823 if (UserHandle.getAppId(app.uid) != appId) {
3824 continue;
3825 }
3826 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3827 continue;
3828 }
3829 if (!app.pkgList.contains(packageName)) {
3830 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003831 }
3832 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003833
3834 // Process has passed all conditions, kill it!
3835 if (!doit) {
3836 return true;
3837 }
3838 app.removed = true;
3839 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003840 }
3841 }
3842
3843 int N = procs.size();
3844 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003845 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003846 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003847 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003848 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003849
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003850 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003851 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003852 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003853 int i;
3854 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003856 if (userId == UserHandle.USER_ALL && name == null) {
3857 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3858 }
3859
3860 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003862 appId = UserHandle.getAppId(
3863 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 } catch (RemoteException e) {
3865 }
3866 }
3867
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003868 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003869 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003870 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3871 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003872 } else {
3873 Slog.i(TAG, "Force stopping user " + userId);
3874 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003875
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003876 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3877 while (badApps.hasNext()) {
3878 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003879 for (i=ba.size()-1; i>=0; i--) {
3880 boolean remove = false;
3881 final int entUid = ba.keyAt(i);
3882 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003883 if (userId == UserHandle.USER_ALL) {
3884 if (UserHandle.getAppId(entUid) == appId) {
3885 remove = true;
3886 }
3887 } else {
3888 if (entUid == UserHandle.getUid(userId, appId)) {
3889 remove = true;
3890 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003891 }
3892 } else if (UserHandle.getUserId(entUid) == userId) {
3893 remove = true;
3894 }
3895 if (remove) {
3896 ba.removeAt(i);
3897 }
3898 }
3899 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003900 badApps.remove();
3901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 }
3903 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003904
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003905 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3906 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003907 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003909 TaskRecord lastTask = null;
3910 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003911 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003912 final boolean samePackage = r.packageName.equals(name)
3913 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003914 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003915 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003916 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003917 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003918 if (r.finishing) {
3919 // If this activity is just finishing, then it is not
3920 // interesting as far as something to stop.
3921 continue;
3922 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003923 return true;
3924 }
3925 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003926 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003927 if (samePackage) {
3928 if (r.app != null) {
3929 r.app.removed = true;
3930 }
3931 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003933 lastTask = r.task;
3934 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003935 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003936 i--;
3937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
3939 }
3940
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003941 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3942 if (!doit) {
3943 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003945 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003947
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003948 if (name == null) {
3949 // Remove all sticky broadcasts from this user.
3950 mStickyBroadcasts.remove(userId);
3951 }
3952
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003953 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003954 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3955 userId, providers)) {
3956 if (!doit) {
3957 return true;
3958 }
3959 didSomething = true;
3960 }
3961 N = providers.size();
3962 for (i=0; i<N; i++) {
3963 removeDyingProviderLocked(null, providers.get(i), true);
3964 }
3965
3966 if (mIntentSenderRecords.size() > 0) {
3967 Iterator<WeakReference<PendingIntentRecord>> it
3968 = mIntentSenderRecords.values().iterator();
3969 while (it.hasNext()) {
3970 WeakReference<PendingIntentRecord> wpir = it.next();
3971 if (wpir == null) {
3972 it.remove();
3973 continue;
3974 }
3975 PendingIntentRecord pir = wpir.get();
3976 if (pir == null) {
3977 it.remove();
3978 continue;
3979 }
3980 if (name == null) {
3981 // Stopping user, remove all objects for the user.
3982 if (pir.key.userId != userId) {
3983 // Not the same user, skip it.
3984 continue;
3985 }
3986 } else {
3987 if (UserHandle.getAppId(pir.uid) != appId) {
3988 // Different app id, skip it.
3989 continue;
3990 }
3991 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3992 // Different user, skip it.
3993 continue;
3994 }
3995 if (!pir.key.packageName.equals(name)) {
3996 // Different package, skip it.
3997 continue;
3998 }
3999 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004000 if (!doit) {
4001 return true;
4002 }
4003 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004004 it.remove();
4005 pir.canceled = true;
4006 if (pir.key.activity != null) {
4007 pir.key.activity.pendingResults.remove(pir.ref);
4008 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004009 }
4010 }
4011
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004012 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004013 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004014 AttributeCache ac = AttributeCache.instance();
4015 if (ac != null) {
4016 ac.removePackage(name);
4017 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004018 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004019 if (mBooted) {
4020 mMainStack.resumeTopActivityLocked(null);
4021 mMainStack.scheduleIdleLocked();
4022 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004023 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004024
4025 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 }
4027
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004028 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004029 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004031 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004032 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004033 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 + "/" + uid + ")");
4035
4036 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004037 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004038 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004039 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4040 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004041 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 boolean needRestart = false;
4044 if (app.pid > 0 && app.pid != MY_PID) {
4045 int pid = app.pid;
4046 synchronized (mPidsSelfLocked) {
4047 mPidsSelfLocked.remove(pid);
4048 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4049 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004050 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004051 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004052 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004053 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004055 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004057 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 } else {
4059 needRestart = true;
4060 }
4061 }
4062 } else {
4063 mRemovedProcesses.add(app);
4064 }
4065
4066 return needRestart;
4067 }
4068
4069 private final void processStartTimedOutLocked(ProcessRecord app) {
4070 final int pid = app.pid;
4071 boolean gone = false;
4072 synchronized (mPidsSelfLocked) {
4073 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4074 if (knownApp != null && knownApp.thread == null) {
4075 mPidsSelfLocked.remove(pid);
4076 gone = true;
4077 }
4078 }
4079
4080 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004081 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004082 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004083 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004084 mProcessNames.remove(app.processName, app.uid);
4085 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004086 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004087 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4088 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004089 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004090 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004091 // Take care of any launching providers waiting for this process.
4092 checkAppInLaunchingProvidersLocked(app, true);
4093 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004094 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004095 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4096 app.processName, app.setAdj, "start timeout");
4097 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004098 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004099 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004100 try {
4101 IBackupManager bm = IBackupManager.Stub.asInterface(
4102 ServiceManager.getService(Context.BACKUP_SERVICE));
4103 bm.agentDisconnected(app.info.packageName);
4104 } catch (RemoteException e) {
4105 // Can't happen; the backup manager is local
4106 }
4107 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004108 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004109 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004110 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004113 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 }
4115 }
4116
4117 private final boolean attachApplicationLocked(IApplicationThread thread,
4118 int pid) {
4119
4120 // Find the application record that is being attached... either via
4121 // the pid if we are running in multiple processes, or just pull the
4122 // next app record if we are emulating process with anonymous threads.
4123 ProcessRecord app;
4124 if (pid != MY_PID && pid >= 0) {
4125 synchronized (mPidsSelfLocked) {
4126 app = mPidsSelfLocked.get(pid);
4127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 } else {
4129 app = null;
4130 }
4131
4132 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004133 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004135 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004137 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 } else {
4139 try {
4140 thread.scheduleExit();
4141 } catch (Exception e) {
4142 // Ignore exceptions.
4143 }
4144 }
4145 return false;
4146 }
4147
4148 // If this application record is still attached to a previous
4149 // process, clean it up now.
4150 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004151 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 }
4153
4154 // Tell the process all about itself.
4155
Joe Onorato8a9b2202010-02-26 18:56:32 -08004156 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 TAG, "Binding process pid " + pid + " to record " + app);
4158
4159 String processName = app.processName;
4160 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004161 AppDeathRecipient adr = new AppDeathRecipient(
4162 app, pid, thread);
4163 thread.asBinder().linkToDeath(adr, 0);
4164 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 } catch (RemoteException e) {
4166 app.resetPackageList();
4167 startProcessLocked(app, "link fail", processName);
4168 return false;
4169 }
4170
Doug Zongker2bec3d42009-12-04 12:52:44 -08004171 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172
4173 app.thread = thread;
4174 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004175 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4176 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 app.forcingToForeground = null;
4178 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004179 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 app.debugging = false;
4181
4182 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4183
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004184 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004185 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004187 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004188 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004189 }
4190
Joe Onorato8a9b2202010-02-26 18:56:32 -08004191 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 TAG, "New app record " + app
4193 + " thread=" + thread.asBinder() + " pid=" + pid);
4194 try {
4195 int testMode = IApplicationThread.DEBUG_OFF;
4196 if (mDebugApp != null && mDebugApp.equals(processName)) {
4197 testMode = mWaitForDebugger
4198 ? IApplicationThread.DEBUG_WAIT
4199 : IApplicationThread.DEBUG_ON;
4200 app.debugging = true;
4201 if (mDebugTransient) {
4202 mDebugApp = mOrigDebugApp;
4203 mWaitForDebugger = mOrigWaitForDebugger;
4204 }
4205 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004206 String profileFile = app.instrumentationProfileFile;
4207 ParcelFileDescriptor profileFd = null;
4208 boolean profileAutoStop = false;
4209 if (mProfileApp != null && mProfileApp.equals(processName)) {
4210 mProfileProc = app;
4211 profileFile = mProfileFile;
4212 profileFd = mProfileFd;
4213 profileAutoStop = mAutoStopProfiler;
4214 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004215 boolean enableOpenGlTrace = false;
4216 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4217 enableOpenGlTrace = true;
4218 mOpenGlTraceApp = null;
4219 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004220
Christopher Tate181fafa2009-05-14 11:12:14 -07004221 // If the app is being launched for restore or full backup, set it up specially
4222 boolean isRestrictedBackupMode = false;
4223 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4224 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004225 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004226 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4227 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004228
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004229 ensurePackageDexOpt(app.instrumentationInfo != null
4230 ? app.instrumentationInfo.packageName
4231 : app.info.packageName);
4232 if (app.instrumentationClass != null) {
4233 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004234 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004235 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004236 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004237 ApplicationInfo appInfo = app.instrumentationInfo != null
4238 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004239 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004240 if (profileFd != null) {
4241 profileFd = profileFd.dup();
4242 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004243 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004244 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004245 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4246 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004247 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004248 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004249 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004250 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 } catch (Exception e) {
4252 // todo: Yikes! What should we do? For now we will try to
4253 // start another process, but that could easily get us in
4254 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004255 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256
4257 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004258 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 startProcessLocked(app, "bind fail", processName);
4260 return false;
4261 }
4262
4263 // Remove this record from the list of starting applications.
4264 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004265 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4266 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 mProcessesOnHold.remove(app);
4268
4269 boolean badApp = false;
4270 boolean didSomething = false;
4271
4272 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004273 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004274 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004275 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 && processName.equals(hr.processName)) {
4277 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004278 if (mHeadless) {
4279 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4280 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 didSomething = true;
4282 }
4283 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004284 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 + hr.intent.getComponent().flattenToShortString(), e);
4286 badApp = true;
4287 }
4288 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004289 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 }
4291 }
4292
4293 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004294 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004296 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 badApp = true;
4299 }
4300 }
4301
Christopher Tatef46723b2012-01-26 14:19:24 -08004302 // Check if a next-broadcast receiver is in this process...
4303 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004305 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004307 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 }
4310 }
4311
Christopher Tate181fafa2009-05-14 11:12:14 -07004312 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004313 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004314 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004315 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004316 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004317 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4318 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4319 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004320 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004321 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004322 e.printStackTrace();
4323 }
4324 }
4325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 if (badApp) {
4327 // todo: Also need to kill application to deal with all
4328 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004329 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 return false;
4331 }
4332
4333 if (!didSomething) {
4334 updateOomAdjLocked();
4335 }
4336
4337 return true;
4338 }
4339
4340 public final void attachApplication(IApplicationThread thread) {
4341 synchronized (this) {
4342 int callingPid = Binder.getCallingPid();
4343 final long origId = Binder.clearCallingIdentity();
4344 attachApplicationLocked(thread, callingPid);
4345 Binder.restoreCallingIdentity(origId);
4346 }
4347 }
4348
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004349 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004351 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4352 if (stopProfiling) {
4353 synchronized (this) {
4354 if (mProfileProc == r.app) {
4355 if (mProfileFd != null) {
4356 try {
4357 mProfileFd.close();
4358 } catch (IOException e) {
4359 }
4360 clearProfilerLocked();
4361 }
4362 }
4363 }
4364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 Binder.restoreCallingIdentity(origId);
4366 }
4367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004369 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004370 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004372
4373 synchronized (this) {
4374 updateEventDispatchingLocked();
4375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 }
4377
Dianne Hackborn661cd522011-08-22 00:26:20 -07004378 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004379 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004380 mWindowManager.showBootMessage(msg, always);
4381 }
4382
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004383 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004384 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004385 final long token = Binder.clearCallingIdentity();
4386 try {
4387 synchronized (this) {
4388 if (mLockScreenShown) {
4389 mLockScreenShown = false;
4390 comeOutOfSleepIfNeededLocked();
4391 }
4392 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004393 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004394 } finally {
4395 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004396 }
4397 }
4398
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004399 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004400 IntentFilter pkgFilter = new IntentFilter();
4401 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4402 pkgFilter.addDataScheme("package");
4403 mContext.registerReceiver(new BroadcastReceiver() {
4404 @Override
4405 public void onReceive(Context context, Intent intent) {
4406 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4407 if (pkgs != null) {
4408 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004409 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004410 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4411 setResultCode(Activity.RESULT_OK);
4412 return;
4413 }
4414 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004415 }
4416 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004417 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004418 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004419
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004420 synchronized (this) {
4421 // Ensure that any processes we had put on hold are now started
4422 // up.
4423 final int NP = mProcessesOnHold.size();
4424 if (NP > 0) {
4425 ArrayList<ProcessRecord> procs =
4426 new ArrayList<ProcessRecord>(mProcessesOnHold);
4427 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004428 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4429 + procs.get(ip));
4430 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004431 }
4432 }
4433
4434 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004435 // Start looking for apps that are abusing wake locks.
4436 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004437 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004438 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004439 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004440 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004441 for (int i=0; i<mStartedUsers.size(); i++) {
4442 UserStartedState uss = mStartedUsers.valueAt(i);
4443 if (uss.mState == UserStartedState.STATE_BOOTING) {
4444 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004445 final int userId = mStartedUsers.keyAt(i);
4446 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4447 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4448 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004449 null, null, 0, null, null,
4450 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004451 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004452 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004453 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004454 }
4455 }
4456 }
4457
4458 final void ensureBootCompleted() {
4459 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004460 boolean enableScreen;
4461 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004462 booting = mBooting;
4463 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004464 enableScreen = !mBooted;
4465 mBooted = true;
4466 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004467
4468 if (booting) {
4469 finishBooting();
4470 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004471
4472 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004473 enableScreenAfterBoot();
4474 }
4475 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004476
4477 public final void activityResumed(IBinder token) {
4478 final long origId = Binder.clearCallingIdentity();
4479 mMainStack.activityResumed(token);
4480 Binder.restoreCallingIdentity(origId);
4481 }
4482
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004483 public final void activityPaused(IBinder token) {
4484 final long origId = Binder.clearCallingIdentity();
4485 mMainStack.activityPaused(token, false);
4486 Binder.restoreCallingIdentity(origId);
4487 }
4488
4489 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4490 CharSequence description) {
4491 if (localLOGV) Slog.v(
4492 TAG, "Activity stopped: token=" + token);
4493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 // Refuse possible leaked file descriptors
4495 if (icicle != null && icicle.hasFileDescriptors()) {
4496 throw new IllegalArgumentException("File descriptors passed in Bundle");
4497 }
4498
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004499 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500
4501 final long origId = Binder.clearCallingIdentity();
4502
4503 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004504 r = mMainStack.isInStackLocked(token);
4505 if (r != null) {
4506 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 }
4508 }
4509
4510 if (r != null) {
4511 sendPendingThumbnail(r, null, null, null, false);
4512 }
4513
4514 trimApplications();
4515
4516 Binder.restoreCallingIdentity(origId);
4517 }
4518
4519 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004520 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004521 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004522 }
4523
4524 public String getCallingPackage(IBinder token) {
4525 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004526 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004527 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 }
4529 }
4530
4531 public ComponentName getCallingActivity(IBinder token) {
4532 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004533 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 return r != null ? r.intent.getComponent() : null;
4535 }
4536 }
4537
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004538 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004539 ActivityRecord r = mMainStack.isInStackLocked(token);
4540 if (r == null) {
4541 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004543 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 }
4545
4546 public ComponentName getActivityClassForToken(IBinder token) {
4547 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004548 ActivityRecord r = mMainStack.isInStackLocked(token);
4549 if (r == null) {
4550 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004552 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 }
4554 }
4555
4556 public String getPackageForToken(IBinder token) {
4557 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004558 ActivityRecord r = mMainStack.isInStackLocked(token);
4559 if (r == null) {
4560 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004562 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 }
4564 }
4565
4566 public IIntentSender getIntentSender(int type,
4567 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004568 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004569 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004570 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004572 if (intents != null) {
4573 if (intents.length < 1) {
4574 throw new IllegalArgumentException("Intents array length must be >= 1");
4575 }
4576 for (int i=0; i<intents.length; i++) {
4577 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004578 if (intent != null) {
4579 if (intent.hasFileDescriptors()) {
4580 throw new IllegalArgumentException("File descriptors passed in Intent");
4581 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004582 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004583 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4584 throw new IllegalArgumentException(
4585 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4586 }
4587 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004588 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004589 }
4590 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004591 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004592 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004593 }
4594 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004595 if (options != null) {
4596 if (options.hasFileDescriptors()) {
4597 throw new IllegalArgumentException("File descriptors passed in options");
4598 }
4599 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601 synchronized(this) {
4602 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004603 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004604 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004605 type == ActivityManager.INTENT_SENDER_BROADCAST, true,
4606 "getIntentSender", null);
4607 if (origUserId == UserHandle.USER_CURRENT) {
4608 // We don't want to evaluate this until the pending intent is
4609 // actually executed. However, we do want to always do the
4610 // security checking for it above.
4611 userId = UserHandle.USER_CURRENT;
4612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004614 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004615 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004616 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4617 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 String msg = "Permission Denial: getIntentSender() from pid="
4619 + Binder.getCallingPid()
4620 + ", uid=" + Binder.getCallingUid()
4621 + ", (need uid=" + uid + ")"
4622 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004623 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 throw new SecurityException(msg);
4625 }
4626 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004627
4628 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004629 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 } catch (RemoteException e) {
4632 throw new SecurityException(e);
4633 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004634 }
4635 }
4636
Dianne Hackborn41203752012-08-31 14:05:51 -07004637 IIntentSender getIntentSenderLocked(int type, String packageName,
4638 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004639 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4640 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004641 if (DEBUG_MU)
4642 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004643 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004644 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004645 activity = mMainStack.isInStackLocked(token);
4646 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004647 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004649 if (activity.finishing) {
4650 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004652 }
4653
4654 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4655 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4656 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4657 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4658 |PendingIntent.FLAG_UPDATE_CURRENT);
4659
4660 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4661 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004662 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004663 WeakReference<PendingIntentRecord> ref;
4664 ref = mIntentSenderRecords.get(key);
4665 PendingIntentRecord rec = ref != null ? ref.get() : null;
4666 if (rec != null) {
4667 if (!cancelCurrent) {
4668 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004669 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004670 rec.key.requestIntent.replaceExtras(intents != null ?
4671 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004672 }
4673 if (intents != null) {
4674 intents[intents.length-1] = rec.key.requestIntent;
4675 rec.key.allIntents = intents;
4676 rec.key.allResolvedTypes = resolvedTypes;
4677 } else {
4678 rec.key.allIntents = null;
4679 rec.key.allResolvedTypes = null;
4680 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 return rec;
4683 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004684 rec.canceled = true;
4685 mIntentSenderRecords.remove(key);
4686 }
4687 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004688 return rec;
4689 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004690 rec = new PendingIntentRecord(this, key, callingUid);
4691 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004692 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004693 if (activity.pendingResults == null) {
4694 activity.pendingResults
4695 = new HashSet<WeakReference<PendingIntentRecord>>();
4696 }
4697 activity.pendingResults.add(rec.ref);
4698 }
4699 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 }
4701
4702 public void cancelIntentSender(IIntentSender sender) {
4703 if (!(sender instanceof PendingIntentRecord)) {
4704 return;
4705 }
4706 synchronized(this) {
4707 PendingIntentRecord rec = (PendingIntentRecord)sender;
4708 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004709 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004710 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4711 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 String msg = "Permission Denial: cancelIntentSender() from pid="
4713 + Binder.getCallingPid()
4714 + ", uid=" + Binder.getCallingUid()
4715 + " is not allowed to cancel packges "
4716 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004717 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 throw new SecurityException(msg);
4719 }
4720 } catch (RemoteException e) {
4721 throw new SecurityException(e);
4722 }
4723 cancelIntentSenderLocked(rec, true);
4724 }
4725 }
4726
4727 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4728 rec.canceled = true;
4729 mIntentSenderRecords.remove(rec.key);
4730 if (cleanActivity && rec.key.activity != null) {
4731 rec.key.activity.pendingResults.remove(rec.ref);
4732 }
4733 }
4734
4735 public String getPackageForIntentSender(IIntentSender pendingResult) {
4736 if (!(pendingResult instanceof PendingIntentRecord)) {
4737 return null;
4738 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004739 try {
4740 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4741 return res.key.packageName;
4742 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 }
4744 return null;
4745 }
4746
Christopher Tatec4a07d12012-04-06 14:19:13 -07004747 public int getUidForIntentSender(IIntentSender sender) {
4748 if (sender instanceof PendingIntentRecord) {
4749 try {
4750 PendingIntentRecord res = (PendingIntentRecord)sender;
4751 return res.uid;
4752 } catch (ClassCastException e) {
4753 }
4754 }
4755 return -1;
4756 }
4757
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004758 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4759 if (!(pendingResult instanceof PendingIntentRecord)) {
4760 return false;
4761 }
4762 try {
4763 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4764 if (res.key.allIntents == null) {
4765 return false;
4766 }
4767 for (int i=0; i<res.key.allIntents.length; i++) {
4768 Intent intent = res.key.allIntents[i];
4769 if (intent.getPackage() != null && intent.getComponent() != null) {
4770 return false;
4771 }
4772 }
4773 return true;
4774 } catch (ClassCastException e) {
4775 }
4776 return false;
4777 }
4778
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004779 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4780 if (!(pendingResult instanceof PendingIntentRecord)) {
4781 return false;
4782 }
4783 try {
4784 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4785 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4786 return true;
4787 }
4788 return false;
4789 } catch (ClassCastException e) {
4790 }
4791 return false;
4792 }
4793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 public void setProcessLimit(int max) {
4795 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4796 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004797 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004798 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004799 mProcessLimitOverride = max;
4800 }
4801 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 }
4803
4804 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004805 synchronized (this) {
4806 return mProcessLimitOverride;
4807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 }
4809
4810 void foregroundTokenDied(ForegroundToken token) {
4811 synchronized (ActivityManagerService.this) {
4812 synchronized (mPidsSelfLocked) {
4813 ForegroundToken cur
4814 = mForegroundProcesses.get(token.pid);
4815 if (cur != token) {
4816 return;
4817 }
4818 mForegroundProcesses.remove(token.pid);
4819 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4820 if (pr == null) {
4821 return;
4822 }
4823 pr.forcingToForeground = null;
4824 pr.foregroundServices = false;
4825 }
4826 updateOomAdjLocked();
4827 }
4828 }
4829
4830 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4831 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4832 "setProcessForeground()");
4833 synchronized(this) {
4834 boolean changed = false;
4835
4836 synchronized (mPidsSelfLocked) {
4837 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004838 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004839 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 return;
4841 }
4842 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4843 if (oldToken != null) {
4844 oldToken.token.unlinkToDeath(oldToken, 0);
4845 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004846 if (pr != null) {
4847 pr.forcingToForeground = null;
4848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004849 changed = true;
4850 }
4851 if (isForeground && token != null) {
4852 ForegroundToken newToken = new ForegroundToken() {
4853 public void binderDied() {
4854 foregroundTokenDied(this);
4855 }
4856 };
4857 newToken.pid = pid;
4858 newToken.token = token;
4859 try {
4860 token.linkToDeath(newToken, 0);
4861 mForegroundProcesses.put(pid, newToken);
4862 pr.forcingToForeground = token;
4863 changed = true;
4864 } catch (RemoteException e) {
4865 // If the process died while doing this, we will later
4866 // do the cleanup with the process death link.
4867 }
4868 }
4869 }
4870
4871 if (changed) {
4872 updateOomAdjLocked();
4873 }
4874 }
4875 }
4876
4877 // =========================================================
4878 // PERMISSIONS
4879 // =========================================================
4880
4881 static class PermissionController extends IPermissionController.Stub {
4882 ActivityManagerService mActivityManagerService;
4883 PermissionController(ActivityManagerService activityManagerService) {
4884 mActivityManagerService = activityManagerService;
4885 }
4886
4887 public boolean checkPermission(String permission, int pid, int uid) {
4888 return mActivityManagerService.checkPermission(permission, pid,
4889 uid) == PackageManager.PERMISSION_GRANTED;
4890 }
4891 }
4892
4893 /**
4894 * This can be called with or without the global lock held.
4895 */
4896 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004897 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004898 // We might be performing an operation on behalf of an indirect binder
4899 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4900 // client identity accordingly before proceeding.
4901 Identity tlsIdentity = sCallerIdentity.get();
4902 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004903 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4905 uid = tlsIdentity.uid;
4906 pid = tlsIdentity.pid;
4907 }
4908
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004909 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 return PackageManager.PERMISSION_GRANTED;
4911 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004912
4913 return ActivityManager.checkComponentPermission(permission, uid,
4914 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 }
4916
4917 /**
4918 * As the only public entry point for permissions checking, this method
4919 * can enforce the semantic that requesting a check on a null global
4920 * permission is automatically denied. (Internally a null permission
4921 * string is used when calling {@link #checkComponentPermission} in cases
4922 * when only uid-based security is needed.)
4923 *
4924 * This can be called with or without the global lock held.
4925 */
4926 public int checkPermission(String permission, int pid, int uid) {
4927 if (permission == null) {
4928 return PackageManager.PERMISSION_DENIED;
4929 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004930 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 }
4932
4933 /**
4934 * Binder IPC calls go through the public entry point.
4935 * This can be called with or without the global lock held.
4936 */
4937 int checkCallingPermission(String permission) {
4938 return checkPermission(permission,
4939 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004940 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 }
4942
4943 /**
4944 * This can be called with or without the global lock held.
4945 */
4946 void enforceCallingPermission(String permission, String func) {
4947 if (checkCallingPermission(permission)
4948 == PackageManager.PERMISSION_GRANTED) {
4949 return;
4950 }
4951
4952 String msg = "Permission Denial: " + func + " from pid="
4953 + Binder.getCallingPid()
4954 + ", uid=" + Binder.getCallingUid()
4955 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004956 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 throw new SecurityException(msg);
4958 }
4959
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004960 /**
4961 * Determine if UID is holding permissions required to access {@link Uri} in
4962 * the given {@link ProviderInfo}. Final permission checking is always done
4963 * in {@link ContentProvider}.
4964 */
4965 private final boolean checkHoldingPermissionsLocked(
4966 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004967 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4968 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004969
4970 if (pi.applicationInfo.uid == uid) {
4971 return true;
4972 } else if (!pi.exported) {
4973 return false;
4974 }
4975
4976 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4977 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004979 // check if target holds top-level <provider> permissions
4980 if (!readMet && pi.readPermission != null
4981 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4982 readMet = true;
4983 }
4984 if (!writeMet && pi.writePermission != null
4985 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4986 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004987 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004988
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004989 // track if unprotected read/write is allowed; any denied
4990 // <path-permission> below removes this ability
4991 boolean allowDefaultRead = pi.readPermission == null;
4992 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004993
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004994 // check if target holds any <path-permission> that match uri
4995 final PathPermission[] pps = pi.pathPermissions;
4996 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004997 final String path = uri.getPath();
4998 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004999 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005000 i--;
5001 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005002 if (pp.match(path)) {
5003 if (!readMet) {
5004 final String pprperm = pp.getReadPermission();
5005 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5006 + pprperm + " for " + pp.getPath()
5007 + ": match=" + pp.match(path)
5008 + " check=" + pm.checkUidPermission(pprperm, uid));
5009 if (pprperm != null) {
5010 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5011 readMet = true;
5012 } else {
5013 allowDefaultRead = false;
5014 }
5015 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005016 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005017 if (!writeMet) {
5018 final String ppwperm = pp.getWritePermission();
5019 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5020 + ppwperm + " for " + pp.getPath()
5021 + ": match=" + pp.match(path)
5022 + " check=" + pm.checkUidPermission(ppwperm, uid));
5023 if (ppwperm != null) {
5024 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5025 writeMet = true;
5026 } else {
5027 allowDefaultWrite = false;
5028 }
5029 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005030 }
5031 }
5032 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005033 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005034
5035 // grant unprotected <provider> read/write, if not blocked by
5036 // <path-permission> above
5037 if (allowDefaultRead) readMet = true;
5038 if (allowDefaultWrite) writeMet = true;
5039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005040 } catch (RemoteException e) {
5041 return false;
5042 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005043
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005044 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 }
5046
5047 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5048 int modeFlags) {
5049 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005050 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 return true;
5052 }
5053 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5054 if (perms == null) return false;
5055 UriPermission perm = perms.get(uri);
5056 if (perm == null) return false;
5057 return (modeFlags&perm.modeFlags) == modeFlags;
5058 }
5059
5060 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005061 enforceNotIsolatedCaller("checkUriPermission");
5062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 // Another redirected-binder-call permissions check as in
5064 // {@link checkComponentPermission}.
5065 Identity tlsIdentity = sCallerIdentity.get();
5066 if (tlsIdentity != null) {
5067 uid = tlsIdentity.uid;
5068 pid = tlsIdentity.pid;
5069 }
5070
5071 // Our own process gets to do everything.
5072 if (pid == MY_PID) {
5073 return PackageManager.PERMISSION_GRANTED;
5074 }
5075 synchronized(this) {
5076 return checkUriPermissionLocked(uri, uid, modeFlags)
5077 ? PackageManager.PERMISSION_GRANTED
5078 : PackageManager.PERMISSION_DENIED;
5079 }
5080 }
5081
Dianne Hackborn39792d22010-08-19 18:01:52 -07005082 /**
5083 * Check if the targetPkg can be granted permission to access uri by
5084 * the callingUid using the given modeFlags. Throws a security exception
5085 * if callingUid is not allowed to do this. Returns the uid of the target
5086 * if the URI permission grant should be performed; returns -1 if it is not
5087 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005088 * If you already know the uid of the target, you can supply it in
5089 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005090 */
5091 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005092 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5094 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5095 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005096 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 }
5098
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005099 if (targetPkg != null) {
5100 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5101 "Checking grant " + targetPkg + " permission to " + uri);
5102 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005103
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005104 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105
5106 // If this is not a content: uri, we can't do anything with it.
5107 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005108 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005109 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005110 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 }
5112
5113 String name = uri.getAuthority();
5114 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005115 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005116 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 if (cpr != null) {
5118 pi = cpr.info;
5119 } else {
5120 try {
5121 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005122 PackageManager.GET_URI_PERMISSION_PATTERNS,
5123 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 } catch (RemoteException ex) {
5125 }
5126 }
5127 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005128 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005129 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 }
5131
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005132 int targetUid = lastTargetUid;
5133 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005134 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005135 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005136 if (targetUid < 0) {
5137 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5138 "Can't grant URI permission no uid for: " + targetPkg);
5139 return -1;
5140 }
5141 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005142 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005146 if (targetUid >= 0) {
5147 // First... does the target actually need this permission?
5148 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5149 // No need to grant the target this permission.
5150 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5151 "Target " + targetPkg + " already has full permission to " + uri);
5152 return -1;
5153 }
5154 } else {
5155 // First... there is no target package, so can anyone access it?
5156 boolean allowed = pi.exported;
5157 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5158 if (pi.readPermission != null) {
5159 allowed = false;
5160 }
5161 }
5162 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5163 if (pi.writePermission != null) {
5164 allowed = false;
5165 }
5166 }
5167 if (allowed) {
5168 return -1;
5169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170 }
5171
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005172 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 if (!pi.grantUriPermissions) {
5174 throw new SecurityException("Provider " + pi.packageName
5175 + "/" + pi.name
5176 + " does not allow granting of Uri permissions (uri "
5177 + uri + ")");
5178 }
5179 if (pi.uriPermissionPatterns != null) {
5180 final int N = pi.uriPermissionPatterns.length;
5181 boolean allowed = false;
5182 for (int i=0; i<N; i++) {
5183 if (pi.uriPermissionPatterns[i] != null
5184 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5185 allowed = true;
5186 break;
5187 }
5188 }
5189 if (!allowed) {
5190 throw new SecurityException("Provider " + pi.packageName
5191 + "/" + pi.name
5192 + " does not allow granting of permission to path of Uri "
5193 + uri);
5194 }
5195 }
5196
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005197 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005199 if (callingUid != Process.myUid()) {
5200 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5201 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5202 throw new SecurityException("Uid " + callingUid
5203 + " does not have permission to uri " + uri);
5204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 }
5206 }
5207
Dianne Hackborn39792d22010-08-19 18:01:52 -07005208 return targetUid;
5209 }
5210
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005211 public int checkGrantUriPermission(int callingUid, String targetPkg,
5212 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005213 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005214 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005215 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005216 }
5217 }
5218
Dianne Hackborn39792d22010-08-19 18:01:52 -07005219 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5220 Uri uri, int modeFlags, UriPermissionOwner owner) {
5221 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5222 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5223 if (modeFlags == 0) {
5224 return;
5225 }
5226
5227 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 // to the uri, and the target doesn't. Let's now give this to
5229 // the target.
5230
Joe Onorato8a9b2202010-02-26 18:56:32 -08005231 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005232 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 HashMap<Uri, UriPermission> targetUris
5235 = mGrantedUriPermissions.get(targetUid);
5236 if (targetUris == null) {
5237 targetUris = new HashMap<Uri, UriPermission>();
5238 mGrantedUriPermissions.put(targetUid, targetUris);
5239 }
5240
5241 UriPermission perm = targetUris.get(uri);
5242 if (perm == null) {
5243 perm = new UriPermission(targetUid, uri);
5244 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005247 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005248 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005250 } else {
5251 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5252 perm.readOwners.add(owner);
5253 owner.addReadPermission(perm);
5254 }
5255 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5256 perm.writeOwners.add(owner);
5257 owner.addWritePermission(perm);
5258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005259 }
5260 }
5261
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005262 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5263 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005264 if (targetPkg == null) {
5265 throw new NullPointerException("targetPkg");
5266 }
5267
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005268 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005269 if (targetUid < 0) {
5270 return;
5271 }
5272
5273 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5274 }
5275
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005276 static class NeededUriGrants extends ArrayList<Uri> {
5277 final String targetPkg;
5278 final int targetUid;
5279 final int flags;
5280
5281 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5282 targetPkg = _targetPkg;
5283 targetUid = _targetUid;
5284 flags = _flags;
5285 }
5286 }
5287
Dianne Hackborn39792d22010-08-19 18:01:52 -07005288 /**
5289 * Like checkGrantUriPermissionLocked, but takes an Intent.
5290 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005291 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5292 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005293 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005294 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5295 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005296 + " from " + intent + "; flags=0x"
5297 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5298
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005299 if (targetPkg == null) {
5300 throw new NullPointerException("targetPkg");
5301 }
5302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005304 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 }
5306 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005307 ClipData clip = intent.getClipData();
5308 if (data == null && clip == null) {
5309 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005310 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005311 if (data != null) {
5312 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5313 mode, needed != null ? needed.targetUid : -1);
5314 if (target > 0) {
5315 if (needed == null) {
5316 needed = new NeededUriGrants(targetPkg, target, mode);
5317 }
5318 needed.add(data);
5319 }
5320 }
5321 if (clip != null) {
5322 for (int i=0; i<clip.getItemCount(); i++) {
5323 Uri uri = clip.getItemAt(i).getUri();
5324 if (uri != null) {
5325 int target = -1;
5326 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5327 mode, needed != null ? needed.targetUid : -1);
5328 if (target > 0) {
5329 if (needed == null) {
5330 needed = new NeededUriGrants(targetPkg, target, mode);
5331 }
5332 needed.add(uri);
5333 }
5334 } else {
5335 Intent clipIntent = clip.getItemAt(i).getIntent();
5336 if (clipIntent != null) {
5337 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5338 callingUid, targetPkg, clipIntent, mode, needed);
5339 if (newNeeded != null) {
5340 needed = newNeeded;
5341 }
5342 }
5343 }
5344 }
5345 }
5346
5347 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005348 }
5349
5350 /**
5351 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5352 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005353 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5354 UriPermissionOwner owner) {
5355 if (needed != null) {
5356 for (int i=0; i<needed.size(); i++) {
5357 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5358 needed.get(i), needed.flags, owner);
5359 }
5360 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005361 }
5362
5363 void grantUriPermissionFromIntentLocked(int callingUid,
5364 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005365 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005366 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005367 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 return;
5369 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005370
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005371 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 }
5373
5374 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5375 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005376 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 synchronized(this) {
5378 final ProcessRecord r = getRecordForAppLocked(caller);
5379 if (r == null) {
5380 throw new SecurityException("Unable to find app for caller "
5381 + caller
5382 + " when granting permission to uri " + uri);
5383 }
5384 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005385 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 }
5387 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005388 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 }
5390
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005391 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 null);
5393 }
5394 }
5395
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005396 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5398 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5399 HashMap<Uri, UriPermission> perms
5400 = mGrantedUriPermissions.get(perm.uid);
5401 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005402 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005403 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 perms.remove(perm.uri);
5405 if (perms.size() == 0) {
5406 mGrantedUriPermissions.remove(perm.uid);
5407 }
5408 }
5409 }
5410 }
5411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5413 int modeFlags) {
5414 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5415 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5416 if (modeFlags == 0) {
5417 return;
5418 }
5419
Joe Onorato8a9b2202010-02-26 18:56:32 -08005420 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005421 "Revoking all granted permissions to " + uri);
5422
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005423 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424
5425 final String authority = uri.getAuthority();
5426 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005427 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005428 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 if (cpr != null) {
5430 pi = cpr.info;
5431 } else {
5432 try {
5433 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005434 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 } catch (RemoteException ex) {
5436 }
5437 }
5438 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005439 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 return;
5441 }
5442
5443 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005444 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 // Right now, if you are not the original owner of the permission,
5446 // you are not allowed to revoke it.
5447 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5448 throw new SecurityException("Uid " + callingUid
5449 + " does not have permission to uri " + uri);
5450 //}
5451 }
5452
5453 // Go through all of the permissions and remove any that match.
5454 final List<String> SEGMENTS = uri.getPathSegments();
5455 if (SEGMENTS != null) {
5456 final int NS = SEGMENTS.size();
5457 int N = mGrantedUriPermissions.size();
5458 for (int i=0; i<N; i++) {
5459 HashMap<Uri, UriPermission> perms
5460 = mGrantedUriPermissions.valueAt(i);
5461 Iterator<UriPermission> it = perms.values().iterator();
5462 toploop:
5463 while (it.hasNext()) {
5464 UriPermission perm = it.next();
5465 Uri targetUri = perm.uri;
5466 if (!authority.equals(targetUri.getAuthority())) {
5467 continue;
5468 }
5469 List<String> targetSegments = targetUri.getPathSegments();
5470 if (targetSegments == null) {
5471 continue;
5472 }
5473 if (targetSegments.size() < NS) {
5474 continue;
5475 }
5476 for (int j=0; j<NS; j++) {
5477 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5478 continue toploop;
5479 }
5480 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005481 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005482 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 perm.clearModes(modeFlags);
5484 if (perm.modeFlags == 0) {
5485 it.remove();
5486 }
5487 }
5488 if (perms.size() == 0) {
5489 mGrantedUriPermissions.remove(
5490 mGrantedUriPermissions.keyAt(i));
5491 N--;
5492 i--;
5493 }
5494 }
5495 }
5496 }
5497
5498 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5499 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005500 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 synchronized(this) {
5502 final ProcessRecord r = getRecordForAppLocked(caller);
5503 if (r == null) {
5504 throw new SecurityException("Unable to find app for caller "
5505 + caller
5506 + " when revoking permission to uri " + uri);
5507 }
5508 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005509 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 return;
5511 }
5512
5513 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5514 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5515 if (modeFlags == 0) {
5516 return;
5517 }
5518
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005519 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520
5521 final String authority = uri.getAuthority();
5522 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005523 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 if (cpr != null) {
5525 pi = cpr.info;
5526 } else {
5527 try {
5528 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005529 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 } catch (RemoteException ex) {
5531 }
5532 }
5533 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005534 Slog.w(TAG, "No content provider found for permission revoke: "
5535 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 return;
5537 }
5538
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005539 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 }
5541 }
5542
Dianne Hackborn7e269642010-08-25 19:50:20 -07005543 @Override
5544 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005545 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005546 synchronized(this) {
5547 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5548 return owner.getExternalTokenLocked();
5549 }
5550 }
5551
5552 @Override
5553 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5554 Uri uri, int modeFlags) {
5555 synchronized(this) {
5556 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5557 if (owner == null) {
5558 throw new IllegalArgumentException("Unknown owner: " + token);
5559 }
5560 if (fromUid != Binder.getCallingUid()) {
5561 if (Binder.getCallingUid() != Process.myUid()) {
5562 // Only system code can grant URI permissions on behalf
5563 // of other users.
5564 throw new SecurityException("nice try");
5565 }
5566 }
5567 if (targetPkg == null) {
5568 throw new IllegalArgumentException("null target");
5569 }
5570 if (uri == null) {
5571 throw new IllegalArgumentException("null uri");
5572 }
5573
5574 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5575 }
5576 }
5577
5578 @Override
5579 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5580 synchronized(this) {
5581 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5582 if (owner == null) {
5583 throw new IllegalArgumentException("Unknown owner: " + token);
5584 }
5585
5586 if (uri == null) {
5587 owner.removeUriPermissionsLocked(mode);
5588 } else {
5589 owner.removeUriPermissionLocked(uri, mode);
5590 }
5591 }
5592 }
5593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5595 synchronized (this) {
5596 ProcessRecord app =
5597 who != null ? getRecordForAppLocked(who) : null;
5598 if (app == null) return;
5599
5600 Message msg = Message.obtain();
5601 msg.what = WAIT_FOR_DEBUGGER_MSG;
5602 msg.obj = app;
5603 msg.arg1 = waiting ? 1 : 0;
5604 mHandler.sendMessage(msg);
5605 }
5606 }
5607
5608 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005609 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5610 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005612 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005613 outInfo.threshold = homeAppMem;
5614 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5615 outInfo.hiddenAppThreshold = hiddenAppMem;
5616 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005617 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005618 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5619 ProcessList.VISIBLE_APP_ADJ);
5620 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5621 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 }
5623
5624 // =========================================================
5625 // TASK MANAGEMENT
5626 // =========================================================
5627
5628 public List getTasks(int maxNum, int flags,
5629 IThumbnailReceiver receiver) {
5630 ArrayList list = new ArrayList();
5631
5632 PendingThumbnailsRecord pending = null;
5633 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005634 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635
5636 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005637 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5639 + ", receiver=" + receiver);
5640
5641 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5642 != PackageManager.PERMISSION_GRANTED) {
5643 if (receiver != null) {
5644 // If the caller wants to wait for pending thumbnails,
5645 // it ain't gonna get them.
5646 try {
5647 receiver.finished();
5648 } catch (RemoteException ex) {
5649 }
5650 }
5651 String msg = "Permission Denial: getTasks() from pid="
5652 + Binder.getCallingPid()
5653 + ", uid=" + Binder.getCallingUid()
5654 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005655 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 throw new SecurityException(msg);
5657 }
5658
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005659 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005660 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005661 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005662 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 TaskRecord curTask = null;
5664 int numActivities = 0;
5665 int numRunning = 0;
5666 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005667 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005669 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670
5671 // Initialize state for next task if needed.
5672 if (top == null ||
5673 (top.state == ActivityState.INITIALIZING
5674 && top.task == r.task)) {
5675 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 curTask = r.task;
5677 numActivities = numRunning = 0;
5678 }
5679
5680 // Add 'r' into the current task.
5681 numActivities++;
5682 if (r.app != null && r.app.thread != null) {
5683 numRunning++;
5684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685
Joe Onorato8a9b2202010-02-26 18:56:32 -08005686 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 TAG, r.intent.getComponent().flattenToShortString()
5688 + ": task=" + r.task);
5689
5690 // If the next one is a different task, generate a new
5691 // TaskInfo entry for what we have.
5692 if (next == null || next.task != curTask) {
5693 ActivityManager.RunningTaskInfo ci
5694 = new ActivityManager.RunningTaskInfo();
5695 ci.id = curTask.taskId;
5696 ci.baseActivity = r.intent.getComponent();
5697 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005698 if (top.thumbHolder != null) {
5699 ci.description = top.thumbHolder.lastDescription;
5700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 ci.numActivities = numActivities;
5702 ci.numRunning = numRunning;
5703 //System.out.println(
5704 // "#" + maxNum + ": " + " descr=" + ci.description);
5705 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005706 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 TAG, "State=" + top.state + "Idle=" + top.idle
5708 + " app=" + top.app
5709 + " thr=" + (top.app != null ? top.app.thread : null));
5710 if (top.state == ActivityState.RESUMED
5711 || top.state == ActivityState.PAUSING) {
5712 if (top.idle && top.app != null
5713 && top.app.thread != null) {
5714 topRecord = top;
5715 topThumbnail = top.app.thread;
5716 } else {
5717 top.thumbnailNeeded = true;
5718 }
5719 }
5720 if (pending == null) {
5721 pending = new PendingThumbnailsRecord(receiver);
5722 }
5723 pending.pendingRecords.add(top);
5724 }
5725 list.add(ci);
5726 maxNum--;
5727 top = null;
5728 }
5729 }
5730
5731 if (pending != null) {
5732 mPendingThumbnails.add(pending);
5733 }
5734 }
5735
Joe Onorato8a9b2202010-02-26 18:56:32 -08005736 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737
5738 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005739 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005741 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005743 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005744 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 }
5746 }
5747
5748 if (pending == null && receiver != null) {
5749 // In this case all thumbnails were available and the client
5750 // is being asked to be told when the remaining ones come in...
5751 // which is unusually, since the top-most currently running
5752 // activity should never have a canned thumbnail! Oh well.
5753 try {
5754 receiver.finished();
5755 } catch (RemoteException ex) {
5756 }
5757 }
5758
5759 return list;
5760 }
5761
5762 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005763 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005764 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5765 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 synchronized (this) {
5768 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5769 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005770 final boolean detailed = checkCallingPermission(
5771 android.Manifest.permission.GET_DETAILED_TASKS)
5772 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005774 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 final int N = mRecentTasks.size();
5777 ArrayList<ActivityManager.RecentTaskInfo> res
5778 = new ArrayList<ActivityManager.RecentTaskInfo>(
5779 maxNum < N ? maxNum : N);
5780 for (int i=0; i<N && maxNum > 0; i++) {
5781 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005782 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005783 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005784 // Return the entry if desired by the caller. We always return
5785 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005786 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005787 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5788 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005789
Dianne Hackborn905577f2011-09-07 18:31:28 -07005790 if (i == 0
5791 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 || (tr.intent == null)
5793 || ((tr.intent.getFlags()
5794 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5795 ActivityManager.RecentTaskInfo rti
5796 = new ActivityManager.RecentTaskInfo();
5797 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005798 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 rti.baseIntent = new Intent(
5800 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005801 if (!detailed) {
5802 rti.baseIntent.replaceExtras((Bundle)null);
5803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005805 rti.description = tr.lastDescription;
5806
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005807 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5808 // Check whether this activity is currently available.
5809 try {
5810 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005811 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005812 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005813 continue;
5814 }
5815 } else if (rti.baseIntent != null) {
5816 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005817 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005818 continue;
5819 }
5820 }
5821 } catch (RemoteException e) {
5822 // Will never happen.
5823 }
5824 }
5825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 res.add(rti);
5827 maxNum--;
5828 }
5829 }
5830 return res;
5831 }
5832 }
5833
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005834 private TaskRecord taskForIdLocked(int id) {
5835 final int N = mRecentTasks.size();
5836 for (int i=0; i<N; i++) {
5837 TaskRecord tr = mRecentTasks.get(i);
5838 if (tr.taskId == id) {
5839 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005840 }
5841 }
5842 return null;
5843 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005844
5845 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5846 synchronized (this) {
5847 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5848 "getTaskThumbnails()");
5849 TaskRecord tr = taskForIdLocked(id);
5850 if (tr != null) {
5851 return mMainStack.getTaskThumbnailsLocked(tr);
5852 }
5853 }
5854 return null;
5855 }
5856
Dianne Hackborn15491c62012-09-19 10:59:14 -07005857 public Bitmap getTaskTopThumbnail(int id) {
5858 synchronized (this) {
5859 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5860 "getTaskTopThumbnail()");
5861 TaskRecord tr = taskForIdLocked(id);
5862 if (tr != null) {
5863 return mMainStack.getTaskTopThumbnailLocked(tr);
5864 }
5865 }
5866 return null;
5867 }
5868
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005869 public boolean removeSubTask(int taskId, int subTaskIndex) {
5870 synchronized (this) {
5871 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5872 "removeSubTask()");
5873 long ident = Binder.clearCallingIdentity();
5874 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005875 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5876 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005877 } finally {
5878 Binder.restoreCallingIdentity(ident);
5879 }
5880 }
5881 }
5882
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005883 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5884 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005885 Intent baseIntent = new Intent(
5886 tr.intent != null ? tr.intent : tr.affinityIntent);
5887 ComponentName component = baseIntent.getComponent();
5888 if (component == null) {
5889 Slog.w(TAG, "Now component for base intent of task: " + tr);
5890 return;
5891 }
5892
5893 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005894 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005895
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005896 if (killProcesses) {
5897 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005898 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005899 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005900 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5901 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5902 for (int i=0; i<uids.size(); i++) {
5903 ProcessRecord proc = uids.valueAt(i);
5904 if (proc.userId != tr.userId) {
5905 continue;
5906 }
5907 if (!proc.pkgList.contains(pkg)) {
5908 continue;
5909 }
5910 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005911 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005912 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005913
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005914 // Kill the running processes.
5915 for (int i=0; i<procs.size(); i++) {
5916 ProcessRecord pr = procs.get(i);
5917 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5918 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5919 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5920 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005921 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005922 Process.killProcessQuiet(pr.pid);
5923 } else {
5924 pr.waitingToKill = "remove task";
5925 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005926 }
5927 }
5928 }
5929
5930 public boolean removeTask(int taskId, int flags) {
5931 synchronized (this) {
5932 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5933 "removeTask()");
5934 long ident = Binder.clearCallingIdentity();
5935 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005936 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5937 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005938 if (r != null) {
5939 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005940 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005941 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005942 } else {
5943 TaskRecord tr = null;
5944 int i=0;
5945 while (i < mRecentTasks.size()) {
5946 TaskRecord t = mRecentTasks.get(i);
5947 if (t.taskId == taskId) {
5948 tr = t;
5949 break;
5950 }
5951 i++;
5952 }
5953 if (tr != null) {
5954 if (tr.numActivities <= 0) {
5955 // Caller is just removing a recent task that is
5956 // not actively running. That is easy!
5957 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005958 cleanUpRemovedTaskLocked(tr, flags);
5959 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005960 } else {
5961 Slog.w(TAG, "removeTask: task " + taskId
5962 + " does not have activities to remove, "
5963 + " but numActivities=" + tr.numActivities
5964 + ": " + tr);
5965 }
5966 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005967 }
5968 } finally {
5969 Binder.restoreCallingIdentity(ident);
5970 }
5971 }
5972 return false;
5973 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5976 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005977 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 TaskRecord jt = startTask;
5979
5980 // First look backwards
5981 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005982 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 if (r.task != jt) {
5984 jt = r.task;
5985 if (affinity.equals(jt.affinity)) {
5986 return j;
5987 }
5988 }
5989 }
5990
5991 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005992 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 jt = startTask;
5994 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005995 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 if (r.task != jt) {
5997 if (affinity.equals(jt.affinity)) {
5998 return j;
5999 }
6000 jt = r.task;
6001 }
6002 }
6003
6004 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006005 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 return N-1;
6007 }
6008
6009 return -1;
6010 }
6011
6012 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006013 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006015 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6017 "moveTaskToFront()");
6018
6019 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006020 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6021 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006022 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006023 return;
6024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 final long origId = Binder.clearCallingIdentity();
6026 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006027 TaskRecord tr = taskForIdLocked(task);
6028 if (tr != null) {
6029 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6030 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006032 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6033 // Caller wants the home activity moved with it. To accomplish this,
6034 // we'll just move the home task to the top first.
6035 mMainStack.moveHomeToFrontLocked();
6036 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006037 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006038 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006040 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6041 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006043 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6044 mMainStack.mUserLeaving = true;
6045 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006046 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6047 // Caller wants the home activity moved with it. To accomplish this,
6048 // we'll just move the home task to the top first.
6049 mMainStack.moveHomeToFrontLocked();
6050 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006051 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 return;
6053 }
6054 }
6055 } finally {
6056 Binder.restoreCallingIdentity(origId);
6057 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006058 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 }
6060 }
6061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 public void moveTaskToBack(int task) {
6063 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6064 "moveTaskToBack()");
6065
6066 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006067 if (mMainStack.mResumedActivity != null
6068 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006069 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6070 Binder.getCallingUid(), "Task to back")) {
6071 return;
6072 }
6073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006075 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 Binder.restoreCallingIdentity(origId);
6077 }
6078 }
6079
6080 /**
6081 * Moves an activity, and all of the other activities within the same task, to the bottom
6082 * of the history stack. The activity's order within the task is unchanged.
6083 *
6084 * @param token A reference to the activity we wish to move
6085 * @param nonRoot If false then this only works if the activity is the root
6086 * of a task; if true it will work for any activity in a task.
6087 * @return Returns true if the move completed, false if not.
6088 */
6089 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006090 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 synchronized(this) {
6092 final long origId = Binder.clearCallingIdentity();
6093 int taskId = getTaskForActivityLocked(token, !nonRoot);
6094 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006095 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 }
6097 Binder.restoreCallingIdentity(origId);
6098 }
6099 return false;
6100 }
6101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 public void moveTaskBackwards(int task) {
6103 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6104 "moveTaskBackwards()");
6105
6106 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006107 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6108 Binder.getCallingUid(), "Task backwards")) {
6109 return;
6110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 final long origId = Binder.clearCallingIdentity();
6112 moveTaskBackwardsLocked(task);
6113 Binder.restoreCallingIdentity(origId);
6114 }
6115 }
6116
6117 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006118 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 }
6120
6121 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6122 synchronized(this) {
6123 return getTaskForActivityLocked(token, onlyRoot);
6124 }
6125 }
6126
6127 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006128 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 TaskRecord lastTask = null;
6130 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006131 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006132 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 if (!onlyRoot || lastTask != r.task) {
6134 return r.task.taskId;
6135 }
6136 return -1;
6137 }
6138 lastTask = r.task;
6139 }
6140
6141 return -1;
6142 }
6143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 // =========================================================
6145 // THUMBNAILS
6146 // =========================================================
6147
6148 public void reportThumbnail(IBinder token,
6149 Bitmap thumbnail, CharSequence description) {
6150 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6151 final long origId = Binder.clearCallingIdentity();
6152 sendPendingThumbnail(null, token, thumbnail, description, true);
6153 Binder.restoreCallingIdentity(origId);
6154 }
6155
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006156 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 Bitmap thumbnail, CharSequence description, boolean always) {
6158 TaskRecord task = null;
6159 ArrayList receivers = null;
6160
6161 //System.out.println("Send pending thumbnail: " + r);
6162
6163 synchronized(this) {
6164 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006165 r = mMainStack.isInStackLocked(token);
6166 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 return;
6168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006170 if (thumbnail == null && r.thumbHolder != null) {
6171 thumbnail = r.thumbHolder.lastThumbnail;
6172 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 }
6174 if (thumbnail == null && !always) {
6175 // If there is no thumbnail, and this entry is not actually
6176 // going away, then abort for now and pick up the next
6177 // thumbnail we get.
6178 return;
6179 }
6180 task = r.task;
6181
6182 int N = mPendingThumbnails.size();
6183 int i=0;
6184 while (i<N) {
6185 PendingThumbnailsRecord pr =
6186 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6187 //System.out.println("Looking in " + pr.pendingRecords);
6188 if (pr.pendingRecords.remove(r)) {
6189 if (receivers == null) {
6190 receivers = new ArrayList();
6191 }
6192 receivers.add(pr);
6193 if (pr.pendingRecords.size() == 0) {
6194 pr.finished = true;
6195 mPendingThumbnails.remove(i);
6196 N--;
6197 continue;
6198 }
6199 }
6200 i++;
6201 }
6202 }
6203
6204 if (receivers != null) {
6205 final int N = receivers.size();
6206 for (int i=0; i<N; i++) {
6207 try {
6208 PendingThumbnailsRecord pr =
6209 (PendingThumbnailsRecord)receivers.get(i);
6210 pr.receiver.newThumbnail(
6211 task != null ? task.taskId : -1, thumbnail, description);
6212 if (pr.finished) {
6213 pr.receiver.finished();
6214 }
6215 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006216 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 }
6218 }
6219 }
6220 }
6221
6222 // =========================================================
6223 // CONTENT PROVIDERS
6224 // =========================================================
6225
Jeff Brown10e89712011-07-08 18:52:57 -07006226 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6227 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006229 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006230 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006231 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 } catch (RemoteException ex) {
6233 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006234 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006235 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6236 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006238 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 for (int i=0; i<N; i++) {
6240 ProviderInfo cpi =
6241 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006242 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6243 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006244 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006245 // This is a singleton provider, but a user besides the
6246 // default user is asking to initialize a process it runs
6247 // in... well, no, it doesn't actually run in this process,
6248 // it runs in the process of the default user. Get rid of it.
6249 providers.remove(i);
6250 N--;
6251 continue;
6252 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006253
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006254 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006255 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006257 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006258 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006260 if (DEBUG_MU)
6261 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 app.pubProviders.put(cpi.name, cpr);
6263 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006264 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 }
6266 }
6267 return providers;
6268 }
6269
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006270 /**
6271 * Check if {@link ProcessRecord} has a possible chance at accessing the
6272 * given {@link ProviderInfo}. Final permission checking is always done
6273 * in {@link ContentProvider}.
6274 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006276 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006278 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006280 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006281 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 return null;
6283 }
6284 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006285 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 == PackageManager.PERMISSION_GRANTED) {
6287 return null;
6288 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006289
6290 PathPermission[] pps = cpi.pathPermissions;
6291 if (pps != null) {
6292 int i = pps.length;
6293 while (i > 0) {
6294 i--;
6295 PathPermission pp = pps[i];
6296 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006297 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006298 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006299 return null;
6300 }
6301 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006302 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006303 == PackageManager.PERMISSION_GRANTED) {
6304 return null;
6305 }
6306 }
6307 }
6308
Dianne Hackbornb424b632010-08-18 15:59:05 -07006309 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6310 if (perms != null) {
6311 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6312 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6313 return null;
6314 }
6315 }
6316 }
6317
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006318 String msg;
6319 if (!cpi.exported) {
6320 msg = "Permission Denial: opening provider " + cpi.name
6321 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6322 + ", uid=" + callingUid + ") that is not exported from uid "
6323 + cpi.applicationInfo.uid;
6324 } else {
6325 msg = "Permission Denial: opening provider " + cpi.name
6326 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6327 + ", uid=" + callingUid + ") requires "
6328 + cpi.readPermission + " or " + cpi.writePermission;
6329 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006330 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 return msg;
6332 }
6333
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006334 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6335 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006336 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006337 for (int i=0; i<r.conProviders.size(); i++) {
6338 ContentProviderConnection conn = r.conProviders.get(i);
6339 if (conn.provider == cpr) {
6340 if (DEBUG_PROVIDER) Slog.v(TAG,
6341 "Adding provider requested by "
6342 + r.processName + " from process "
6343 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6344 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6345 if (stable) {
6346 conn.stableCount++;
6347 conn.numStableIncs++;
6348 } else {
6349 conn.unstableCount++;
6350 conn.numUnstableIncs++;
6351 }
6352 return conn;
6353 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006354 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006355 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6356 if (stable) {
6357 conn.stableCount = 1;
6358 conn.numStableIncs = 1;
6359 } else {
6360 conn.unstableCount = 1;
6361 conn.numUnstableIncs = 1;
6362 }
6363 cpr.connections.add(conn);
6364 r.conProviders.add(conn);
6365 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006366 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006367 cpr.addExternalProcessHandleLocked(externalProcessToken);
6368 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006369 }
6370
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006371 boolean decProviderCountLocked(ContentProviderConnection conn,
6372 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6373 if (conn != null) {
6374 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006375 if (DEBUG_PROVIDER) Slog.v(TAG,
6376 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006377 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006378 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006379 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6380 if (stable) {
6381 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006382 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006383 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006384 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006385 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6386 cpr.connections.remove(conn);
6387 conn.client.conProviders.remove(conn);
6388 return true;
6389 }
6390 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006391 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006392 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006393 return false;
6394 }
6395
Amith Yamasani742a6712011-05-04 14:49:28 -07006396 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006397 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006399 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 ProviderInfo cpi = null;
6401
6402 synchronized(this) {
6403 ProcessRecord r = null;
6404 if (caller != null) {
6405 r = getRecordForAppLocked(caller);
6406 if (r == null) {
6407 throw new SecurityException(
6408 "Unable to find app for caller " + caller
6409 + " (pid=" + Binder.getCallingPid()
6410 + ") when getting content provider " + name);
6411 }
6412 }
6413
6414 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006415 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006416 boolean providerRunning = cpr != null;
6417 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006419 String msg;
6420 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6421 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423
6424 if (r != null && cpr.canRunHere(r)) {
6425 // This provider has been published or is in the process
6426 // of being published... but it is also allowed to run
6427 // in the caller's process, so don't make a connection
6428 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006429 ContentProviderHolder holder = cpr.newHolder(null);
6430 // don't give caller the provider object, it needs
6431 // to make its own.
6432 holder.provider = null;
6433 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 }
6435
6436 final long origId = Binder.clearCallingIdentity();
6437
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006438 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006440 conn = incProviderCountLocked(r, cpr, token, stable);
6441 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006442 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006443 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006444 // make sure to count it as being accessed and thus
6445 // back up on the LRU list. This is good because
6446 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006447 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006448 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006449 }
6450
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006451 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006452 if (false) {
6453 if (cpr.name.flattenToShortString().equals(
6454 "com.android.providers.calendar/.CalendarProvider2")) {
6455 Slog.v(TAG, "****************** KILLING "
6456 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006457 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006458 }
6459 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006460 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006461 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6462 // NOTE: there is still a race here where a signal could be
6463 // pending on the process even though we managed to update its
6464 // adj level. Not sure what to do about this, but at least
6465 // the race is now smaller.
6466 if (!success) {
6467 // Uh oh... it looks like the provider's process
6468 // has been killed on us. We need to wait for a new
6469 // process to be started, and make sure its death
6470 // doesn't kill our process.
6471 Slog.i(TAG,
6472 "Existing provider " + cpr.name.flattenToShortString()
6473 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006474 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006475 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006476 if (!lastRef) {
6477 // This wasn't the last ref our process had on
6478 // the provider... we have now been killed, bail.
6479 return null;
6480 }
6481 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006482 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 }
6485
6486 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006489 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006490 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006492 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006493 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006494 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 } catch (RemoteException ex) {
6496 }
6497 if (cpi == null) {
6498 return null;
6499 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006500 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6501 cpi.name, cpi.flags);
6502 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006503 userId = 0;
6504 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006505 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006506
Dianne Hackbornb424b632010-08-18 15:59:05 -07006507 String msg;
6508 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6509 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 }
6511
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006512 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006513 && !cpi.processName.equals("system")) {
6514 // If this content provider does not run in the system
6515 // process, and the system is not yet ready to run other
6516 // processes, then fail fast instead of hanging.
6517 throw new IllegalArgumentException(
6518 "Attempt to launch content provider before system ready");
6519 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006520
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006521 // Make sure that the user who owns this provider is started. If not,
6522 // we don't want to allow it to run.
6523 if (mStartedUsers.get(userId) == null) {
6524 Slog.w(TAG, "Unable to launch app "
6525 + cpi.applicationInfo.packageName + "/"
6526 + cpi.applicationInfo.uid + " for provider "
6527 + name + ": user " + userId + " is stopped");
6528 return null;
6529 }
6530
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006531 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006532 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 final boolean firstClass = cpr == null;
6534 if (firstClass) {
6535 try {
6536 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006537 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 getApplicationInfo(
6539 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006540 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006542 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 + cpi.name);
6544 return null;
6545 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006546 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006547 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 } catch (RemoteException ex) {
6549 // pm is in same process, this will never happen.
6550 }
6551 }
6552
6553 if (r != null && cpr.canRunHere(r)) {
6554 // If this is a multiprocess provider, then just return its
6555 // info and allow the caller to instantiate it. Only do
6556 // this if the provider is the same user as the caller's
6557 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006558 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 }
6560
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006561 if (DEBUG_PROVIDER) {
6562 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006563 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006564 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 }
6566
6567 // This is single process, and our app is now connecting to it.
6568 // See if we are already in the process of launching this
6569 // provider.
6570 final int N = mLaunchingProviders.size();
6571 int i;
6572 for (i=0; i<N; i++) {
6573 if (mLaunchingProviders.get(i) == cpr) {
6574 break;
6575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 }
6577
6578 // If the provider is not already being launched, then get it
6579 // started.
6580 if (i >= N) {
6581 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006582
6583 try {
6584 // Content provider is now in use, its package can't be stopped.
6585 try {
6586 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006587 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006588 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006589 } catch (IllegalArgumentException e) {
6590 Slog.w(TAG, "Failed trying to unstop package "
6591 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006592 }
6593
6594 ProcessRecord proc = startProcessLocked(cpi.processName,
6595 cpr.appInfo, false, 0, "content provider",
6596 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006597 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006598 if (proc == null) {
6599 Slog.w(TAG, "Unable to launch app "
6600 + cpi.applicationInfo.packageName + "/"
6601 + cpi.applicationInfo.uid + " for provider "
6602 + name + ": process is bad");
6603 return null;
6604 }
6605 cpr.launchingApp = proc;
6606 mLaunchingProviders.add(cpr);
6607 } finally {
6608 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 }
6611
6612 // Make sure the provider is published (the same provider class
6613 // may be published under multiple names).
6614 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006615 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006617
Amith Yamasani742a6712011-05-04 14:49:28 -07006618 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006619 conn = incProviderCountLocked(r, cpr, token, stable);
6620 if (conn != null) {
6621 conn.waiting = true;
6622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 }
6624 }
6625
6626 // Wait for the provider to be published...
6627 synchronized (cpr) {
6628 while (cpr.provider == null) {
6629 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006630 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 + cpi.applicationInfo.packageName + "/"
6632 + cpi.applicationInfo.uid + " for provider "
6633 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006634 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 cpi.applicationInfo.packageName,
6636 cpi.applicationInfo.uid, name);
6637 return null;
6638 }
6639 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006640 if (DEBUG_MU) {
6641 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6642 + cpr.launchingApp);
6643 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006644 if (conn != null) {
6645 conn.waiting = true;
6646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 cpr.wait();
6648 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006649 } finally {
6650 if (conn != null) {
6651 conn.waiting = false;
6652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 }
6654 }
6655 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006656 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 }
6658
6659 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006660 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006661 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 if (caller == null) {
6663 String msg = "null IApplicationThread when getting content provider "
6664 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006665 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 throw new SecurityException(msg);
6667 }
6668
Dianne Hackborn139748f2012-09-24 11:36:57 -07006669 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006670 false, true, "getContentProvider", null);
6671 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 }
6673
Jeff Sharkey6d515712012-09-20 16:06:08 -07006674 public ContentProviderHolder getContentProviderExternal(
6675 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006676 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6677 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006678 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006679 false, true, "getContentProvider", null);
6680 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006681 }
6682
Dianne Hackborn41203752012-08-31 14:05:51 -07006683 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6684 IBinder token, int userId) {
6685 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 }
6687
6688 /**
6689 * Drop a content provider from a ProcessRecord's bookkeeping
6690 * @param cpr
6691 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006692 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006693 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006695 ContentProviderConnection conn;
6696 try {
6697 conn = (ContentProviderConnection)connection;
6698 } catch (ClassCastException e) {
6699 String msg ="removeContentProvider: " + connection
6700 + " not a ContentProviderConnection";
6701 Slog.w(TAG, msg);
6702 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006704 if (conn == null) {
6705 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006707 if (decProviderCountLocked(conn, null, null, stable)) {
6708 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 }
6711 }
6712
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006713 public void removeContentProviderExternal(String name, IBinder token) {
6714 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6715 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006716 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006717 }
6718
Dianne Hackborn41203752012-08-31 14:05:51 -07006719 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006721 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 if(cpr == null) {
6723 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006724 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 return;
6726 }
6727
6728 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006729 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006730 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006731 if (localCpr.hasExternalProcessHandles()) {
6732 if (localCpr.removeExternalProcessHandleLocked(token)) {
6733 updateOomAdjLocked();
6734 } else {
6735 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6736 + " with no external reference for token: "
6737 + token + ".");
6738 }
6739 } else {
6740 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6741 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 }
6744 }
6745
6746 public final void publishContentProviders(IApplicationThread caller,
6747 List<ContentProviderHolder> providers) {
6748 if (providers == null) {
6749 return;
6750 }
6751
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006752 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006753 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006755 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006756 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 if (r == null) {
6758 throw new SecurityException(
6759 "Unable to find app for caller " + caller
6760 + " (pid=" + Binder.getCallingPid()
6761 + ") when publishing content providers");
6762 }
6763
6764 final long origId = Binder.clearCallingIdentity();
6765
6766 final int N = providers.size();
6767 for (int i=0; i<N; i++) {
6768 ContentProviderHolder src = providers.get(i);
6769 if (src == null || src.info == null || src.provider == null) {
6770 continue;
6771 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006772 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006773 if (DEBUG_MU)
6774 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006776 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006777 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 String names[] = dst.info.authority.split(";");
6779 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006780 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 }
6782
6783 int NL = mLaunchingProviders.size();
6784 int j;
6785 for (j=0; j<NL; j++) {
6786 if (mLaunchingProviders.get(j) == dst) {
6787 mLaunchingProviders.remove(j);
6788 j--;
6789 NL--;
6790 }
6791 }
6792 synchronized (dst) {
6793 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006794 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 dst.notifyAll();
6796 }
6797 updateOomAdjLocked(r);
6798 }
6799 }
6800
6801 Binder.restoreCallingIdentity(origId);
6802 }
6803 }
6804
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006805 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6806 ContentProviderConnection conn;
6807 try {
6808 conn = (ContentProviderConnection)connection;
6809 } catch (ClassCastException e) {
6810 String msg ="refContentProvider: " + connection
6811 + " not a ContentProviderConnection";
6812 Slog.w(TAG, msg);
6813 throw new IllegalArgumentException(msg);
6814 }
6815 if (conn == null) {
6816 throw new NullPointerException("connection is null");
6817 }
6818
6819 synchronized (this) {
6820 if (stable > 0) {
6821 conn.numStableIncs += stable;
6822 }
6823 stable = conn.stableCount + stable;
6824 if (stable < 0) {
6825 throw new IllegalStateException("stableCount < 0: " + stable);
6826 }
6827
6828 if (unstable > 0) {
6829 conn.numUnstableIncs += unstable;
6830 }
6831 unstable = conn.unstableCount + unstable;
6832 if (unstable < 0) {
6833 throw new IllegalStateException("unstableCount < 0: " + unstable);
6834 }
6835
6836 if ((stable+unstable) <= 0) {
6837 throw new IllegalStateException("ref counts can't go to zero here: stable="
6838 + stable + " unstable=" + unstable);
6839 }
6840 conn.stableCount = stable;
6841 conn.unstableCount = unstable;
6842 return !conn.dead;
6843 }
6844 }
6845
6846 public void unstableProviderDied(IBinder connection) {
6847 ContentProviderConnection conn;
6848 try {
6849 conn = (ContentProviderConnection)connection;
6850 } catch (ClassCastException e) {
6851 String msg ="refContentProvider: " + connection
6852 + " not a ContentProviderConnection";
6853 Slog.w(TAG, msg);
6854 throw new IllegalArgumentException(msg);
6855 }
6856 if (conn == null) {
6857 throw new NullPointerException("connection is null");
6858 }
6859
6860 // Safely retrieve the content provider associated with the connection.
6861 IContentProvider provider;
6862 synchronized (this) {
6863 provider = conn.provider.provider;
6864 }
6865
6866 if (provider == null) {
6867 // Um, yeah, we're way ahead of you.
6868 return;
6869 }
6870
6871 // Make sure the caller is being honest with us.
6872 if (provider.asBinder().pingBinder()) {
6873 // Er, no, still looks good to us.
6874 synchronized (this) {
6875 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6876 + " says " + conn + " died, but we don't agree");
6877 return;
6878 }
6879 }
6880
6881 // Well look at that! It's dead!
6882 synchronized (this) {
6883 if (conn.provider.provider != provider) {
6884 // But something changed... good enough.
6885 return;
6886 }
6887
6888 ProcessRecord proc = conn.provider.proc;
6889 if (proc == null || proc.thread == null) {
6890 // Seems like the process is already cleaned up.
6891 return;
6892 }
6893
6894 // As far as we're concerned, this is just like receiving a
6895 // death notification... just a bit prematurely.
6896 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6897 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006898 final long ident = Binder.clearCallingIdentity();
6899 try {
6900 appDiedLocked(proc, proc.pid, proc.thread);
6901 } finally {
6902 Binder.restoreCallingIdentity(ident);
6903 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006904 }
6905 }
6906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006908 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006909 synchronized (mSelf) {
6910 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6911 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006912 if (providers != null) {
6913 for (int i=providers.size()-1; i>=0; i--) {
6914 ProviderInfo pi = (ProviderInfo)providers.get(i);
6915 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6916 Slog.w(TAG, "Not installing system proc provider " + pi.name
6917 + ": not system .apk");
6918 providers.remove(i);
6919 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006920 }
6921 }
6922 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006923 if (providers != null) {
6924 mSystemThread.installSystemProviders(providers);
6925 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006926
6927 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006928
6929 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 }
6931
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006932 /**
6933 * Allows app to retrieve the MIME type of a URI without having permission
6934 * to access its content provider.
6935 *
6936 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6937 *
6938 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6939 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6940 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006941 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006942 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006943 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006944 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006945 final String name = uri.getAuthority();
6946 final long ident = Binder.clearCallingIdentity();
6947 ContentProviderHolder holder = null;
6948
6949 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006950 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006951 if (holder != null) {
6952 return holder.provider.getType(uri);
6953 }
6954 } catch (RemoteException e) {
6955 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6956 return null;
6957 } finally {
6958 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006959 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006960 }
6961 Binder.restoreCallingIdentity(ident);
6962 }
6963
6964 return null;
6965 }
6966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 // =========================================================
6968 // GLOBAL MANAGEMENT
6969 // =========================================================
6970
6971 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006972 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 String proc = customProcess != null ? customProcess : info.processName;
6974 BatteryStatsImpl.Uid.Proc ps = null;
6975 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006976 int uid = info.uid;
6977 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006978 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006979 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6980 uid = 0;
6981 while (true) {
6982 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6983 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6984 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6985 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006986 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006987 mNextIsolatedProcessUid++;
6988 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6989 // No process for this uid, use it.
6990 break;
6991 }
6992 stepsLeft--;
6993 if (stepsLeft <= 0) {
6994 return null;
6995 }
6996 }
6997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 synchronized (stats) {
6999 ps = stats.getProcessStatsLocked(info.uid, proc);
7000 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007001 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 }
7003
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007004 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7005 ProcessRecord app;
7006 if (!isolated) {
7007 app = getProcessRecordLocked(info.processName, info.uid);
7008 } else {
7009 app = null;
7010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011
7012 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007013 app = newProcessRecordLocked(null, info, null, isolated);
7014 mProcessNames.put(info.processName, app.uid, app);
7015 if (isolated) {
7016 mIsolatedProcesses.put(app.uid, app);
7017 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007018 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 }
7020
Dianne Hackborne7f97212011-02-24 14:40:20 -08007021 // This package really, really can not be stopped.
7022 try {
7023 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007024 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007025 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007026 } catch (IllegalArgumentException e) {
7027 Slog.w(TAG, "Failed trying to unstop package "
7028 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007029 }
7030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7032 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7033 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007034 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
7036 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7037 mPersistentStartingProcesses.add(app);
7038 startProcessLocked(app, "added application", app.processName);
7039 }
7040
7041 return app;
7042 }
7043
7044 public void unhandledBack() {
7045 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7046 "unhandledBack()");
7047
7048 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007049 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007050 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 TAG, "Performing unhandledBack(): stack size = " + count);
7052 if (count > 1) {
7053 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007054 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007055 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 Binder.restoreCallingIdentity(origId);
7057 }
7058 }
7059 }
7060
7061 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007062 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007063 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007065 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 ParcelFileDescriptor pfd = null;
7067 if (cph != null) {
7068 // We record the binder invoker's uid in thread-local storage before
7069 // going to the content provider to open the file. Later, in the code
7070 // that handles all permissions checks, we look for this uid and use
7071 // that rather than the Activity Manager's own uid. The effect is that
7072 // we do the check against the caller's permissions even though it looks
7073 // to the content provider like the Activity Manager itself is making
7074 // the request.
7075 sCallerIdentity.set(new Identity(
7076 Binder.getCallingPid(), Binder.getCallingUid()));
7077 try {
7078 pfd = cph.provider.openFile(uri, "r");
7079 } catch (FileNotFoundException e) {
7080 // do nothing; pfd will be returned null
7081 } finally {
7082 // Ensure that whatever happens, we clean up the identity state
7083 sCallerIdentity.remove();
7084 }
7085
7086 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007087 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007089 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 }
7091 return pfd;
7092 }
7093
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007094 // Actually is sleeping or shutting down or whatever else in the future
7095 // is an inactive state.
7096 public boolean isSleeping() {
7097 return mSleeping || mShuttingDown;
7098 }
7099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007101 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7102 != PackageManager.PERMISSION_GRANTED) {
7103 throw new SecurityException("Requires permission "
7104 + android.Manifest.permission.DEVICE_POWER);
7105 }
7106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007108 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007109 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007111 if (!mSleeping) {
7112 mSleeping = true;
7113 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007114
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007115 // Initialize the wake times of all processes.
7116 checkExcessivePowerUsageLocked(false);
7117 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7118 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7119 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 }
7122 }
7123
Dianne Hackborn55280a92009-05-07 15:53:46 -07007124 public boolean shutdown(int timeout) {
7125 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7126 != PackageManager.PERMISSION_GRANTED) {
7127 throw new SecurityException("Requires permission "
7128 + android.Manifest.permission.SHUTDOWN);
7129 }
7130
7131 boolean timedout = false;
7132
7133 synchronized(this) {
7134 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007135 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007136
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007137 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007138 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007139 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007140 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007141 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007142 long delay = endTime - System.currentTimeMillis();
7143 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007144 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007145 timedout = true;
7146 break;
7147 }
7148 try {
7149 this.wait();
7150 } catch (InterruptedException e) {
7151 }
7152 }
7153 }
7154 }
7155
7156 mUsageStatsService.shutdown();
7157 mBatteryStatsService.shutdown();
7158
7159 return timedout;
7160 }
7161
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007162 public final void activitySlept(IBinder token) {
7163 if (localLOGV) Slog.v(
7164 TAG, "Activity slept: token=" + token);
7165
7166 ActivityRecord r = null;
7167
7168 final long origId = Binder.clearCallingIdentity();
7169
7170 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007171 r = mMainStack.isInStackLocked(token);
7172 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007173 mMainStack.activitySleptLocked(r);
7174 }
7175 }
7176
7177 Binder.restoreCallingIdentity(origId);
7178 }
7179
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007180 private void comeOutOfSleepIfNeededLocked() {
7181 if (!mWentToSleep && !mLockScreenShown) {
7182 if (mSleeping) {
7183 mSleeping = false;
7184 mMainStack.awakeFromSleepingLocked();
7185 mMainStack.resumeTopActivityLocked(null);
7186 }
7187 }
7188 }
7189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007191 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7192 != PackageManager.PERMISSION_GRANTED) {
7193 throw new SecurityException("Requires permission "
7194 + android.Manifest.permission.DEVICE_POWER);
7195 }
7196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007198 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007199 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007200 comeOutOfSleepIfNeededLocked();
7201 }
7202 }
7203
Jeff Brownc042ee22012-05-08 13:03:42 -07007204 private void updateEventDispatchingLocked() {
7205 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7206 }
7207
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007208 public void setLockScreenShown(boolean shown) {
7209 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7210 != PackageManager.PERMISSION_GRANTED) {
7211 throw new SecurityException("Requires permission "
7212 + android.Manifest.permission.DEVICE_POWER);
7213 }
7214
7215 synchronized(this) {
7216 mLockScreenShown = shown;
7217 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 }
7219 }
7220
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007221 public void stopAppSwitches() {
7222 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7223 != PackageManager.PERMISSION_GRANTED) {
7224 throw new SecurityException("Requires permission "
7225 + android.Manifest.permission.STOP_APP_SWITCHES);
7226 }
7227
7228 synchronized(this) {
7229 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7230 + APP_SWITCH_DELAY_TIME;
7231 mDidAppSwitch = false;
7232 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7233 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7234 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7235 }
7236 }
7237
7238 public void resumeAppSwitches() {
7239 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7240 != PackageManager.PERMISSION_GRANTED) {
7241 throw new SecurityException("Requires permission "
7242 + android.Manifest.permission.STOP_APP_SWITCHES);
7243 }
7244
7245 synchronized(this) {
7246 // Note that we don't execute any pending app switches... we will
7247 // let those wait until either the timeout, or the next start
7248 // activity request.
7249 mAppSwitchesAllowedTime = 0;
7250 }
7251 }
7252
7253 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7254 String name) {
7255 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7256 return true;
7257 }
7258
7259 final int perm = checkComponentPermission(
7260 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007261 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007262 if (perm == PackageManager.PERMISSION_GRANTED) {
7263 return true;
7264 }
7265
Joe Onorato8a9b2202010-02-26 18:56:32 -08007266 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007267 return false;
7268 }
7269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 public void setDebugApp(String packageName, boolean waitForDebugger,
7271 boolean persistent) {
7272 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7273 "setDebugApp()");
7274
7275 // Note that this is not really thread safe if there are multiple
7276 // callers into it at the same time, but that's not a situation we
7277 // care about.
7278 if (persistent) {
7279 final ContentResolver resolver = mContext.getContentResolver();
7280 Settings.System.putString(
7281 resolver, Settings.System.DEBUG_APP,
7282 packageName);
7283 Settings.System.putInt(
7284 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7285 waitForDebugger ? 1 : 0);
7286 }
7287
7288 synchronized (this) {
7289 if (!persistent) {
7290 mOrigDebugApp = mDebugApp;
7291 mOrigWaitForDebugger = mWaitForDebugger;
7292 }
7293 mDebugApp = packageName;
7294 mWaitForDebugger = waitForDebugger;
7295 mDebugTransient = !persistent;
7296 if (packageName != null) {
7297 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007298 forceStopPackageLocked(packageName, -1, false, false, true, true,
7299 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007300 Binder.restoreCallingIdentity(origId);
7301 }
7302 }
7303 }
7304
Siva Velusamy92a8b222012-03-09 16:24:04 -08007305 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7306 synchronized (this) {
7307 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7308 if (!isDebuggable) {
7309 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7310 throw new SecurityException("Process not debuggable: " + app.packageName);
7311 }
7312 }
7313
7314 mOpenGlTraceApp = processName;
7315 }
7316 }
7317
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007318 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7319 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7320 synchronized (this) {
7321 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7322 if (!isDebuggable) {
7323 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7324 throw new SecurityException("Process not debuggable: " + app.packageName);
7325 }
7326 }
7327 mProfileApp = processName;
7328 mProfileFile = profileFile;
7329 if (mProfileFd != null) {
7330 try {
7331 mProfileFd.close();
7332 } catch (IOException e) {
7333 }
7334 mProfileFd = null;
7335 }
7336 mProfileFd = profileFd;
7337 mProfileType = 0;
7338 mAutoStopProfiler = autoStopProfiler;
7339 }
7340 }
7341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 public void setAlwaysFinish(boolean enabled) {
7343 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7344 "setAlwaysFinish()");
7345
7346 Settings.System.putInt(
7347 mContext.getContentResolver(),
7348 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7349
7350 synchronized (this) {
7351 mAlwaysFinishActivities = enabled;
7352 }
7353 }
7354
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007355 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007357 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007358 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007359 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 }
7361 }
7362
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007363 public boolean isUserAMonkey() {
7364 // For now the fact that there is a controller implies
7365 // we have a monkey.
7366 synchronized (this) {
7367 return mController != null;
7368 }
7369 }
7370
Jeff Sharkeya4620792011-05-20 15:29:23 -07007371 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007372 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7373 "registerProcessObserver()");
7374 synchronized (this) {
7375 mProcessObservers.register(observer);
7376 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007377 }
7378
7379 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007380 synchronized (this) {
7381 mProcessObservers.unregister(observer);
7382 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007383 }
7384
Daniel Sandler69a48172010-06-23 16:29:36 -04007385 public void setImmersive(IBinder token, boolean immersive) {
7386 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007387 ActivityRecord r = mMainStack.isInStackLocked(token);
7388 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007389 throw new IllegalArgumentException();
7390 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007391 r.immersive = immersive;
7392 }
7393 }
7394
7395 public boolean isImmersive(IBinder token) {
7396 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007397 ActivityRecord r = mMainStack.isInStackLocked(token);
7398 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007399 throw new IllegalArgumentException();
7400 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007401 return r.immersive;
7402 }
7403 }
7404
7405 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007406 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007407 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007408 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007409 return (r != null) ? r.immersive : false;
7410 }
7411 }
7412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 public final void enterSafeMode() {
7414 synchronized(this) {
7415 // It only makes sense to do this before the system is ready
7416 // and started launching other packages.
7417 if (!mSystemReady) {
7418 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007419 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 } catch (RemoteException e) {
7421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 }
7423 }
7424 }
7425
Jeff Brownb09abc12011-01-13 21:08:27 -08007426 public final void showSafeModeOverlay() {
7427 View v = LayoutInflater.from(mContext).inflate(
7428 com.android.internal.R.layout.safe_mode, null);
7429 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7430 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7431 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7432 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007433 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007434 lp.format = v.getBackground().getOpacity();
7435 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7436 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7437 ((WindowManager)mContext.getSystemService(
7438 Context.WINDOW_SERVICE)).addView(v, lp);
7439 }
7440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 public void noteWakeupAlarm(IIntentSender sender) {
7442 if (!(sender instanceof PendingIntentRecord)) {
7443 return;
7444 }
7445 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7446 synchronized (stats) {
7447 if (mBatteryStatsService.isOnBattery()) {
7448 mBatteryStatsService.enforceCallingPermission();
7449 PendingIntentRecord rec = (PendingIntentRecord)sender;
7450 int MY_UID = Binder.getCallingUid();
7451 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7452 BatteryStatsImpl.Uid.Pkg pkg =
7453 stats.getPackageStatsLocked(uid, rec.key.packageName);
7454 pkg.incWakeupsLocked();
7455 }
7456 }
7457 }
7458
Dianne Hackborn64825172011-03-02 21:32:58 -08007459 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007461 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007463 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 // XXX Note: don't acquire main activity lock here, because the window
7465 // manager calls in with its locks held.
7466
7467 boolean killed = false;
7468 synchronized (mPidsSelfLocked) {
7469 int[] types = new int[pids.length];
7470 int worstType = 0;
7471 for (int i=0; i<pids.length; i++) {
7472 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7473 if (proc != null) {
7474 int type = proc.setAdj;
7475 types[i] = type;
7476 if (type > worstType) {
7477 worstType = type;
7478 }
7479 }
7480 }
7481
Dianne Hackborn64825172011-03-02 21:32:58 -08007482 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007484 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7485 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007486 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007488
7489 // If this is not a secure call, don't let it kill processes that
7490 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007491 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7492 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007493 }
7494
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007495 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 for (int i=0; i<pids.length; i++) {
7497 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7498 if (proc == null) {
7499 continue;
7500 }
7501 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007502 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007503 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007504 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7505 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007507 proc.killedBackground = true;
7508 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 }
7510 }
7511 }
7512 return killed;
7513 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007514
7515 @Override
7516 public boolean killProcessesBelowForeground(String reason) {
7517 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7518 throw new SecurityException("killProcessesBelowForeground() only available to system");
7519 }
7520
7521 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7522 }
7523
7524 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7525 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7526 throw new SecurityException("killProcessesBelowAdj() only available to system");
7527 }
7528
7529 boolean killed = false;
7530 synchronized (mPidsSelfLocked) {
7531 final int size = mPidsSelfLocked.size();
7532 for (int i = 0; i < size; i++) {
7533 final int pid = mPidsSelfLocked.keyAt(i);
7534 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7535 if (proc == null) continue;
7536
7537 final int adj = proc.setAdj;
7538 if (adj > belowAdj && !proc.killedBackground) {
7539 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7540 EventLog.writeEvent(
7541 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7542 killed = true;
7543 proc.killedBackground = true;
7544 Process.killProcessQuiet(pid);
7545 }
7546 }
7547 }
7548 return killed;
7549 }
7550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 public final void startRunning(String pkg, String cls, String action,
7552 String data) {
7553 synchronized(this) {
7554 if (mStartRunning) {
7555 return;
7556 }
7557 mStartRunning = true;
7558 mTopComponent = pkg != null && cls != null
7559 ? new ComponentName(pkg, cls) : null;
7560 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7561 mTopData = data;
7562 if (!mSystemReady) {
7563 return;
7564 }
7565 }
7566
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007567 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 }
7569
7570 private void retrieveSettings() {
7571 final ContentResolver resolver = mContext.getContentResolver();
7572 String debugApp = Settings.System.getString(
7573 resolver, Settings.System.DEBUG_APP);
7574 boolean waitForDebugger = Settings.System.getInt(
7575 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7576 boolean alwaysFinishActivities = Settings.System.getInt(
7577 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7578
7579 Configuration configuration = new Configuration();
7580 Settings.System.getConfiguration(resolver, configuration);
7581
7582 synchronized (this) {
7583 mDebugApp = mOrigDebugApp = debugApp;
7584 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7585 mAlwaysFinishActivities = alwaysFinishActivities;
7586 // This happens before any activities are started, so we can
7587 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007588 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007589 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 }
7591 }
7592
7593 public boolean testIsSystemReady() {
7594 // no need to synchronize(this) just to read & return the value
7595 return mSystemReady;
7596 }
7597
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007598 private static File getCalledPreBootReceiversFile() {
7599 File dataDir = Environment.getDataDirectory();
7600 File systemDir = new File(dataDir, "system");
7601 File fname = new File(systemDir, "called_pre_boots.dat");
7602 return fname;
7603 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007604
7605 static final int LAST_DONE_VERSION = 10000;
7606
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007607 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7608 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7609 File file = getCalledPreBootReceiversFile();
7610 FileInputStream fis = null;
7611 try {
7612 fis = new FileInputStream(file);
7613 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007614 int fvers = dis.readInt();
7615 if (fvers == LAST_DONE_VERSION) {
7616 String vers = dis.readUTF();
7617 String codename = dis.readUTF();
7618 String build = dis.readUTF();
7619 if (android.os.Build.VERSION.RELEASE.equals(vers)
7620 && android.os.Build.VERSION.CODENAME.equals(codename)
7621 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7622 int num = dis.readInt();
7623 while (num > 0) {
7624 num--;
7625 String pkg = dis.readUTF();
7626 String cls = dis.readUTF();
7627 lastDoneReceivers.add(new ComponentName(pkg, cls));
7628 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007629 }
7630 }
7631 } catch (FileNotFoundException e) {
7632 } catch (IOException e) {
7633 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7634 } finally {
7635 if (fis != null) {
7636 try {
7637 fis.close();
7638 } catch (IOException e) {
7639 }
7640 }
7641 }
7642 return lastDoneReceivers;
7643 }
7644
7645 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7646 File file = getCalledPreBootReceiversFile();
7647 FileOutputStream fos = null;
7648 DataOutputStream dos = null;
7649 try {
7650 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7651 fos = new FileOutputStream(file);
7652 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007653 dos.writeInt(LAST_DONE_VERSION);
7654 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007655 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007656 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007657 dos.writeInt(list.size());
7658 for (int i=0; i<list.size(); i++) {
7659 dos.writeUTF(list.get(i).getPackageName());
7660 dos.writeUTF(list.get(i).getClassName());
7661 }
7662 } catch (IOException e) {
7663 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7664 file.delete();
7665 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007666 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007667 if (dos != null) {
7668 try {
7669 dos.close();
7670 } catch (IOException e) {
7671 // TODO Auto-generated catch block
7672 e.printStackTrace();
7673 }
7674 }
7675 }
7676 }
7677
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007678 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 synchronized(this) {
7680 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007681 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 return;
7683 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007684
7685 // Check to see if there are any update receivers to run.
7686 if (!mDidUpdate) {
7687 if (mWaitingUpdate) {
7688 return;
7689 }
7690 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7691 List<ResolveInfo> ris = null;
7692 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007693 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007694 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007695 } catch (RemoteException e) {
7696 }
7697 if (ris != null) {
7698 for (int i=ris.size()-1; i>=0; i--) {
7699 if ((ris.get(i).activityInfo.applicationInfo.flags
7700 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7701 ris.remove(i);
7702 }
7703 }
7704 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007705
7706 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7707
7708 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007709 for (int i=0; i<ris.size(); i++) {
7710 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007711 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7712 if (lastDoneReceivers.contains(comp)) {
7713 ris.remove(i);
7714 i--;
7715 }
7716 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007717
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007718 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007719 for (int i=0; i<ris.size(); i++) {
7720 ActivityInfo ai = ris.get(i).activityInfo;
7721 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7722 doneReceivers.add(comp);
7723 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007724 for (int j=0; j<users.length; j++) {
7725 IIntentReceiver finisher = null;
7726 if (i == ris.size()-1 && j == users.length-1) {
7727 finisher = new IIntentReceiver.Stub() {
7728 public void performReceive(Intent intent, int resultCode,
7729 String data, Bundle extras, boolean ordered,
7730 boolean sticky, int sendingUser) {
7731 // The raw IIntentReceiver interface is called
7732 // with the AM lock held, so redispatch to
7733 // execute our code without the lock.
7734 mHandler.post(new Runnable() {
7735 public void run() {
7736 synchronized (ActivityManagerService.this) {
7737 mDidUpdate = true;
7738 }
7739 writeLastDonePreBootReceivers(doneReceivers);
7740 showBootMessage(mContext.getText(
7741 R.string.android_upgrading_complete),
7742 false);
7743 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007744 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007745 });
7746 }
7747 };
7748 }
7749 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7750 + " for user " + users[j]);
7751 broadcastIntentLocked(null, null, intent, null, finisher,
7752 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7753 users[j]);
7754 if (finisher != null) {
7755 mWaitingUpdate = true;
7756 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007757 }
7758 }
7759 }
7760 if (mWaitingUpdate) {
7761 return;
7762 }
7763 mDidUpdate = true;
7764 }
7765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 mSystemReady = true;
7767 if (!mStartRunning) {
7768 return;
7769 }
7770 }
7771
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007772 ArrayList<ProcessRecord> procsToKill = null;
7773 synchronized(mPidsSelfLocked) {
7774 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7775 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7776 if (!isAllowedWhileBooting(proc.info)){
7777 if (procsToKill == null) {
7778 procsToKill = new ArrayList<ProcessRecord>();
7779 }
7780 procsToKill.add(proc);
7781 }
7782 }
7783 }
7784
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007785 synchronized(this) {
7786 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007787 for (int i=procsToKill.size()-1; i>=0; i--) {
7788 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007789 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007790 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007791 }
7792 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007793
7794 // Now that we have cleaned up any update processes, we
7795 // are ready to start launching real processes and know that
7796 // we won't trample on them any more.
7797 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007798 }
7799
Joe Onorato8a9b2202010-02-26 18:56:32 -08007800 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 SystemClock.uptimeMillis());
7803
7804 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007805 // Make sure we have no pre-ready processes sitting around.
7806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7808 ResolveInfo ri = mContext.getPackageManager()
7809 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007810 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 CharSequence errorMsg = null;
7812 if (ri != null) {
7813 ActivityInfo ai = ri.activityInfo;
7814 ApplicationInfo app = ai.applicationInfo;
7815 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7816 mTopAction = Intent.ACTION_FACTORY_TEST;
7817 mTopData = null;
7818 mTopComponent = new ComponentName(app.packageName,
7819 ai.name);
7820 } else {
7821 errorMsg = mContext.getResources().getText(
7822 com.android.internal.R.string.factorytest_not_system);
7823 }
7824 } else {
7825 errorMsg = mContext.getResources().getText(
7826 com.android.internal.R.string.factorytest_no_action);
7827 }
7828 if (errorMsg != null) {
7829 mTopAction = null;
7830 mTopData = null;
7831 mTopComponent = null;
7832 Message msg = Message.obtain();
7833 msg.what = SHOW_FACTORY_ERROR_MSG;
7834 msg.getData().putCharSequence("msg", errorMsg);
7835 mHandler.sendMessage(msg);
7836 }
7837 }
7838 }
7839
7840 retrieveSettings();
7841
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007842 if (goingCallback != null) goingCallback.run();
7843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 synchronized (this) {
7845 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7846 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007847 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007848 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 if (apps != null) {
7850 int N = apps.size();
7851 int i;
7852 for (i=0; i<N; i++) {
7853 ApplicationInfo info
7854 = (ApplicationInfo)apps.get(i);
7855 if (info != null &&
7856 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007857 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 }
7859 }
7860 }
7861 } catch (RemoteException ex) {
7862 // pm is in same process, this will never happen.
7863 }
7864 }
7865
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007866 // Start up initial activity.
7867 mBooting = true;
7868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007870 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 Message msg = Message.obtain();
7872 msg.what = SHOW_UID_ERROR_MSG;
7873 mHandler.sendMessage(msg);
7874 }
7875 } catch (RemoteException e) {
7876 }
7877
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007878 long ident = Binder.clearCallingIdentity();
7879 try {
7880 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7881 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7882 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7883 broadcastIntentLocked(null, null, intent,
7884 null, null, 0, null, null, null,
7885 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
7886 } finally {
7887 Binder.restoreCallingIdentity(ident);
7888 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007889 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007890 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 }
7892 }
7893
Dan Egnorb7f03672009-12-09 16:22:32 -08007894 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007895 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007897 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007898 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 startAppProblemLocked(app);
7900 app.stopFreezingAllLocked();
7901 return handleAppCrashLocked(app);
7902 }
7903
Dan Egnorb7f03672009-12-09 16:22:32 -08007904 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007905 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007907 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007908 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7909 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 startAppProblemLocked(app);
7911 app.stopFreezingAllLocked();
7912 }
7913
7914 /**
7915 * Generate a process error record, suitable for attachment to a ProcessRecord.
7916 *
7917 * @param app The ProcessRecord in which the error occurred.
7918 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7919 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007920 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 * @param shortMsg Short message describing the crash.
7922 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007923 * @param stackTrace Full crash stack trace, may be null.
7924 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 * @return Returns a fully-formed AppErrorStateInfo record.
7926 */
7927 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007928 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 report.condition = condition;
7932 report.processName = app.processName;
7933 report.pid = app.pid;
7934 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007935 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 report.shortMsg = shortMsg;
7937 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007938 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939
7940 return report;
7941 }
7942
Dan Egnor42471dd2010-01-07 17:25:22 -08007943 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 synchronized (this) {
7945 app.crashing = false;
7946 app.crashingReport = null;
7947 app.notResponding = false;
7948 app.notRespondingReport = null;
7949 if (app.anrDialog == fromDialog) {
7950 app.anrDialog = null;
7951 }
7952 if (app.waitDialog == fromDialog) {
7953 app.waitDialog = null;
7954 }
7955 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007956 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007957 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007958 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7959 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007960 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 }
7963 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007964
Dan Egnorb7f03672009-12-09 16:22:32 -08007965 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007966 if (mHeadless) {
7967 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7968 return false;
7969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 long now = SystemClock.uptimeMillis();
7971
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007972 Long crashTime;
7973 if (!app.isolated) {
7974 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7975 } else {
7976 crashTime = null;
7977 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007978 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007980 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007982 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007983 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007984 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7985 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007987 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007989 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7990 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 }
7992 }
7993 if (!app.persistent) {
7994 // We don't want to start this process again until the user
7995 // explicitly does so... but for persistent process, we really
7996 // need to keep it running. If a persistent process is actually
7997 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007998 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008000 if (!app.isolated) {
8001 // XXX We don't have a way to mark isolated processes
8002 // as bad, since they don't have a peristent identity.
8003 mBadProcesses.put(app.info.processName, app.uid, now);
8004 mProcessCrashTimes.remove(app.info.processName, app.uid);
8005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008007 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008008 // Don't let services in this process be restarted and potentially
8009 // annoy the user repeatedly. Unless it is persistent, since those
8010 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008011 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008012 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 return false;
8014 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008015 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008016 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008017 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008018 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008019 // If the top running activity is from this crashing
8020 // process, then terminate it to avoid getting in a loop.
8021 Slog.w(TAG, " Force finishing activity "
8022 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008023 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008024 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008025 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008026 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008027 // stopped, to avoid a situation where one will get
8028 // re-start our crashing activity once it gets resumed again.
8029 index--;
8030 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008031 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008032 if (r.state == ActivityState.RESUMED
8033 || r.state == ActivityState.PAUSING
8034 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008035 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008036 Slog.w(TAG, " Force finishing activity "
8037 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008038 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008039 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008040 }
8041 }
8042 }
8043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 }
8045
8046 // Bump up the crash count of any services currently running in the proc.
8047 if (app.services.size() != 0) {
8048 // Any services running in the application need to be placed
8049 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008050 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008052 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 sr.crashCount++;
8054 }
8055 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008056
8057 // If the crashing process is what we consider to be the "home process" and it has been
8058 // replaced by a third-party app, clear the package preferred activities from packages
8059 // with a home activity running in the process to prevent a repeatedly crashing app
8060 // from blocking the user to manually clear the list.
8061 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8062 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8063 Iterator it = mHomeProcess.activities.iterator();
8064 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008065 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008066 if (r.isHomeActivity) {
8067 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8068 try {
8069 ActivityThread.getPackageManager()
8070 .clearPackagePreferredActivities(r.packageName);
8071 } catch (RemoteException c) {
8072 // pm is in same process, this will never happen.
8073 }
8074 }
8075 }
8076 }
8077
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008078 if (!app.isolated) {
8079 // XXX Can't keep track of crash times for isolated processes,
8080 // because they don't have a perisistent identity.
8081 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8082 }
8083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 return true;
8085 }
8086
8087 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008088 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8089 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 skipCurrentReceiverLocked(app);
8091 }
8092
8093 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008094 for (BroadcastQueue queue : mBroadcastQueues) {
8095 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 }
8097 }
8098
Dan Egnor60d87622009-12-16 16:32:58 -08008099 /**
8100 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8101 * The application process will exit immediately after this call returns.
8102 * @param app object of the crashing app, null for the system server
8103 * @param crashInfo describing the exception
8104 */
8105 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008106 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008107 final String processName = app == null ? "system_server"
8108 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008109
8110 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008111 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008112 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008113 crashInfo.exceptionClassName,
8114 crashInfo.exceptionMessage,
8115 crashInfo.throwFileName,
8116 crashInfo.throwLineNumber);
8117
Jeff Sharkeya353d262011-10-28 11:12:06 -07008118 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008119
8120 crashApplication(r, crashInfo);
8121 }
8122
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008123 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008124 IBinder app,
8125 int violationMask,
8126 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008127 ProcessRecord r = findAppProcess(app, "StrictMode");
8128 if (r == null) {
8129 return;
8130 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008131
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008132 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008133 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008134 boolean logIt = true;
8135 synchronized (mAlreadyLoggedViolatedStacks) {
8136 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8137 logIt = false;
8138 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008139 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008140 // the relative pain numbers, without logging all
8141 // the stack traces repeatedly. We'd want to do
8142 // likewise in the client code, which also does
8143 // dup suppression, before the Binder call.
8144 } else {
8145 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8146 mAlreadyLoggedViolatedStacks.clear();
8147 }
8148 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8149 }
8150 }
8151 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008152 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008153 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008154 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008155
8156 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8157 AppErrorResult result = new AppErrorResult();
8158 synchronized (this) {
8159 final long origId = Binder.clearCallingIdentity();
8160
8161 Message msg = Message.obtain();
8162 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8163 HashMap<String, Object> data = new HashMap<String, Object>();
8164 data.put("result", result);
8165 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008166 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008167 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008168 msg.obj = data;
8169 mHandler.sendMessage(msg);
8170
8171 Binder.restoreCallingIdentity(origId);
8172 }
8173 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008174 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008175 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008176 }
8177
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008178 // Depending on the policy in effect, there could be a bunch of
8179 // these in quick succession so we try to batch these together to
8180 // minimize disk writes, number of dropbox entries, and maximize
8181 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008182 private void logStrictModeViolationToDropBox(
8183 ProcessRecord process,
8184 StrictMode.ViolationInfo info) {
8185 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008186 return;
8187 }
8188 final boolean isSystemApp = process == null ||
8189 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8190 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008191 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008192 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8193 final DropBoxManager dbox = (DropBoxManager)
8194 mContext.getSystemService(Context.DROPBOX_SERVICE);
8195
8196 // Exit early if the dropbox isn't configured to accept this report type.
8197 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8198
8199 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008200 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008201 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8202 synchronized (sb) {
8203 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008204 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008205 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8206 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008207 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8208 if (info.violationNumThisLoop != 0) {
8209 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8210 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008211 if (info.numAnimationsRunning != 0) {
8212 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8213 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008214 if (info.broadcastIntentAction != null) {
8215 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8216 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008217 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008218 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008219 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008220 if (info.numInstances != -1) {
8221 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8222 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008223 if (info.tags != null) {
8224 for (String tag : info.tags) {
8225 sb.append("Span-Tag: ").append(tag).append("\n");
8226 }
8227 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008228 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008229 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8230 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008231 }
8232 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008233
8234 // Only buffer up to ~64k. Various logging bits truncate
8235 // things at 128k.
8236 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008237 }
8238
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008239 // Flush immediately if the buffer's grown too large, or this
8240 // is a non-system app. Non-system apps are isolated with a
8241 // different tag & policy and not batched.
8242 //
8243 // Batching is useful during internal testing with
8244 // StrictMode settings turned up high. Without batching,
8245 // thousands of separate files could be created on boot.
8246 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008247 new Thread("Error dump: " + dropboxTag) {
8248 @Override
8249 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008250 String report;
8251 synchronized (sb) {
8252 report = sb.toString();
8253 sb.delete(0, sb.length());
8254 sb.trimToSize();
8255 }
8256 if (report.length() != 0) {
8257 dbox.addText(dropboxTag, report);
8258 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008259 }
8260 }.start();
8261 return;
8262 }
8263
8264 // System app batching:
8265 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008266 // An existing dropbox-writing thread is outstanding, so
8267 // we don't need to start it up. The existing thread will
8268 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008269 return;
8270 }
8271
8272 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8273 // (After this point, we shouldn't access AMS internal data structures.)
8274 new Thread("Error dump: " + dropboxTag) {
8275 @Override
8276 public void run() {
8277 // 5 second sleep to let stacks arrive and be batched together
8278 try {
8279 Thread.sleep(5000); // 5 seconds
8280 } catch (InterruptedException e) {}
8281
8282 String errorReport;
8283 synchronized (mStrictModeBuffer) {
8284 errorReport = mStrictModeBuffer.toString();
8285 if (errorReport.length() == 0) {
8286 return;
8287 }
8288 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8289 mStrictModeBuffer.trimToSize();
8290 }
8291 dbox.addText(dropboxTag, errorReport);
8292 }
8293 }.start();
8294 }
8295
Dan Egnor60d87622009-12-16 16:32:58 -08008296 /**
8297 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8298 * @param app object of the crashing app, null for the system server
8299 * @param tag reported by the caller
8300 * @param crashInfo describing the context of the error
8301 * @return true if the process should exit immediately (WTF is fatal)
8302 */
8303 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008304 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008305 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008306 final String processName = app == null ? "system_server"
8307 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008308
8309 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008310 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008311 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008312 tag, crashInfo.exceptionMessage);
8313
Jeff Sharkeya353d262011-10-28 11:12:06 -07008314 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008315
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008316 if (r != null && r.pid != Process.myPid() &&
8317 Settings.Secure.getInt(mContext.getContentResolver(),
8318 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008319 crashApplication(r, crashInfo);
8320 return true;
8321 } else {
8322 return false;
8323 }
8324 }
8325
8326 /**
8327 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8328 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8329 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008330 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008331 if (app == null) {
8332 return null;
8333 }
8334
8335 synchronized (this) {
8336 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8337 final int NA = apps.size();
8338 for (int ia=0; ia<NA; ia++) {
8339 ProcessRecord p = apps.valueAt(ia);
8340 if (p.thread != null && p.thread.asBinder() == app) {
8341 return p;
8342 }
8343 }
8344 }
8345
Dianne Hackborncb44d962011-03-10 17:02:27 -08008346 Slog.w(TAG, "Can't find mystery application for " + reason
8347 + " from pid=" + Binder.getCallingPid()
8348 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008349 return null;
8350 }
8351 }
8352
8353 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008354 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8355 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008356 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008357 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8358 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008359 // Watchdog thread ends up invoking this function (with
8360 // a null ProcessRecord) to add the stack file to dropbox.
8361 // Do not acquire a lock on this (am) in such cases, as it
8362 // could cause a potential deadlock, if and when watchdog
8363 // is invoked due to unavailability of lock on am and it
8364 // would prevent watchdog from killing system_server.
8365 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008366 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008367 return;
8368 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008369 // Note: ProcessRecord 'process' is guarded by the service
8370 // instance. (notably process.pkgList, which could otherwise change
8371 // concurrently during execution of this method)
8372 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008373 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008374 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008375 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008376 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8377 for (String pkg : process.pkgList) {
8378 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008379 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008380 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008381 if (pi != null) {
8382 sb.append(" v").append(pi.versionCode);
8383 if (pi.versionName != null) {
8384 sb.append(" (").append(pi.versionName).append(")");
8385 }
8386 }
8387 } catch (RemoteException e) {
8388 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008389 }
Dan Egnora455d192010-03-12 08:52:28 -08008390 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008391 }
Dan Egnora455d192010-03-12 08:52:28 -08008392 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008393 }
8394
8395 private static String processClass(ProcessRecord process) {
8396 if (process == null || process.pid == MY_PID) {
8397 return "system_server";
8398 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8399 return "system_app";
8400 } else {
8401 return "data_app";
8402 }
8403 }
8404
8405 /**
8406 * Write a description of an error (crash, WTF, ANR) to the drop box.
8407 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8408 * @param process which caused the error, null means the system server
8409 * @param activity which triggered the error, null if unknown
8410 * @param parent activity related to the error, null if unknown
8411 * @param subject line related to the error, null if absent
8412 * @param report in long form describing the error, null if absent
8413 * @param logFile to include in the report, null if none
8414 * @param crashInfo giving an application stack trace, null if absent
8415 */
8416 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008417 ProcessRecord process, String processName, ActivityRecord activity,
8418 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008419 final String report, final File logFile,
8420 final ApplicationErrorReport.CrashInfo crashInfo) {
8421 // NOTE -- this must never acquire the ActivityManagerService lock,
8422 // otherwise the watchdog may be prevented from resetting the system.
8423
8424 final String dropboxTag = processClass(process) + "_" + eventType;
8425 final DropBoxManager dbox = (DropBoxManager)
8426 mContext.getSystemService(Context.DROPBOX_SERVICE);
8427
8428 // Exit early if the dropbox isn't configured to accept this report type.
8429 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8430
8431 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008432 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008433 if (activity != null) {
8434 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8435 }
8436 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8437 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8438 }
8439 if (parent != null && parent != activity) {
8440 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8441 }
8442 if (subject != null) {
8443 sb.append("Subject: ").append(subject).append("\n");
8444 }
8445 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008446 if (Debug.isDebuggerConnected()) {
8447 sb.append("Debugger: Connected\n");
8448 }
Dan Egnora455d192010-03-12 08:52:28 -08008449 sb.append("\n");
8450
8451 // Do the rest in a worker thread to avoid blocking the caller on I/O
8452 // (After this point, we shouldn't access AMS internal data structures.)
8453 Thread worker = new Thread("Error dump: " + dropboxTag) {
8454 @Override
8455 public void run() {
8456 if (report != null) {
8457 sb.append(report);
8458 }
8459 if (logFile != null) {
8460 try {
8461 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8462 } catch (IOException e) {
8463 Slog.e(TAG, "Error reading " + logFile, e);
8464 }
8465 }
8466 if (crashInfo != null && crashInfo.stackTrace != null) {
8467 sb.append(crashInfo.stackTrace);
8468 }
8469
8470 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8471 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8472 if (lines > 0) {
8473 sb.append("\n");
8474
8475 // Merge several logcat streams, and take the last N lines
8476 InputStreamReader input = null;
8477 try {
8478 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8479 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8480 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8481
8482 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8483 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8484 input = new InputStreamReader(logcat.getInputStream());
8485
8486 int num;
8487 char[] buf = new char[8192];
8488 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8489 } catch (IOException e) {
8490 Slog.e(TAG, "Error running logcat", e);
8491 } finally {
8492 if (input != null) try { input.close(); } catch (IOException e) {}
8493 }
8494 }
8495
8496 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008497 }
Dan Egnora455d192010-03-12 08:52:28 -08008498 };
8499
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008500 if (process == null) {
8501 // If process is null, we are being called from some internal code
8502 // and may be about to die -- run this synchronously.
8503 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008504 } else {
8505 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008506 }
8507 }
8508
8509 /**
8510 * Bring up the "unexpected error" dialog box for a crashing app.
8511 * Deal with edge cases (intercepts from instrumented applications,
8512 * ActivityController, error intent receivers, that sort of thing).
8513 * @param r the application crashing
8514 * @param crashInfo describing the failure
8515 */
8516 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008517 long timeMillis = System.currentTimeMillis();
8518 String shortMsg = crashInfo.exceptionClassName;
8519 String longMsg = crashInfo.exceptionMessage;
8520 String stackTrace = crashInfo.stackTrace;
8521 if (shortMsg != null && longMsg != null) {
8522 longMsg = shortMsg + ": " + longMsg;
8523 } else if (shortMsg != null) {
8524 longMsg = shortMsg;
8525 }
8526
Dan Egnor60d87622009-12-16 16:32:58 -08008527 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008529 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 try {
8531 String name = r != null ? r.processName : null;
8532 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008533 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008534 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008535 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 + " at watcher's request");
8537 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008538 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 }
8540 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008541 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 }
8543 }
8544
8545 final long origId = Binder.clearCallingIdentity();
8546
8547 // If this process is running instrumentation, finish it.
8548 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008549 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008551 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8552 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 Bundle info = new Bundle();
8554 info.putString("shortMsg", shortMsg);
8555 info.putString("longMsg", longMsg);
8556 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8557 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008558 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 }
8560
Dan Egnor60d87622009-12-16 16:32:58 -08008561 // If we can't identify the process or it's already exceeded its crash quota,
8562 // quit right away without showing a crash dialog.
8563 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008565 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 }
8567
8568 Message msg = Message.obtain();
8569 msg.what = SHOW_ERROR_MSG;
8570 HashMap data = new HashMap();
8571 data.put("result", result);
8572 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 msg.obj = data;
8574 mHandler.sendMessage(msg);
8575
8576 Binder.restoreCallingIdentity(origId);
8577 }
8578
8579 int res = result.get();
8580
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008581 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008583 if (r != null && !r.isolated) {
8584 // XXX Can't keep track of crash time for isolated processes,
8585 // since they don't have a persistent identity.
8586 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 SystemClock.uptimeMillis());
8588 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008589 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008590 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008591 }
8592 }
8593
8594 if (appErrorIntent != null) {
8595 try {
8596 mContext.startActivity(appErrorIntent);
8597 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008598 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008602
8603 Intent createAppErrorIntentLocked(ProcessRecord r,
8604 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8605 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008606 if (report == null) {
8607 return null;
8608 }
8609 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8610 result.setComponent(r.errorReportReceiver);
8611 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8612 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8613 return result;
8614 }
8615
Dan Egnorb7f03672009-12-09 16:22:32 -08008616 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8617 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008618 if (r.errorReportReceiver == null) {
8619 return null;
8620 }
8621
8622 if (!r.crashing && !r.notResponding) {
8623 return null;
8624 }
8625
Dan Egnorb7f03672009-12-09 16:22:32 -08008626 ApplicationErrorReport report = new ApplicationErrorReport();
8627 report.packageName = r.info.packageName;
8628 report.installerPackageName = r.errorReportReceiver.getPackageName();
8629 report.processName = r.processName;
8630 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008631 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008632
Dan Egnorb7f03672009-12-09 16:22:32 -08008633 if (r.crashing) {
8634 report.type = ApplicationErrorReport.TYPE_CRASH;
8635 report.crashInfo = crashInfo;
8636 } else if (r.notResponding) {
8637 report.type = ApplicationErrorReport.TYPE_ANR;
8638 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008639
Dan Egnorb7f03672009-12-09 16:22:32 -08008640 report.anrInfo.activity = r.notRespondingReport.tag;
8641 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8642 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008643 }
8644
Dan Egnorb7f03672009-12-09 16:22:32 -08008645 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008646 }
8647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008649 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 // assume our apps are happy - lazy create the list
8651 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8652
Dianne Hackborn0c380492012-08-20 17:23:30 -07008653 final boolean allUsers = ActivityManager.checkUidPermission(
8654 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8655 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8656 int userId = UserHandle.getUserId(Binder.getCallingUid());
8657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 synchronized (this) {
8659
8660 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008661 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8662 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008663 if (!allUsers && app.userId != userId) {
8664 continue;
8665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8667 // This one's in trouble, so we'll generate a report for it
8668 // crashes are higher priority (in case there's a crash *and* an anr)
8669 ActivityManager.ProcessErrorStateInfo report = null;
8670 if (app.crashing) {
8671 report = app.crashingReport;
8672 } else if (app.notResponding) {
8673 report = app.notRespondingReport;
8674 }
8675
8676 if (report != null) {
8677 if (errList == null) {
8678 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8679 }
8680 errList.add(report);
8681 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008682 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 " crashing = " + app.crashing +
8684 " notResponding = " + app.notResponding);
8685 }
8686 }
8687 }
8688 }
8689
8690 return errList;
8691 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008692
8693 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008694 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008695 if (currApp != null) {
8696 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8697 }
8698 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008699 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8700 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008701 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8702 if (currApp != null) {
8703 currApp.lru = 0;
8704 }
8705 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008706 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008707 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8708 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8709 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8710 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8711 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8712 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8713 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8714 } else {
8715 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8716 }
8717 }
8718
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008719 private void fillInProcMemInfo(ProcessRecord app,
8720 ActivityManager.RunningAppProcessInfo outInfo) {
8721 outInfo.pid = app.pid;
8722 outInfo.uid = app.info.uid;
8723 if (mHeavyWeightProcess == app) {
8724 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8725 }
8726 if (app.persistent) {
8727 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8728 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008729 if (app.hasActivities) {
8730 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8731 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008732 outInfo.lastTrimLevel = app.trimMemoryLevel;
8733 int adj = app.curAdj;
8734 outInfo.importance = oomAdjToImportance(adj, outInfo);
8735 outInfo.importanceReasonCode = app.adjTypeCode;
8736 }
8737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008739 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008740 // Lazy instantiation of list
8741 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008742 final boolean allUsers = ActivityManager.checkUidPermission(
8743 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8744 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8745 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 synchronized (this) {
8747 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008748 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8749 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008750 if (!allUsers && app.userId != userId) {
8751 continue;
8752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8754 // Generate process state info for running application
8755 ActivityManager.RunningAppProcessInfo currApp =
8756 new ActivityManager.RunningAppProcessInfo(app.processName,
8757 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008758 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008759 if (app.adjSource instanceof ProcessRecord) {
8760 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008761 currApp.importanceReasonImportance = oomAdjToImportance(
8762 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008763 } else if (app.adjSource instanceof ActivityRecord) {
8764 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008765 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8766 }
8767 if (app.adjTarget instanceof ComponentName) {
8768 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8769 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008770 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 // + " lru=" + currApp.lru);
8772 if (runList == null) {
8773 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8774 }
8775 runList.add(currApp);
8776 }
8777 }
8778 }
8779 return runList;
8780 }
8781
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008782 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008783 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008784 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8785 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8786 if (runningApps != null && runningApps.size() > 0) {
8787 Set<String> extList = new HashSet<String>();
8788 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8789 if (app.pkgList != null) {
8790 for (String pkg : app.pkgList) {
8791 extList.add(pkg);
8792 }
8793 }
8794 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008795 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008796 for (String pkg : extList) {
8797 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008798 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008799 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8800 retList.add(info);
8801 }
8802 } catch (RemoteException e) {
8803 }
8804 }
8805 }
8806 return retList;
8807 }
8808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008810 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8811 enforceNotIsolatedCaller("getMyMemoryState");
8812 synchronized (this) {
8813 ProcessRecord proc;
8814 synchronized (mPidsSelfLocked) {
8815 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8816 }
8817 fillInProcMemInfo(proc, outInfo);
8818 }
8819 }
8820
8821 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008823 if (checkCallingPermission(android.Manifest.permission.DUMP)
8824 != PackageManager.PERMISSION_GRANTED) {
8825 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8826 + Binder.getCallingPid()
8827 + ", uid=" + Binder.getCallingUid()
8828 + " without permission "
8829 + android.Manifest.permission.DUMP);
8830 return;
8831 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008832
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008833 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008834 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008835 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008836
8837 int opti = 0;
8838 while (opti < args.length) {
8839 String opt = args[opti];
8840 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8841 break;
8842 }
8843 opti++;
8844 if ("-a".equals(opt)) {
8845 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008846 } else if ("-c".equals(opt)) {
8847 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 } else if ("-h".equals(opt)) {
8849 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008850 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008852 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008853 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8854 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8855 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008856 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008857 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008858 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008859 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008860 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008861 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008862 pw.println(" all: dump all activities");
8863 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008864 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008865 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8866 pw.println(" a partial substring in a component name, a");
8867 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008868 pw.println(" -a: include all available server state.");
8869 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008871 } else {
8872 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008874 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008875
8876 long origId = Binder.clearCallingIdentity();
8877 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008878 // Is the caller requesting to dump a particular piece of data?
8879 if (opti < args.length) {
8880 String cmd = args[opti];
8881 opti++;
8882 if ("activities".equals(cmd) || "a".equals(cmd)) {
8883 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008884 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008886 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008887 String[] newArgs;
8888 String name;
8889 if (opti >= args.length) {
8890 name = null;
8891 newArgs = EMPTY_STRING_ARRAY;
8892 } else {
8893 name = args[opti];
8894 opti++;
8895 newArgs = new String[args.length - opti];
8896 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8897 args.length - opti);
8898 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008899 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008900 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008901 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008902 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008903 String[] newArgs;
8904 String name;
8905 if (opti >= args.length) {
8906 name = null;
8907 newArgs = EMPTY_STRING_ARRAY;
8908 } else {
8909 name = args[opti];
8910 opti++;
8911 newArgs = new String[args.length - opti];
8912 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8913 args.length - opti);
8914 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008915 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008916 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008917 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008918 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008919 String[] newArgs;
8920 String name;
8921 if (opti >= args.length) {
8922 name = null;
8923 newArgs = EMPTY_STRING_ARRAY;
8924 } else {
8925 name = args[opti];
8926 opti++;
8927 newArgs = new String[args.length - opti];
8928 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8929 args.length - opti);
8930 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008931 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008932 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008933 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008934 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8935 synchronized (this) {
8936 dumpOomLocked(fd, pw, args, opti, true);
8937 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008938 } else if ("provider".equals(cmd)) {
8939 String[] newArgs;
8940 String name;
8941 if (opti >= args.length) {
8942 name = null;
8943 newArgs = EMPTY_STRING_ARRAY;
8944 } else {
8945 name = args[opti];
8946 opti++;
8947 newArgs = new String[args.length - opti];
8948 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8949 }
8950 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8951 pw.println("No providers match: " + name);
8952 pw.println("Use -h for help.");
8953 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008954 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8955 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008956 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008957 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008958 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008959 String[] newArgs;
8960 String name;
8961 if (opti >= args.length) {
8962 name = null;
8963 newArgs = EMPTY_STRING_ARRAY;
8964 } else {
8965 name = args[opti];
8966 opti++;
8967 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008968 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8969 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008970 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008971 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008972 pw.println("No services match: " + name);
8973 pw.println("Use -h for help.");
8974 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 } else if ("package".equals(cmd)) {
8976 String[] newArgs;
8977 if (opti >= args.length) {
8978 pw.println("package: no package name specified");
8979 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008980 } else {
8981 dumpPackage = args[opti];
8982 opti++;
8983 newArgs = new String[args.length - opti];
8984 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8985 args.length - opti);
8986 args = newArgs;
8987 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008988 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008989 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8991 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008992 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008993 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008994 } else {
8995 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008996 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8997 pw.println("Bad activity command, or no activities match: " + cmd);
8998 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008999 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009000 }
9001 if (!more) {
9002 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009003 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009005 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009006
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009007 // No piece of data specified, dump everything.
9008 synchronized (this) {
9009 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009010 needSep = dumpPendingIntentsLocked(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 = dumpBroadcastsLocked(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 Hackbornee9aef02011-11-16 13:21:46 -08009024 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, 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 Hackborn599db5c2012-08-03 19:28:48 -07009031 needSep = mServices.dumpServicesLocked(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 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009039 if (needSep) {
9040 pw.println(" ");
9041 }
9042 if (dumpAll) {
9043 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009044 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009045 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009047 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009048 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009049
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009050 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009052 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9053 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009054 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9055 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009056 pw.println(" ");
9057 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009058 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9059 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009060 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009064 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009065 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009066 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009069 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009071 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009072 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9073 pw.println(" ");
9074 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009075 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009076 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009077 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009078 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009079 pw.println(" ");
9080 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009081 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009082 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009086 if (mMainStack.mPausingActivity != null) {
9087 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009088 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009089 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009090 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009091 if (dumpAll) {
9092 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9093 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009094 pw.println(" mDismissKeyguardOnNextActivity: "
9095 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009098 if (mRecentTasks.size() > 0) {
9099 pw.println();
9100 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101
9102 final int N = mRecentTasks.size();
9103 for (int i=0; i<N; i++) {
9104 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009105 if (dumpPackage != null) {
9106 if (tr.realActivity == null ||
9107 !dumpPackage.equals(tr.realActivity)) {
9108 continue;
9109 }
9110 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009111 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9112 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009113 if (dumpAll) {
9114 mRecentTasks.get(i).dump(pw, " ");
9115 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009116 }
9117 }
9118
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009119 if (dumpAll) {
9120 pw.println(" ");
9121 pw.println(" mCurTask: " + mCurTask);
9122 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009123
9124 return true;
9125 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009126
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009128 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009129 boolean needSep = false;
9130 int numPers = 0;
9131
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009132 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9133
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009134 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009135 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9136 final int NA = procs.size();
9137 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009138 ProcessRecord r = procs.valueAt(ia);
9139 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9140 continue;
9141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 if (!needSep) {
9143 pw.println(" All known processes:");
9144 needSep = true;
9145 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009146 pw.print(r.persistent ? " *PERS*" : " *APP*");
9147 pw.print(" UID "); pw.print(procs.keyAt(ia));
9148 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 r.dump(pw, " ");
9150 if (r.persistent) {
9151 numPers++;
9152 }
9153 }
9154 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009155 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009156
9157 if (mIsolatedProcesses.size() > 0) {
9158 if (needSep) pw.println(" ");
9159 needSep = true;
9160 pw.println(" Isolated process list (sorted by uid):");
9161 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9162 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9163 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9164 continue;
9165 }
9166 pw.println(String.format("%sIsolated #%2d: %s",
9167 " ", i, r.toString()));
9168 }
9169 }
9170
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009171 if (mLruProcesses.size() > 0) {
9172 if (needSep) pw.println(" ");
9173 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009174 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009175 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009176 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177 needSep = true;
9178 }
9179
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009180 if (dumpAll) {
9181 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009182 boolean printed = false;
9183 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9184 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9185 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9186 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009187 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009188 if (!printed) {
9189 if (needSep) pw.println(" ");
9190 needSep = true;
9191 pw.println(" PID mappings:");
9192 printed = true;
9193 }
9194 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9195 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196 }
9197 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009198 }
9199
9200 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009201 synchronized (mPidsSelfLocked) {
9202 boolean printed = false;
9203 for (int i=0; i<mForegroundProcesses.size(); i++) {
9204 ProcessRecord r = mPidsSelfLocked.get(
9205 mForegroundProcesses.valueAt(i).pid);
9206 if (dumpPackage != null && (r == null
9207 || !dumpPackage.equals(r.info.packageName))) {
9208 continue;
9209 }
9210 if (!printed) {
9211 if (needSep) pw.println(" ");
9212 needSep = true;
9213 pw.println(" Foreground Processes:");
9214 printed = true;
9215 }
9216 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9217 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220 }
9221
9222 if (mPersistentStartingProcesses.size() > 0) {
9223 if (needSep) pw.println(" ");
9224 needSep = true;
9225 pw.println(" Persisent processes that are starting:");
9226 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009227 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009229
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009230 if (mRemovedProcesses.size() > 0) {
9231 if (needSep) pw.println(" ");
9232 needSep = true;
9233 pw.println(" Processes that are being removed:");
9234 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009235 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009236 }
9237
9238 if (mProcessesOnHold.size() > 0) {
9239 if (needSep) pw.println(" ");
9240 needSep = true;
9241 pw.println(" Processes that are on old until the system is ready:");
9242 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009243 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009246 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009247
9248 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009249 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009250 long now = SystemClock.uptimeMillis();
9251 for (Map.Entry<String, SparseArray<Long>> procs
9252 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009253 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009254 SparseArray<Long> uids = procs.getValue();
9255 final int N = uids.size();
9256 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009257 int puid = uids.keyAt(i);
9258 ProcessRecord r = mProcessNames.get(pname, puid);
9259 if (dumpPackage != null && (r == null
9260 || !dumpPackage.equals(r.info.packageName))) {
9261 continue;
9262 }
9263 if (!printed) {
9264 if (needSep) pw.println(" ");
9265 needSep = true;
9266 pw.println(" Time since processes crashed:");
9267 printed = true;
9268 }
9269 pw.print(" Process "); pw.print(pname);
9270 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009271 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009272 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9273 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009274 }
9275 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009278 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009279 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009280 for (Map.Entry<String, SparseArray<Long>> procs
9281 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009282 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283 SparseArray<Long> uids = procs.getValue();
9284 final int N = uids.size();
9285 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009286 int puid = uids.keyAt(i);
9287 ProcessRecord r = mProcessNames.get(pname, puid);
9288 if (dumpPackage != null && (r == null
9289 || !dumpPackage.equals(r.info.packageName))) {
9290 continue;
9291 }
9292 if (!printed) {
9293 if (needSep) pw.println(" ");
9294 needSep = true;
9295 pw.println(" Bad processes:");
9296 }
9297 pw.print(" Bad process "); pw.print(pname);
9298 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009299 pw.print(": crashed at time ");
9300 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301 }
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009304
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009305 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009306 pw.println(" mStartedUsers:");
9307 for (int i=0; i<mStartedUsers.size(); i++) {
9308 UserStartedState uss = mStartedUsers.valueAt(i);
9309 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009310 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009311 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009312 pw.print(" mUserLru: [");
9313 for (int i=0; i<mUserLru.size(); i++) {
9314 if (i > 0) pw.print(", ");
9315 pw.print(mUserLru.get(i));
9316 }
9317 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009318 if (dumpAll) {
9319 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9320 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009321 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009322 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009323 if (dumpAll) {
9324 StringBuilder sb = new StringBuilder(128);
9325 sb.append(" mPreviousProcessVisibleTime: ");
9326 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9327 pw.println(sb);
9328 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009329 if (mHeavyWeightProcess != null) {
9330 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9331 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009332 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009333 if (dumpAll) {
9334 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009335 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009336 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009337 for (Map.Entry<String, Integer> entry
9338 : mCompatModePackages.getPackages().entrySet()) {
9339 String pkg = entry.getKey();
9340 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009341 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9342 continue;
9343 }
9344 if (!printed) {
9345 pw.println(" mScreenCompatPackages:");
9346 printed = true;
9347 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009348 pw.print(" "); pw.print(pkg); pw.print(": ");
9349 pw.print(mode); pw.println();
9350 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009351 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009352 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009353 if (mSleeping || mWentToSleep || mLockScreenShown) {
9354 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9355 + " mLockScreenShown " + mLockScreenShown);
9356 }
9357 if (mShuttingDown) {
9358 pw.println(" mShuttingDown=" + mShuttingDown);
9359 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009360 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9361 || mOrigWaitForDebugger) {
9362 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9363 + " mDebugTransient=" + mDebugTransient
9364 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9365 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009366 if (mOpenGlTraceApp != null) {
9367 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9368 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009369 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9370 || mProfileFd != null) {
9371 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9372 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9373 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9374 + mAutoStopProfiler);
9375 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009376 if (mAlwaysFinishActivities || mController != null) {
9377 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9378 + " mController=" + mController);
9379 }
9380 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009383 + " mProcessesReady=" + mProcessesReady
9384 + " mSystemReady=" + mSystemReady);
9385 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009386 + " mBooted=" + mBooted
9387 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009388 pw.print(" mLastPowerCheckRealtime=");
9389 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9390 pw.println("");
9391 pw.print(" mLastPowerCheckUptime=");
9392 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9393 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009394 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9395 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009396 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009397 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9398 + " mNumHiddenProcs=" + mNumHiddenProcs
9399 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009400 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402
9403 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404 }
9405
Dianne Hackborn287952c2010-09-22 22:34:31 -07009406 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009407 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009408 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009409 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009410 long now = SystemClock.uptimeMillis();
9411 for (int i=0; i<mProcessesToGc.size(); i++) {
9412 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009413 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9414 continue;
9415 }
9416 if (!printed) {
9417 if (needSep) pw.println(" ");
9418 needSep = true;
9419 pw.println(" Processes that are waiting to GC:");
9420 printed = true;
9421 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009422 pw.print(" Process "); pw.println(proc);
9423 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9424 pw.print(", last gced=");
9425 pw.print(now-proc.lastRequestedGc);
9426 pw.print(" ms ago, last lowMem=");
9427 pw.print(now-proc.lastLowMemory);
9428 pw.println(" ms ago");
9429
9430 }
9431 }
9432 return needSep;
9433 }
9434
9435 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9436 int opti, boolean dumpAll) {
9437 boolean needSep = false;
9438
9439 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009440 if (needSep) pw.println(" ");
9441 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009442 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009443 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009444 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009445 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9446 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9447 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9448 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9449 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009450 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009451 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009452 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009453 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009454 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009455 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009456
9457 if (needSep) pw.println(" ");
9458 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009459 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009460 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009462 needSep = true;
9463 }
9464
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009465 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009466
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009467 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009468 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009469 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009470 if (mHeavyWeightProcess != null) {
9471 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9472 }
9473
9474 return true;
9475 }
9476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009477 /**
9478 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009479 * - no provider specified: dump all the providers
9480 * - a flattened component name that matched an existing provider was specified as the
9481 * first arg: dump that one provider
9482 * - the first arg isn't the flattened component name of an existing provider:
9483 * dump all providers whose component contains the first arg as a substring
9484 */
9485 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9486 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009487 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009488 }
9489
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009490 static class ItemMatcher {
9491 ArrayList<ComponentName> components;
9492 ArrayList<String> strings;
9493 ArrayList<Integer> objects;
9494 boolean all;
9495
9496 ItemMatcher() {
9497 all = true;
9498 }
9499
9500 void build(String name) {
9501 ComponentName componentName = ComponentName.unflattenFromString(name);
9502 if (componentName != null) {
9503 if (components == null) {
9504 components = new ArrayList<ComponentName>();
9505 }
9506 components.add(componentName);
9507 all = false;
9508 } else {
9509 int objectId = 0;
9510 // Not a '/' separated full component name; maybe an object ID?
9511 try {
9512 objectId = Integer.parseInt(name, 16);
9513 if (objects == null) {
9514 objects = new ArrayList<Integer>();
9515 }
9516 objects.add(objectId);
9517 all = false;
9518 } catch (RuntimeException e) {
9519 // Not an integer; just do string match.
9520 if (strings == null) {
9521 strings = new ArrayList<String>();
9522 }
9523 strings.add(name);
9524 all = false;
9525 }
9526 }
9527 }
9528
9529 int build(String[] args, int opti) {
9530 for (; opti<args.length; opti++) {
9531 String name = args[opti];
9532 if ("--".equals(name)) {
9533 return opti+1;
9534 }
9535 build(name);
9536 }
9537 return opti;
9538 }
9539
9540 boolean match(Object object, ComponentName comp) {
9541 if (all) {
9542 return true;
9543 }
9544 if (components != null) {
9545 for (int i=0; i<components.size(); i++) {
9546 if (components.get(i).equals(comp)) {
9547 return true;
9548 }
9549 }
9550 }
9551 if (objects != null) {
9552 for (int i=0; i<objects.size(); i++) {
9553 if (System.identityHashCode(object) == objects.get(i)) {
9554 return true;
9555 }
9556 }
9557 }
9558 if (strings != null) {
9559 String flat = comp.flattenToString();
9560 for (int i=0; i<strings.size(); i++) {
9561 if (flat.contains(strings.get(i))) {
9562 return true;
9563 }
9564 }
9565 }
9566 return false;
9567 }
9568 }
9569
Dianne Hackborn625ac272010-09-17 18:29:22 -07009570 /**
9571 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009572 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009573 * - the cmd arg isn't the flattened component name of an existing activity:
9574 * dump all activity whose component contains the cmd as a substring
9575 * - A hex number of the ActivityRecord object instance.
9576 */
9577 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9578 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009579 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009580
9581 if ("all".equals(name)) {
9582 synchronized (this) {
9583 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009584 activities.add(r1);
9585 }
9586 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009587 } else if ("top".equals(name)) {
9588 synchronized (this) {
9589 final int N = mMainStack.mHistory.size();
9590 if (N > 0) {
9591 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9592 }
9593 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009594 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009595 ItemMatcher matcher = new ItemMatcher();
9596 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009597
9598 synchronized (this) {
9599 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009600 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009601 activities.add(r1);
9602 }
9603 }
9604 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009605 }
9606
9607 if (activities.size() <= 0) {
9608 return false;
9609 }
9610
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009611 String[] newArgs = new String[args.length - opti];
9612 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9613
Dianne Hackborn30d71892010-12-11 10:37:55 -08009614 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009615 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009616 for (int i=activities.size()-1; i>=0; i--) {
9617 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009618 if (needSep) {
9619 pw.println();
9620 }
9621 needSep = true;
9622 synchronized (this) {
9623 if (lastTask != r.task) {
9624 lastTask = r.task;
9625 pw.print("TASK "); pw.print(lastTask.affinity);
9626 pw.print(" id="); pw.println(lastTask.taskId);
9627 if (dumpAll) {
9628 lastTask.dump(pw, " ");
9629 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009630 }
9631 }
9632 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009633 }
9634 return true;
9635 }
9636
9637 /**
9638 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9639 * there is a thread associated with the activity.
9640 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009641 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009642 final ActivityRecord r, String[] args, boolean dumpAll) {
9643 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009644 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009645 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9646 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9647 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009648 if (r.app != null) pw.println(r.app.pid);
9649 else pw.println("(not running)");
9650 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009651 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009652 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009653 }
9654 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009655 // flush anything that is already in the PrintWriter since the thread is going
9656 // to write to the file descriptor directly
9657 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009658 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009659 TransferPipe tp = new TransferPipe();
9660 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009661 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9662 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009663 tp.go(fd);
9664 } finally {
9665 tp.kill();
9666 }
9667 } catch (IOException e) {
9668 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009669 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009670 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009671 }
9672 }
9673 }
9674
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009675 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009676 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009677 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009678 boolean onlyHistory = false;
9679
9680 if ("history".equals(dumpPackage)) {
9681 onlyHistory = true;
9682 dumpPackage = null;
9683 }
9684
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009685 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009686 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009687 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009688 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 Iterator it = mRegisteredReceivers.values().iterator();
9690 while (it.hasNext()) {
9691 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009692 if (dumpPackage != null && (r.app == null ||
9693 !dumpPackage.equals(r.app.info.packageName))) {
9694 continue;
9695 }
9696 if (!printed) {
9697 pw.println(" Registered Receivers:");
9698 needSep = true;
9699 printed = true;
9700 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009701 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702 r.dump(pw, " ");
9703 }
9704 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009705
9706 if (mReceiverResolver.dump(pw, needSep ?
9707 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9708 " ", dumpPackage, false)) {
9709 needSep = true;
9710 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009711 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009712
9713 for (BroadcastQueue q : mBroadcastQueues) {
9714 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009716
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009717 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009718
Dianne Hackborn786b4402012-08-27 15:14:02 -07009719 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009720 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9721 if (needSep) {
9722 pw.println();
9723 }
9724 needSep = true;
9725 pw.print(" Sticky broadcasts for user ");
9726 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9727 StringBuilder sb = new StringBuilder(128);
9728 for (Map.Entry<String, ArrayList<Intent>> ent
9729 : mStickyBroadcasts.valueAt(user).entrySet()) {
9730 pw.print(" * Sticky action "); pw.print(ent.getKey());
9731 if (dumpAll) {
9732 pw.println(":");
9733 ArrayList<Intent> intents = ent.getValue();
9734 final int N = intents.size();
9735 for (int i=0; i<N; i++) {
9736 sb.setLength(0);
9737 sb.append(" Intent: ");
9738 intents.get(i).toShortString(sb, false, true, false, false);
9739 pw.println(sb.toString());
9740 Bundle bundle = intents.get(i).getExtras();
9741 if (bundle != null) {
9742 pw.print(" ");
9743 pw.println(bundle.toString());
9744 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009745 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009746 } else {
9747 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009748 }
9749 }
9750 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009751 }
9752
Dianne Hackborn786b4402012-08-27 15:14:02 -07009753 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009754 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009755 for (BroadcastQueue queue : mBroadcastQueues) {
9756 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9757 + queue.mBroadcastsScheduled);
9758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009759 pw.println(" mHandler:");
9760 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009761 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009762 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009763
9764 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009765 }
9766
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009767 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009768 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009769 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009770
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009771 ItemMatcher matcher = new ItemMatcher();
9772 matcher.build(args, opti);
9773
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009774 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009775
9776 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009777
9778 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009779 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009780 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009781 ContentProviderRecord r = mLaunchingProviders.get(i);
9782 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9783 continue;
9784 }
9785 if (!printed) {
9786 if (needSep) pw.println(" ");
9787 needSep = true;
9788 pw.println(" Launching content providers:");
9789 printed = true;
9790 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009791 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009792 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009793 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009794 }
9795
9796 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009797 if (needSep) pw.println();
9798 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009799 pw.println("Granted Uri Permissions:");
9800 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9801 int uid = mGrantedUriPermissions.keyAt(i);
9802 HashMap<Uri, UriPermission> perms
9803 = mGrantedUriPermissions.valueAt(i);
9804 pw.print(" * UID "); pw.print(uid);
9805 pw.println(" holds:");
9806 for (UriPermission perm : perms.values()) {
9807 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009808 if (dumpAll) {
9809 perm.dump(pw, " ");
9810 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009811 }
9812 }
9813 needSep = true;
9814 }
9815
9816 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009817 }
9818
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009819 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009820 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009821 boolean needSep = false;
9822
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009823 if (mIntentSenderRecords.size() > 0) {
9824 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009825 Iterator<WeakReference<PendingIntentRecord>> it
9826 = mIntentSenderRecords.values().iterator();
9827 while (it.hasNext()) {
9828 WeakReference<PendingIntentRecord> ref = it.next();
9829 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009830 if (dumpPackage != null && (rec == null
9831 || !dumpPackage.equals(rec.key.packageName))) {
9832 continue;
9833 }
9834 if (!printed) {
9835 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9836 printed = true;
9837 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009838 needSep = true;
9839 if (rec != null) {
9840 pw.print(" * "); pw.println(rec);
9841 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009842 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009843 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009844 } else {
9845 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009846 }
9847 }
9848 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009849
9850 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009851 }
9852
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009853 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009854 String prefix, String label, boolean complete, boolean brief, boolean client,
9855 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009856 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009857 boolean needNL = false;
9858 final String innerPrefix = prefix + " ";
9859 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009860 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009861 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009862 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9863 continue;
9864 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009865 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009866 if (needNL) {
9867 pw.println(" ");
9868 needNL = false;
9869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 if (lastTask != r.task) {
9871 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009872 pw.print(prefix);
9873 pw.print(full ? "* " : " ");
9874 pw.println(lastTask);
9875 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009876 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009877 } else if (complete) {
9878 // Complete + brief == give a summary. Isn't that obvious?!?
9879 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009880 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009881 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009882 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009884 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009885 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9886 pw.print(" #"); pw.print(i); pw.print(": ");
9887 pw.println(r);
9888 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009889 r.dump(pw, innerPrefix);
9890 } else if (complete) {
9891 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009892 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009893 if (r.app != null) {
9894 pw.print(innerPrefix); pw.println(r.app);
9895 }
9896 }
9897 if (client && r.app != null && r.app.thread != null) {
9898 // flush anything that is already in the PrintWriter since the thread is going
9899 // to write to the file descriptor directly
9900 pw.flush();
9901 try {
9902 TransferPipe tp = new TransferPipe();
9903 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009904 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9905 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009906 // Short timeout, since blocking here can
9907 // deadlock with the application.
9908 tp.go(fd, 2000);
9909 } finally {
9910 tp.kill();
9911 }
9912 } catch (IOException e) {
9913 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9914 } catch (RemoteException e) {
9915 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9916 }
9917 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009919 }
9920 }
9921
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009922 private static String buildOomTag(String prefix, String space, int val, int base) {
9923 if (val == base) {
9924 if (space == null) return prefix;
9925 return prefix + " ";
9926 }
9927 return prefix + "+" + Integer.toString(val-base);
9928 }
9929
9930 private static final int dumpProcessList(PrintWriter pw,
9931 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009932 String prefix, String normalLabel, String persistentLabel,
9933 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009934 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009935 final int N = list.size()-1;
9936 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009937 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009938 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9939 continue;
9940 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009941 pw.println(String.format("%s%s #%2d: %s",
9942 prefix, (r.persistent ? persistentLabel : normalLabel),
9943 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009944 if (r.persistent) {
9945 numPers++;
9946 }
9947 }
9948 return numPers;
9949 }
9950
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009951 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009952 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009953 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009954 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009955
Dianne Hackborn905577f2011-09-07 18:31:28 -07009956 ArrayList<Pair<ProcessRecord, Integer>> list
9957 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9958 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009959 ProcessRecord r = origList.get(i);
9960 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9961 continue;
9962 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009963 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9964 }
9965
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009966 if (list.size() <= 0) {
9967 return false;
9968 }
9969
Dianne Hackborn905577f2011-09-07 18:31:28 -07009970 Comparator<Pair<ProcessRecord, Integer>> comparator
9971 = new Comparator<Pair<ProcessRecord, Integer>>() {
9972 @Override
9973 public int compare(Pair<ProcessRecord, Integer> object1,
9974 Pair<ProcessRecord, Integer> object2) {
9975 if (object1.first.setAdj != object2.first.setAdj) {
9976 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9977 }
9978 if (object1.second.intValue() != object2.second.intValue()) {
9979 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9980 }
9981 return 0;
9982 }
9983 };
9984
9985 Collections.sort(list, comparator);
9986
Dianne Hackborn287952c2010-09-22 22:34:31 -07009987 final long curRealtime = SystemClock.elapsedRealtime();
9988 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9989 final long curUptime = SystemClock.uptimeMillis();
9990 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9991
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009992 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009993 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009994 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009995 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009996 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009997 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9998 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009999 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10000 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010001 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10002 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010003 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10004 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010005 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010006 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010007 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10008 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10009 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10010 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10011 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10012 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10013 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10014 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010015 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10016 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010017 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10018 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010019 } else {
10020 oomAdj = Integer.toString(r.setAdj);
10021 }
10022 String schedGroup;
10023 switch (r.setSchedGroup) {
10024 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10025 schedGroup = "B";
10026 break;
10027 case Process.THREAD_GROUP_DEFAULT:
10028 schedGroup = "F";
10029 break;
10030 default:
10031 schedGroup = Integer.toString(r.setSchedGroup);
10032 break;
10033 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010034 String foreground;
10035 if (r.foregroundActivities) {
10036 foreground = "A";
10037 } else if (r.foregroundServices) {
10038 foreground = "S";
10039 } else {
10040 foreground = " ";
10041 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010042 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010043 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010044 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10045 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010046 if (r.adjSource != null || r.adjTarget != null) {
10047 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010048 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010049 if (r.adjTarget instanceof ComponentName) {
10050 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10051 } else if (r.adjTarget != null) {
10052 pw.print(r.adjTarget.toString());
10053 } else {
10054 pw.print("{null}");
10055 }
10056 pw.print("<=");
10057 if (r.adjSource instanceof ProcessRecord) {
10058 pw.print("Proc{");
10059 pw.print(((ProcessRecord)r.adjSource).toShortString());
10060 pw.println("}");
10061 } else if (r.adjSource != null) {
10062 pw.println(r.adjSource.toString());
10063 } else {
10064 pw.println("{null}");
10065 }
10066 }
10067 if (inclDetails) {
10068 pw.print(prefix);
10069 pw.print(" ");
10070 pw.print("oom: max="); pw.print(r.maxAdj);
10071 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010072 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010073 pw.print(" curRaw="); pw.print(r.curRawAdj);
10074 pw.print(" setRaw="); pw.print(r.setRawAdj);
10075 pw.print(" cur="); pw.print(r.curAdj);
10076 pw.print(" set="); pw.println(r.setAdj);
10077 pw.print(prefix);
10078 pw.print(" ");
10079 pw.print("keeping="); pw.print(r.keeping);
10080 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010081 pw.print(" empty="); pw.print(r.empty);
10082 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010083
10084 if (!r.keeping) {
10085 if (r.lastWakeTime != 0) {
10086 long wtime;
10087 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10088 synchronized (stats) {
10089 wtime = stats.getProcessWakeTime(r.info.uid,
10090 r.pid, curRealtime);
10091 }
10092 long timeUsed = wtime - r.lastWakeTime;
10093 pw.print(prefix);
10094 pw.print(" ");
10095 pw.print("keep awake over ");
10096 TimeUtils.formatDuration(realtimeSince, pw);
10097 pw.print(" used ");
10098 TimeUtils.formatDuration(timeUsed, pw);
10099 pw.print(" (");
10100 pw.print((timeUsed*100)/realtimeSince);
10101 pw.println("%)");
10102 }
10103 if (r.lastCpuTime != 0) {
10104 long timeUsed = r.curCpuTime - r.lastCpuTime;
10105 pw.print(prefix);
10106 pw.print(" ");
10107 pw.print("run cpu over ");
10108 TimeUtils.formatDuration(uptimeSince, pw);
10109 pw.print(" used ");
10110 TimeUtils.formatDuration(timeUsed, pw);
10111 pw.print(" (");
10112 pw.print((timeUsed*100)/uptimeSince);
10113 pw.println("%)");
10114 }
10115 }
10116 }
10117 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010118 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010119 }
10120
Dianne Hackbornb437e092011-08-05 17:50:29 -070010121 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010122 ArrayList<ProcessRecord> procs;
10123 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010124 if (args != null && args.length > start
10125 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010126 procs = new ArrayList<ProcessRecord>();
10127 int pid = -1;
10128 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010129 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010130 } catch (NumberFormatException e) {
10131
10132 }
10133 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10134 ProcessRecord proc = mLruProcesses.get(i);
10135 if (proc.pid == pid) {
10136 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010137 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010138 procs.add(proc);
10139 }
10140 }
10141 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010142 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010143 return null;
10144 }
10145 } else {
10146 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10147 }
10148 }
10149 return procs;
10150 }
10151
10152 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10153 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010154 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010155 if (procs == null) {
10156 return;
10157 }
10158
10159 long uptime = SystemClock.uptimeMillis();
10160 long realtime = SystemClock.elapsedRealtime();
10161 pw.println("Applications Graphics Acceleration Info:");
10162 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10163
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010164 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10165 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010166 if (r.thread != null) {
10167 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10168 pw.flush();
10169 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010170 TransferPipe tp = new TransferPipe();
10171 try {
10172 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10173 tp.go(fd);
10174 } finally {
10175 tp.kill();
10176 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010177 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010178 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010179 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010180 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010181 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010182 pw.flush();
10183 }
10184 }
10185 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010186 }
10187
Jeff Brown6754ba22011-12-14 20:20:01 -080010188 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10189 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10190 if (procs == null) {
10191 return;
10192 }
10193
10194 pw.println("Applications Database Info:");
10195
10196 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10197 ProcessRecord r = procs.get(i);
10198 if (r.thread != null) {
10199 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10200 pw.flush();
10201 try {
10202 TransferPipe tp = new TransferPipe();
10203 try {
10204 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10205 tp.go(fd);
10206 } finally {
10207 tp.kill();
10208 }
10209 } catch (IOException e) {
10210 pw.println("Failure while dumping the app: " + r);
10211 pw.flush();
10212 } catch (RemoteException e) {
10213 pw.println("Got a RemoteException while dumping the app " + r);
10214 pw.flush();
10215 }
10216 }
10217 }
10218 }
10219
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010220 final static class MemItem {
10221 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010222 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010223 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010224 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010225 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010226
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010227 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010228 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010229 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010230 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010231 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010232 }
10233 }
10234
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010235 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010236 boolean sort) {
10237 if (sort) {
10238 Collections.sort(items, new Comparator<MemItem>() {
10239 @Override
10240 public int compare(MemItem lhs, MemItem rhs) {
10241 if (lhs.pss < rhs.pss) {
10242 return 1;
10243 } else if (lhs.pss > rhs.pss) {
10244 return -1;
10245 }
10246 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010247 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010248 });
10249 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010250
10251 for (int i=0; i<items.size(); i++) {
10252 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010253 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010254 if (mi.subitems != null) {
10255 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10256 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010257 }
10258 }
10259
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010260 // These are in KB.
10261 static final long[] DUMP_MEM_BUCKETS = new long[] {
10262 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10263 120*1024, 160*1024, 200*1024,
10264 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10265 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10266 };
10267
Dianne Hackborn672342c2011-11-29 11:29:02 -080010268 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10269 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010270 int start = label.lastIndexOf('.');
10271 if (start >= 0) start++;
10272 else start = 0;
10273 int end = label.length();
10274 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10275 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10276 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10277 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010278 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010279 out.append(label, start, end);
10280 return;
10281 }
10282 }
10283 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010284 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010285 out.append(label, start, end);
10286 }
10287
10288 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10289 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10290 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10291 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10292 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10293 };
10294 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10295 "System", "Persistent", "Foreground",
10296 "Visible", "Perceptible", "Heavy Weight",
10297 "Backup", "A Services", "Home", "Previous",
10298 "B Services", "Background"
10299 };
10300
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010301 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010302 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010303 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010304 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010305 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010306
10307 int opti = 0;
10308 while (opti < args.length) {
10309 String opt = args[opti];
10310 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10311 break;
10312 }
10313 opti++;
10314 if ("-a".equals(opt)) {
10315 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010316 } else if ("--oom".equals(opt)) {
10317 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010318 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010319 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010321 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010322 pw.println("If [process] is specified it can be the name or ");
10323 pw.println("pid of a specific process to dump.");
10324 return;
10325 } else {
10326 pw.println("Unknown argument: " + opt + "; use -h for help");
10327 }
10328 }
10329
10330 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010331 if (procs == null) {
10332 return;
10333 }
10334
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010335 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010336 long uptime = SystemClock.uptimeMillis();
10337 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010338
10339 if (procs.size() == 1 || isCheckinRequest) {
10340 dumpAll = true;
10341 }
10342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010343 if (isCheckinRequest) {
10344 // short checkin version
10345 pw.println(uptime + "," + realtime);
10346 pw.flush();
10347 } else {
10348 pw.println("Applications Memory Usage (kB):");
10349 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10350 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010351
Dianne Hackbornb437e092011-08-05 17:50:29 -070010352 String[] innerArgs = new String[args.length-opti];
10353 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10354
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010355 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10356 long nativePss=0, dalvikPss=0, otherPss=0;
10357 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10358
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010359 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10360 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10361 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010362
10363 long totalPss = 0;
10364
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010365 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10366 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010368 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010369 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10370 pw.flush();
10371 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010372 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010373 if (dumpAll) {
10374 try {
10375 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10376 } catch (RemoteException e) {
10377 if (!isCheckinRequest) {
10378 pw.println("Got RemoteException!");
10379 pw.flush();
10380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010382 } else {
10383 mi = new Debug.MemoryInfo();
10384 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010385 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010386
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010387 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010388 long myTotalPss = mi.getTotalPss();
10389 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010390 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010391 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010392 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010393
10394 nativePss += mi.nativePss;
10395 dalvikPss += mi.dalvikPss;
10396 otherPss += mi.otherPss;
10397 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10398 long mem = mi.getOtherPss(j);
10399 miscPss[j] += mem;
10400 otherPss -= mem;
10401 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010402
10403 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010404 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10405 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010406 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010407 if (oomProcs[oomIndex] == null) {
10408 oomProcs[oomIndex] = new ArrayList<MemItem>();
10409 }
10410 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010411 break;
10412 }
10413 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 }
10416 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010417
10418 if (!isCheckinRequest && procs.size() > 1) {
10419 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10420
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010421 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10422 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10423 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010424 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010425 String label = Debug.MemoryInfo.getOtherLabel(j);
10426 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010427 }
10428
Dianne Hackbornb437e092011-08-05 17:50:29 -070010429 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10430 for (int j=0; j<oomPss.length; j++) {
10431 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010432 String label = DUMP_MEM_OOM_LABEL[j];
10433 MemItem item = new MemItem(label, label, oomPss[j],
10434 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010435 item.subitems = oomProcs[j];
10436 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010437 }
10438 }
10439
Dianne Hackborn672342c2011-11-29 11:29:02 -080010440 if (outTag != null || outStack != null) {
10441 if (outTag != null) {
10442 appendMemBucket(outTag, totalPss, "total", false);
10443 }
10444 if (outStack != null) {
10445 appendMemBucket(outStack, totalPss, "total", true);
10446 }
10447 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010448 for (int i=0; i<oomMems.size(); i++) {
10449 MemItem miCat = oomMems.get(i);
10450 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10451 continue;
10452 }
10453 if (miCat.id < ProcessList.SERVICE_ADJ
10454 || miCat.id == ProcessList.HOME_APP_ADJ
10455 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010456 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10457 outTag.append(" / ");
10458 }
10459 if (outStack != null) {
10460 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10461 if (firstLine) {
10462 outStack.append(":");
10463 firstLine = false;
10464 }
10465 outStack.append("\n\t at ");
10466 } else {
10467 outStack.append("$");
10468 }
10469 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010470 for (int j=0; j<miCat.subitems.size(); j++) {
10471 MemItem mi = miCat.subitems.get(j);
10472 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010473 if (outTag != null) {
10474 outTag.append(" ");
10475 }
10476 if (outStack != null) {
10477 outStack.append("$");
10478 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010479 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010480 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10481 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10482 }
10483 if (outStack != null) {
10484 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10485 }
10486 }
10487 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10488 outStack.append("(");
10489 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10490 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10491 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10492 outStack.append(":");
10493 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10494 }
10495 }
10496 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010497 }
10498 }
10499 }
10500 }
10501
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010502 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010503 pw.println();
10504 pw.println("Total PSS by process:");
10505 dumpMemItems(pw, " ", procMems, true);
10506 pw.println();
10507 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010508 pw.println("Total PSS by OOM adjustment:");
10509 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010510 if (!oomOnly) {
10511 PrintWriter out = categoryPw != null ? categoryPw : pw;
10512 out.println();
10513 out.println("Total PSS by category:");
10514 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010515 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010516 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010517 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010518 final int[] SINGLE_LONG_FORMAT = new int[] {
10519 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10520 };
10521 long[] longOut = new long[1];
10522 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10523 SINGLE_LONG_FORMAT, null, longOut, null);
10524 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10525 longOut[0] = 0;
10526 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10527 SINGLE_LONG_FORMAT, null, longOut, null);
10528 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10529 longOut[0] = 0;
10530 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10531 SINGLE_LONG_FORMAT, null, longOut, null);
10532 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10533 longOut[0] = 0;
10534 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10535 SINGLE_LONG_FORMAT, null, longOut, null);
10536 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10537 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10538 pw.print(shared); pw.println(" kB");
10539 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10540 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 }
10543
10544 /**
10545 * Searches array of arguments for the specified string
10546 * @param args array of argument strings
10547 * @param value value to search for
10548 * @return true if the value is contained in the array
10549 */
10550 private static boolean scanArgs(String[] args, String value) {
10551 if (args != null) {
10552 for (String arg : args) {
10553 if (value.equals(arg)) {
10554 return true;
10555 }
10556 }
10557 }
10558 return false;
10559 }
10560
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010561 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10562 ContentProviderRecord cpr, boolean always) {
10563 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10564
10565 if (!inLaunching || always) {
10566 synchronized (cpr) {
10567 cpr.launchingApp = null;
10568 cpr.notifyAll();
10569 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010570 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010571 String names[] = cpr.info.authority.split(";");
10572 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010573 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 }
10575 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010576
10577 for (int i=0; i<cpr.connections.size(); i++) {
10578 ContentProviderConnection conn = cpr.connections.get(i);
10579 if (conn.waiting) {
10580 // If this connection is waiting for the provider, then we don't
10581 // need to mess with its process unless we are always removing
10582 // or for some reason the provider is not currently launching.
10583 if (inLaunching && !always) {
10584 continue;
10585 }
10586 }
10587 ProcessRecord capp = conn.client;
10588 conn.dead = true;
10589 if (conn.stableCount > 0) {
10590 if (!capp.persistent && capp.thread != null
10591 && capp.pid != 0
10592 && capp.pid != MY_PID) {
10593 Slog.i(TAG, "Kill " + capp.processName
10594 + " (pid " + capp.pid + "): provider " + cpr.info.name
10595 + " in dying process " + (proc != null ? proc.processName : "??"));
10596 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10597 capp.processName, capp.setAdj, "dying provider "
10598 + cpr.name.toShortString());
10599 Process.killProcessQuiet(capp.pid);
10600 }
10601 } else if (capp.thread != null && conn.provider.provider != null) {
10602 try {
10603 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10604 } catch (RemoteException e) {
10605 }
10606 // In the protocol here, we don't expect the client to correctly
10607 // clean up this connection, we'll just remove it.
10608 cpr.connections.remove(i);
10609 conn.client.conProviders.remove(conn);
10610 }
10611 }
10612
10613 if (inLaunching && always) {
10614 mLaunchingProviders.remove(cpr);
10615 }
10616 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010617 }
10618
10619 /**
10620 * Main code for cleaning up a process when it has gone away. This is
10621 * called both as a result of the process dying, or directly when stopping
10622 * a process when running in single process mode.
10623 */
10624 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010625 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010626 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010627 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 }
10629
Dianne Hackborn36124872009-10-08 16:22:03 -070010630 mProcessesToGc.remove(app);
10631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 // Dismiss any open dialogs.
10633 if (app.crashDialog != null) {
10634 app.crashDialog.dismiss();
10635 app.crashDialog = null;
10636 }
10637 if (app.anrDialog != null) {
10638 app.anrDialog.dismiss();
10639 app.anrDialog = null;
10640 }
10641 if (app.waitDialog != null) {
10642 app.waitDialog.dismiss();
10643 app.waitDialog = null;
10644 }
10645
10646 app.crashing = false;
10647 app.notResponding = false;
10648
10649 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010650 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010651 app.thread = null;
10652 app.forcingToForeground = null;
10653 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010654 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010655 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010656 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010658 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010659
10660 boolean restart = false;
10661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010662 // Remove published content providers.
10663 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010664 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010666 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010667
10668 final boolean always = app.bad || !allowRestart;
10669 if (removeDyingProviderLocked(app, cpr, always) || always) {
10670 // We left the provider in the launching list, need to
10671 // restart it.
10672 restart = true;
10673 }
10674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010676 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010677 }
10678 app.pubProviders.clear();
10679 }
10680
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010681 // Take care of any launching providers waiting for this process.
10682 if (checkAppInLaunchingProvidersLocked(app, false)) {
10683 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 // Unregister from connected content providers.
10687 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010688 for (int i=0; i<app.conProviders.size(); i++) {
10689 ContentProviderConnection conn = app.conProviders.get(i);
10690 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 }
10692 app.conProviders.clear();
10693 }
10694
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010695 // At this point there may be remaining entries in mLaunchingProviders
10696 // where we were the only one waiting, so they are no longer of use.
10697 // Look for these and clean up if found.
10698 // XXX Commented out for now. Trying to figure out a way to reproduce
10699 // the actual situation to identify what is actually going on.
10700 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010701 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010702 ContentProviderRecord cpr = (ContentProviderRecord)
10703 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010704 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010705 synchronized (cpr) {
10706 cpr.launchingApp = null;
10707 cpr.notifyAll();
10708 }
10709 }
10710 }
10711 }
10712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010713 skipCurrentReceiverLocked(app);
10714
10715 // Unregister any receivers.
10716 if (app.receivers.size() > 0) {
10717 Iterator<ReceiverList> it = app.receivers.iterator();
10718 while (it.hasNext()) {
10719 removeReceiverLocked(it.next());
10720 }
10721 app.receivers.clear();
10722 }
10723
Christopher Tate181fafa2009-05-14 11:12:14 -070010724 // If the app is undergoing backup, tell the backup manager about it
10725 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010726 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010727 try {
10728 IBackupManager bm = IBackupManager.Stub.asInterface(
10729 ServiceManager.getService(Context.BACKUP_SERVICE));
10730 bm.agentDisconnected(app.info.packageName);
10731 } catch (RemoteException e) {
10732 // can't happen; backup manager is local
10733 }
10734 }
10735
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010736 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10737 ProcessChangeItem item = mPendingProcessChanges.get(i);
10738 if (item.pid == app.pid) {
10739 mPendingProcessChanges.remove(i);
10740 mAvailProcessChanges.add(item);
10741 }
10742 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010743 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010745 // If the caller is restarting this app, then leave it in its
10746 // current lists and let the caller take care of it.
10747 if (restarting) {
10748 return;
10749 }
10750
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010751 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010752 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010754 mProcessNames.remove(app.processName, app.uid);
10755 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010756 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010757 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10758 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010759 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010761 } else if (!app.removed) {
10762 // This app is persistent, so we need to keep its record around.
10763 // If it is not already on the pending app list, add it there
10764 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10766 mPersistentStartingProcesses.add(app);
10767 restart = true;
10768 }
10769 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010770 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10771 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 mProcessesOnHold.remove(app);
10773
The Android Open Source Project4df24232009-03-05 14:34:35 -080010774 if (app == mHomeProcess) {
10775 mHomeProcess = null;
10776 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010777 if (app == mPreviousProcess) {
10778 mPreviousProcess = null;
10779 }
10780
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010781 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010782 // We have components that still need to be running in the
10783 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010784 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010785 startProcessLocked(app, "restart", app.processName);
10786 } else if (app.pid > 0 && app.pid != MY_PID) {
10787 // Goodbye!
10788 synchronized (mPidsSelfLocked) {
10789 mPidsSelfLocked.remove(app.pid);
10790 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10791 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010792 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010793 }
10794 }
10795
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010796 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10797 // Look through the content providers we are waiting to have launched,
10798 // and if any run in this process then either schedule a restart of
10799 // the process or kill the client waiting for it if this process has
10800 // gone bad.
10801 int NL = mLaunchingProviders.size();
10802 boolean restart = false;
10803 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010804 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010805 if (cpr.launchingApp == app) {
10806 if (!alwaysBad && !app.bad) {
10807 restart = true;
10808 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010809 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010810 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010811 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010812 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010813 }
10814 }
10815 }
10816 return restart;
10817 }
10818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 // =========================================================
10820 // SERVICES
10821 // =========================================================
10822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010823 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10824 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010825 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010827 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010828 }
10829 }
10830
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010831 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010832 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010833 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010834 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010835 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010836 }
10837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010839 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010840 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010841 // Refuse possible leaked file descriptors
10842 if (service != null && service.hasFileDescriptors() == true) {
10843 throw new IllegalArgumentException("File descriptors passed in Intent");
10844 }
10845
Amith Yamasani742a6712011-05-04 14:49:28 -070010846 if (DEBUG_SERVICE)
10847 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 synchronized(this) {
10849 final int callingPid = Binder.getCallingPid();
10850 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010851 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010853 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010854 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855 Binder.restoreCallingIdentity(origId);
10856 return res;
10857 }
10858 }
10859
10860 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010861 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010863 if (DEBUG_SERVICE)
10864 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010866 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010867 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 Binder.restoreCallingIdentity(origId);
10869 return res;
10870 }
10871 }
10872
10873 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010874 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010875 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010876 // Refuse possible leaked file descriptors
10877 if (service != null && service.hasFileDescriptors() == true) {
10878 throw new IllegalArgumentException("File descriptors passed in Intent");
10879 }
10880
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010881 checkValidCaller(Binder.getCallingUid(), userId);
10882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010884 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 }
10887
10888 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010889 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010890 // Refuse possible leaked file descriptors
10891 if (service != null && service.hasFileDescriptors() == true) {
10892 throw new IllegalArgumentException("File descriptors passed in Intent");
10893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010895 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 }
10898
10899 public boolean stopServiceToken(ComponentName className, IBinder token,
10900 int startId) {
10901 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010902 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 }
10905
10906 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010907 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010908 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010909 mServices.setServiceForegroundLocked(className, token, id, notification,
10910 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010911 }
10912 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010913
Dianne Hackborn41203752012-08-31 14:05:51 -070010914 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10915 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010916 final int callingUserId = UserHandle.getUserId(callingUid);
10917 if (callingUserId != userId) {
10918 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10919 if ((requireFull || checkComponentPermission(
10920 android.Manifest.permission.INTERACT_ACROSS_USERS,
10921 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10922 && checkComponentPermission(
10923 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10924 callingPid, callingUid, -1, true)
10925 != PackageManager.PERMISSION_GRANTED) {
10926 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10927 // In this case, they would like to just execute as their
10928 // owner user instead of failing.
10929 userId = callingUserId;
10930 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010931 StringBuilder builder = new StringBuilder(128);
10932 builder.append("Permission Denial: ");
10933 builder.append(name);
10934 if (callerPackage != null) {
10935 builder.append(" from ");
10936 builder.append(callerPackage);
10937 }
10938 builder.append(" asks to run as user ");
10939 builder.append(userId);
10940 builder.append(" but is calling from user ");
10941 builder.append(UserHandle.getUserId(callingUid));
10942 builder.append("; this requires ");
10943 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10944 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010945 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010946 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10947 }
10948 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010949 Slog.w(TAG, msg);
10950 throw new SecurityException(msg);
10951 }
10952 }
10953 }
10954 if (userId == UserHandle.USER_CURRENT
10955 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070010956 // Note that we may be accessing this outside of a lock...
10957 // shouldn't be a big deal, if this is being called outside
10958 // of a locked context there is intrinsically a race with
10959 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010960 userId = mCurrentUserId;
10961 }
10962 if (!allowAll && userId < 0) {
10963 throw new IllegalArgumentException(
10964 "Call does not support special user #" + userId);
10965 }
10966 }
10967 return userId;
10968 }
10969
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010970 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10971 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010972 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010973 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010974 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10975 if (ActivityManager.checkUidPermission(
10976 android.Manifest.permission.INTERACT_ACROSS_USERS,
10977 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10978 ComponentName comp = new ComponentName(aInfo.packageName, className);
10979 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10980 + " requests FLAG_SINGLE_USER, but app does not hold "
10981 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10982 Slog.w(TAG, msg);
10983 throw new SecurityException(msg);
10984 }
10985 result = true;
10986 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010987 } else if (componentProcessName == aInfo.packageName) {
10988 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10989 } else if ("system".equals(componentProcessName)) {
10990 result = true;
10991 }
10992 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010993 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10994 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010995 }
10996 return result;
10997 }
10998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 public int bindService(IApplicationThread caller, IBinder token,
11000 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011001 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011002 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 // Refuse possible leaked file descriptors
11004 if (service != null && service.hasFileDescriptors() == true) {
11005 throw new IllegalArgumentException("File descriptors passed in Intent");
11006 }
11007
11008 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011009 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11010 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 }
11012 }
11013
11014 public boolean unbindService(IServiceConnection connection) {
11015 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011016 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 }
11019
11020 public void publishService(IBinder token, Intent intent, IBinder service) {
11021 // Refuse possible leaked file descriptors
11022 if (intent != null && intent.hasFileDescriptors() == true) {
11023 throw new IllegalArgumentException("File descriptors passed in Intent");
11024 }
11025
11026 synchronized(this) {
11027 if (!(token instanceof ServiceRecord)) {
11028 throw new IllegalArgumentException("Invalid service token");
11029 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011030 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011031 }
11032 }
11033
11034 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11035 // Refuse possible leaked file descriptors
11036 if (intent != null && intent.hasFileDescriptors() == true) {
11037 throw new IllegalArgumentException("File descriptors passed in Intent");
11038 }
11039
11040 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011041 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011042 }
11043 }
11044
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011045 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011046 synchronized(this) {
11047 if (!(token instanceof ServiceRecord)) {
11048 throw new IllegalArgumentException("Invalid service token");
11049 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011050 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 }
11053
11054 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011055 // BACKUP AND RESTORE
11056 // =========================================================
11057
11058 // Cause the target app to be launched if necessary and its backup agent
11059 // instantiated. The backup agent will invoke backupAgentCreated() on the
11060 // activity manager to announce its creation.
11061 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011062 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011063 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11064
11065 synchronized(this) {
11066 // !!! TODO: currently no check here that we're already bound
11067 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11068 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11069 synchronized (stats) {
11070 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11071 }
11072
Dianne Hackborne7f97212011-02-24 14:40:20 -080011073 // Backup agent is now in use, its package can't be stopped.
11074 try {
11075 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011076 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011077 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011078 } catch (IllegalArgumentException e) {
11079 Slog.w(TAG, "Failed trying to unstop package "
11080 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011081 }
11082
Christopher Tate181fafa2009-05-14 11:12:14 -070011083 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011084 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11085 ? new ComponentName(app.packageName, app.backupAgentName)
11086 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011087 // startProcessLocked() returns existing proc's record if it's already running
11088 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011089 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011090 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011091 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011092 return false;
11093 }
11094
11095 r.app = proc;
11096 mBackupTarget = r;
11097 mBackupAppName = app.packageName;
11098
Christopher Tate6fa95972009-06-05 18:43:55 -070011099 // Try not to kill the process during backup
11100 updateOomAdjLocked(proc);
11101
Christopher Tate181fafa2009-05-14 11:12:14 -070011102 // If the process is already attached, schedule the creation of the backup agent now.
11103 // If it is not yet live, this will be done when it attaches to the framework.
11104 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011105 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011106 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011107 proc.thread.scheduleCreateBackupAgent(app,
11108 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011109 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011110 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011111 }
11112 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011113 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011114 }
11115 // Invariants: at this point, the target app process exists and the application
11116 // is either already running or in the process of coming up. mBackupTarget and
11117 // mBackupAppName describe the app, so that when it binds back to the AM we
11118 // know that it's scheduled for a backup-agent operation.
11119 }
11120
11121 return true;
11122 }
11123
11124 // A backup agent has just come up
11125 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011126 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011127 + " = " + agent);
11128
11129 synchronized(this) {
11130 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011131 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011132 return;
11133 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011134 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011135
Dianne Hackborn06740692010-09-22 22:46:21 -070011136 long oldIdent = Binder.clearCallingIdentity();
11137 try {
11138 IBackupManager bm = IBackupManager.Stub.asInterface(
11139 ServiceManager.getService(Context.BACKUP_SERVICE));
11140 bm.agentConnected(agentPackageName, agent);
11141 } catch (RemoteException e) {
11142 // can't happen; the backup manager service is local
11143 } catch (Exception e) {
11144 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11145 e.printStackTrace();
11146 } finally {
11147 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011148 }
11149 }
11150
11151 // done with this agent
11152 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011153 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011154 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011155 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011156 return;
11157 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011158
11159 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011160 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011161 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011162 return;
11163 }
11164
Christopher Tate181fafa2009-05-14 11:12:14 -070011165 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011166 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011167 return;
11168 }
11169
Christopher Tate6fa95972009-06-05 18:43:55 -070011170 ProcessRecord proc = mBackupTarget.app;
11171 mBackupTarget = null;
11172 mBackupAppName = null;
11173
11174 // Not backing this app up any more; reset its OOM adjustment
11175 updateOomAdjLocked(proc);
11176
Christopher Tatec7b31e32009-06-10 15:49:30 -070011177 // If the app crashed during backup, 'thread' will be null here
11178 if (proc.thread != null) {
11179 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011180 proc.thread.scheduleDestroyBackupAgent(appInfo,
11181 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011182 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011183 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011184 e.printStackTrace();
11185 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011186 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011187 }
11188 }
11189 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190 // BROADCASTS
11191 // =========================================================
11192
Josh Bartel7f208742010-02-25 11:01:44 -060011193 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011194 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011195 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011196 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11197 if (stickies == null) {
11198 return cur;
11199 }
11200 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 if (list == null) {
11202 return cur;
11203 }
11204 int N = list.size();
11205 for (int i=0; i<N; i++) {
11206 Intent intent = list.get(i);
11207 if (filter.match(resolver, intent, true, TAG) >= 0) {
11208 if (cur == null) {
11209 cur = new ArrayList<Intent>();
11210 }
11211 cur.add(intent);
11212 }
11213 }
11214 return cur;
11215 }
11216
Christopher Tatef46723b2012-01-26 14:19:24 -080011217 boolean isPendingBroadcastProcessLocked(int pid) {
11218 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11219 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221
Christopher Tatef46723b2012-01-26 14:19:24 -080011222 void skipPendingBroadcastLocked(int pid) {
11223 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11224 for (BroadcastQueue queue : mBroadcastQueues) {
11225 queue.skipPendingBroadcastLocked(pid);
11226 }
11227 }
11228
11229 // The app just attached; send any pending broadcasts that it should receive
11230 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11231 boolean didSomething = false;
11232 for (BroadcastQueue queue : mBroadcastQueues) {
11233 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011234 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011235 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 }
11237
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011238 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011239 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011240 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011241 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011242 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 synchronized(this) {
11244 ProcessRecord callerApp = null;
11245 if (caller != null) {
11246 callerApp = getRecordForAppLocked(caller);
11247 if (callerApp == null) {
11248 throw new SecurityException(
11249 "Unable to find app for caller " + caller
11250 + " (pid=" + Binder.getCallingPid()
11251 + ") when registering receiver " + receiver);
11252 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011253 if (callerApp.info.uid != Process.SYSTEM_UID &&
11254 !callerApp.pkgList.contains(callerPackage)) {
11255 throw new SecurityException("Given caller package " + callerPackage
11256 + " is not running in process " + callerApp);
11257 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011258 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011259 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011260 } else {
11261 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011262 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011263 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 }
11265
Dianne Hackborn139748f2012-09-24 11:36:57 -070011266 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011267 true, true, "registerReceiver", callerPackage);
11268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 List allSticky = null;
11270
11271 // Look for any matching sticky broadcasts...
11272 Iterator actions = filter.actionsIterator();
11273 if (actions != null) {
11274 while (actions.hasNext()) {
11275 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011276 allSticky = getStickiesLocked(action, filter, allSticky,
11277 UserHandle.USER_ALL);
11278 allSticky = getStickiesLocked(action, filter, allSticky,
11279 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 }
11281 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011282 allSticky = getStickiesLocked(null, filter, allSticky,
11283 UserHandle.USER_ALL);
11284 allSticky = getStickiesLocked(null, filter, allSticky,
11285 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011286 }
11287
11288 // The first sticky in the list is returned directly back to
11289 // the client.
11290 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11291
Joe Onorato8a9b2202010-02-26 18:56:32 -080011292 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011293 + ": " + sticky);
11294
11295 if (receiver == null) {
11296 return sticky;
11297 }
11298
11299 ReceiverList rl
11300 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11301 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011302 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11303 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011304 if (rl.app != null) {
11305 rl.app.receivers.add(rl);
11306 } else {
11307 try {
11308 receiver.asBinder().linkToDeath(rl, 0);
11309 } catch (RemoteException e) {
11310 return sticky;
11311 }
11312 rl.linkedToDeath = true;
11313 }
11314 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011315 } else if (rl.uid != callingUid) {
11316 throw new IllegalArgumentException(
11317 "Receiver requested to register for uid " + callingUid
11318 + " was previously registered for uid " + rl.uid);
11319 } else if (rl.pid != callingPid) {
11320 throw new IllegalArgumentException(
11321 "Receiver requested to register for pid " + callingPid
11322 + " was previously registered for pid " + rl.pid);
11323 } else if (rl.userId != userId) {
11324 throw new IllegalArgumentException(
11325 "Receiver requested to register for user " + userId
11326 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011328 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011329 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011330 rl.add(bf);
11331 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011332 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 }
11334 mReceiverResolver.addFilter(bf);
11335
11336 // Enqueue broadcasts for all existing stickies that match
11337 // this filter.
11338 if (allSticky != null) {
11339 ArrayList receivers = new ArrayList();
11340 receivers.add(bf);
11341
11342 int N = allSticky.size();
11343 for (int i=0; i<N; i++) {
11344 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011345 BroadcastQueue queue = broadcastQueueForIntent(intent);
11346 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011347 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011348 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011349 queue.enqueueParallelBroadcastLocked(r);
11350 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011351 }
11352 }
11353
11354 return sticky;
11355 }
11356 }
11357
11358 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011359 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360
Christopher Tatef46723b2012-01-26 14:19:24 -080011361 final long origId = Binder.clearCallingIdentity();
11362 try {
11363 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364
Christopher Tatef46723b2012-01-26 14:19:24 -080011365 synchronized(this) {
11366 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011368 if (rl != null) {
11369 if (rl.curBroadcast != null) {
11370 BroadcastRecord r = rl.curBroadcast;
11371 final boolean doNext = finishReceiverLocked(
11372 receiver.asBinder(), r.resultCode, r.resultData,
11373 r.resultExtras, r.resultAbort, true);
11374 if (doNext) {
11375 doTrim = true;
11376 r.queue.processNextBroadcast(false);
11377 }
11378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379
Christopher Tatef46723b2012-01-26 14:19:24 -080011380 if (rl.app != null) {
11381 rl.app.receivers.remove(rl);
11382 }
11383 removeReceiverLocked(rl);
11384 if (rl.linkedToDeath) {
11385 rl.linkedToDeath = false;
11386 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 }
11389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390
Christopher Tatef46723b2012-01-26 14:19:24 -080011391 // If we actually concluded any broadcasts, we might now be able
11392 // to trim the recipients' apps from our working set
11393 if (doTrim) {
11394 trimApplications();
11395 return;
11396 }
11397
11398 } finally {
11399 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 }
11402
11403 void removeReceiverLocked(ReceiverList rl) {
11404 mRegisteredReceivers.remove(rl.receiver.asBinder());
11405 int N = rl.size();
11406 for (int i=0; i<N; i++) {
11407 mReceiverResolver.removeFilter(rl.get(i));
11408 }
11409 }
11410
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011411 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011412 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11413 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011414 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011415 try {
11416 r.thread.dispatchPackageBroadcast(cmd, packages);
11417 } catch (RemoteException ex) {
11418 }
11419 }
11420 }
11421 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011422
11423 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11424 int[] users) {
11425 List<ResolveInfo> receivers = null;
11426 try {
11427 HashSet<ComponentName> singleUserReceivers = null;
11428 boolean scannedFirstReceivers = false;
11429 for (int user : users) {
11430 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11431 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11432 if (newReceivers != null && newReceivers.size() == 0) {
11433 newReceivers = null;
11434 }
11435 if (receivers == null) {
11436 receivers = newReceivers;
11437 } else if (newReceivers != null) {
11438 // We need to concatenate the additional receivers
11439 // found with what we have do far. This would be easy,
11440 // but we also need to de-dup any receivers that are
11441 // singleUser.
11442 if (!scannedFirstReceivers) {
11443 // Collect any single user receivers we had already retrieved.
11444 scannedFirstReceivers = true;
11445 for (int i=0; i<receivers.size(); i++) {
11446 ResolveInfo ri = receivers.get(i);
11447 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11448 ComponentName cn = new ComponentName(
11449 ri.activityInfo.packageName, ri.activityInfo.name);
11450 if (singleUserReceivers == null) {
11451 singleUserReceivers = new HashSet<ComponentName>();
11452 }
11453 singleUserReceivers.add(cn);
11454 }
11455 }
11456 }
11457 // Add the new results to the existing results, tracking
11458 // and de-dupping single user receivers.
11459 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011460 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011461 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11462 ComponentName cn = new ComponentName(
11463 ri.activityInfo.packageName, ri.activityInfo.name);
11464 if (singleUserReceivers == null) {
11465 singleUserReceivers = new HashSet<ComponentName>();
11466 }
11467 if (!singleUserReceivers.contains(cn)) {
11468 singleUserReceivers.add(cn);
11469 receivers.add(ri);
11470 }
11471 } else {
11472 receivers.add(ri);
11473 }
11474 }
11475 }
11476 }
11477 } catch (RemoteException ex) {
11478 // pm is in same process, this will never happen.
11479 }
11480 return receivers;
11481 }
11482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 private final int broadcastIntentLocked(ProcessRecord callerApp,
11484 String callerPackage, Intent intent, String resolvedType,
11485 IIntentReceiver resultTo, int resultCode, String resultData,
11486 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011487 boolean ordered, boolean sticky, int callingPid, int callingUid,
11488 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 intent = new Intent(intent);
11490
Dianne Hackborne7f97212011-02-24 14:40:20 -080011491 // By default broadcasts do not go to stopped apps.
11492 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11493
Joe Onorato8a9b2202010-02-26 18:56:32 -080011494 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011495 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011496 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011498 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011500
Dianne Hackborn139748f2012-09-24 11:36:57 -070011501 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011502 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011503
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011504 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011505 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011506 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011507 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11508 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11509 Slog.w(TAG, "Skipping broadcast of " + intent
11510 + ": user " + userId + " is stopped");
11511 return ActivityManager.BROADCAST_SUCCESS;
11512 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011513 }
11514
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011515 /*
11516 * Prevent non-system code (defined here to be non-persistent
11517 * processes) from sending protected broadcasts.
11518 */
11519 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11520 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11521 callingUid == 0) {
11522 // Always okay.
11523 } else if (callerApp == null || !callerApp.persistent) {
11524 try {
11525 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11526 intent.getAction())) {
11527 String msg = "Permission Denial: not allowed to send broadcast "
11528 + intent.getAction() + " from pid="
11529 + callingPid + ", uid=" + callingUid;
11530 Slog.w(TAG, msg);
11531 throw new SecurityException(msg);
11532 }
11533 } catch (RemoteException e) {
11534 Slog.w(TAG, "Remote exception", e);
11535 return ActivityManager.BROADCAST_SUCCESS;
11536 }
11537 }
11538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 // Handle special intents: if this broadcast is from the package
11540 // manager about a package being removed, we need to remove all of
11541 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011542 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011543 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011544 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11545 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011546 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 || uidRemoved) {
11548 if (checkComponentPermission(
11549 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011550 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 == PackageManager.PERMISSION_GRANTED) {
11552 if (uidRemoved) {
11553 final Bundle intentExtras = intent.getExtras();
11554 final int uid = intentExtras != null
11555 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11556 if (uid >= 0) {
11557 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11558 synchronized (bs) {
11559 bs.removeUidStatsLocked(uid);
11560 }
11561 }
11562 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011563 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011564 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011565 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011566 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11567 if (list != null && (list.length > 0)) {
11568 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011569 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011570 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011571 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011572 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011573 }
11574 } else {
11575 Uri data = intent.getData();
11576 String ssp;
11577 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11578 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11579 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011580 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11581 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011582 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011583 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011584 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011585 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011587 }
11588 }
11589 }
11590 } else {
11591 String msg = "Permission Denial: " + intent.getAction()
11592 + " broadcast from " + callerPackage + " (pid=" + callingPid
11593 + ", uid=" + callingUid + ")"
11594 + " requires "
11595 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011596 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 throw new SecurityException(msg);
11598 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011599
11600 // Special case for adding a package: by default turn on compatibility
11601 // mode.
11602 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011603 Uri data = intent.getData();
11604 String ssp;
11605 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11606 mCompatModePackages.handlePackageAddedLocked(ssp,
11607 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609 }
11610
11611 /*
11612 * If this is the time zone changed action, queue up a message that will reset the timezone
11613 * of all currently running processes. This message will get queued up before the broadcast
11614 * happens.
11615 */
11616 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11617 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11618 }
11619
Robert Greenwalt03595d02010-11-02 14:08:23 -070011620 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11621 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11622 }
11623
Robert Greenwalt434203a2010-10-11 16:00:27 -070011624 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11625 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11626 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11627 }
11628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011629 // Add to the sticky list if requested.
11630 if (sticky) {
11631 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11632 callingPid, callingUid)
11633 != PackageManager.PERMISSION_GRANTED) {
11634 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11635 + callingPid + ", uid=" + callingUid
11636 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011637 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638 throw new SecurityException(msg);
11639 }
11640 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011641 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011643 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011644 }
11645 if (intent.getComponent() != null) {
11646 throw new SecurityException(
11647 "Sticky broadcasts can't target a specific component");
11648 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011649 // We use userId directly here, since the "all" target is maintained
11650 // as a separate set of sticky broadcasts.
11651 if (userId != UserHandle.USER_ALL) {
11652 // But first, if this is not a broadcast to all users, then
11653 // make sure it doesn't conflict with an existing broadcast to
11654 // all users.
11655 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11656 UserHandle.USER_ALL);
11657 if (stickies != null) {
11658 ArrayList<Intent> list = stickies.get(intent.getAction());
11659 if (list != null) {
11660 int N = list.size();
11661 int i;
11662 for (i=0; i<N; i++) {
11663 if (intent.filterEquals(list.get(i))) {
11664 throw new IllegalArgumentException(
11665 "Sticky broadcast " + intent + " for user "
11666 + userId + " conflicts with existing global broadcast");
11667 }
11668 }
11669 }
11670 }
11671 }
11672 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11673 if (stickies == null) {
11674 stickies = new HashMap<String, ArrayList<Intent>>();
11675 mStickyBroadcasts.put(userId, stickies);
11676 }
11677 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678 if (list == null) {
11679 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011680 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011681 }
11682 int N = list.size();
11683 int i;
11684 for (i=0; i<N; i++) {
11685 if (intent.filterEquals(list.get(i))) {
11686 // This sticky already exists, replace it.
11687 list.set(i, new Intent(intent));
11688 break;
11689 }
11690 }
11691 if (i >= N) {
11692 list.add(new Intent(intent));
11693 }
11694 }
11695
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011696 int[] users;
11697 if (userId == UserHandle.USER_ALL) {
11698 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011699 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011700 } else {
11701 // Caller wants broadcast to go to one specific user.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011702 users = mCurrentUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011703 }
11704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011705 // Figure out who all will receive this broadcast.
11706 List receivers = null;
11707 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011708 // Need to resolve the intent to interested receivers...
11709 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11710 == 0) {
11711 receivers = collectReceiverComponents(intent, resolvedType, users);
11712 }
11713 if (intent.getComponent() == null) {
11714 registeredReceivers = mReceiverResolver.queryIntent(intent,
11715 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716 }
11717
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011718 final boolean replacePending =
11719 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11720
Joe Onorato8a9b2202010-02-26 18:56:32 -080011721 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011722 + " replacePending=" + replacePending);
11723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11725 if (!ordered && NR > 0) {
11726 // If we are not serializing this broadcast, then send the
11727 // registered receivers separately so they don't wait for the
11728 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011729 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11730 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 callerPackage, callingPid, callingUid, requiredPermission,
11732 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011733 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011734 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011735 TAG, "Enqueueing parallel broadcast " + r);
11736 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011737 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011738 queue.enqueueParallelBroadcastLocked(r);
11739 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 registeredReceivers = null;
11742 NR = 0;
11743 }
11744
11745 // Merge into one list.
11746 int ir = 0;
11747 if (receivers != null) {
11748 // A special case for PACKAGE_ADDED: do not allow the package
11749 // being added to see this broadcast. This prevents them from
11750 // using this as a back door to get run as soon as they are
11751 // installed. Maybe in the future we want to have a special install
11752 // broadcast or such for apps, but we'd like to deliberately make
11753 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011754 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011755 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11756 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11757 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011758 Uri data = intent.getData();
11759 if (data != null) {
11760 String pkgName = data.getSchemeSpecificPart();
11761 if (pkgName != null) {
11762 skipPackages = new String[] { pkgName };
11763 }
11764 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011765 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011766 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011767 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011768 if (skipPackages != null && (skipPackages.length > 0)) {
11769 for (String skipPackage : skipPackages) {
11770 if (skipPackage != null) {
11771 int NT = receivers.size();
11772 for (int it=0; it<NT; it++) {
11773 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11774 if (curt.activityInfo.packageName.equals(skipPackage)) {
11775 receivers.remove(it);
11776 it--;
11777 NT--;
11778 }
11779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011780 }
11781 }
11782 }
11783
11784 int NT = receivers != null ? receivers.size() : 0;
11785 int it = 0;
11786 ResolveInfo curt = null;
11787 BroadcastFilter curr = null;
11788 while (it < NT && ir < NR) {
11789 if (curt == null) {
11790 curt = (ResolveInfo)receivers.get(it);
11791 }
11792 if (curr == null) {
11793 curr = registeredReceivers.get(ir);
11794 }
11795 if (curr.getPriority() >= curt.priority) {
11796 // Insert this broadcast record into the final list.
11797 receivers.add(it, curr);
11798 ir++;
11799 curr = null;
11800 it++;
11801 NT++;
11802 } else {
11803 // Skip to the next ResolveInfo in the final list.
11804 it++;
11805 curt = null;
11806 }
11807 }
11808 }
11809 while (ir < NR) {
11810 if (receivers == null) {
11811 receivers = new ArrayList();
11812 }
11813 receivers.add(registeredReceivers.get(ir));
11814 ir++;
11815 }
11816
11817 if ((receivers != null && receivers.size() > 0)
11818 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011819 BroadcastQueue queue = broadcastQueueForIntent(intent);
11820 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011822 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011823 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011824 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011825 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011826 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 if (DEBUG_BROADCAST) {
11828 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011829 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011831 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011832 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011833 queue.enqueueOrderedBroadcastLocked(r);
11834 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 }
11837
Dianne Hackborna4972e92012-03-14 10:38:05 -070011838 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011839 }
11840
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011841 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011842 // Refuse possible leaked file descriptors
11843 if (intent != null && intent.hasFileDescriptors() == true) {
11844 throw new IllegalArgumentException("File descriptors passed in Intent");
11845 }
11846
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011847 int flags = intent.getFlags();
11848
11849 if (!mProcessesReady) {
11850 // if the caller really truly claims to know what they're doing, go
11851 // ahead and allow the broadcast without launching any receivers
11852 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11853 intent = new Intent(intent);
11854 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11855 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11856 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11857 + " before boot completion");
11858 throw new IllegalStateException("Cannot broadcast before boot completed");
11859 }
11860 }
11861
11862 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11863 throw new IllegalArgumentException(
11864 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11865 }
11866
11867 return intent;
11868 }
11869
11870 public final int broadcastIntent(IApplicationThread caller,
11871 Intent intent, String resolvedType, IIntentReceiver resultTo,
11872 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011873 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011874 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011876 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011878 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11879 final int callingPid = Binder.getCallingPid();
11880 final int callingUid = Binder.getCallingUid();
11881 final long origId = Binder.clearCallingIdentity();
11882 int res = broadcastIntentLocked(callerApp,
11883 callerApp != null ? callerApp.info.packageName : null,
11884 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011885 resultCode, resultData, map, requiredPermission, serialized, sticky,
11886 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011887 Binder.restoreCallingIdentity(origId);
11888 return res;
11889 }
11890 }
11891
11892 int broadcastIntentInPackage(String packageName, int uid,
11893 Intent intent, String resolvedType, IIntentReceiver resultTo,
11894 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011895 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011897 intent = verifyBroadcastLocked(intent);
11898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011899 final long origId = Binder.clearCallingIdentity();
11900 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11901 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011902 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011903 Binder.restoreCallingIdentity(origId);
11904 return res;
11905 }
11906 }
11907
Amith Yamasani742a6712011-05-04 14:49:28 -070011908 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011909 // Refuse possible leaked file descriptors
11910 if (intent != null && intent.hasFileDescriptors() == true) {
11911 throw new IllegalArgumentException("File descriptors passed in Intent");
11912 }
11913
Dianne Hackborn139748f2012-09-24 11:36:57 -070011914 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011915 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011917 synchronized(this) {
11918 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11919 != PackageManager.PERMISSION_GRANTED) {
11920 String msg = "Permission Denial: unbroadcastIntent() from pid="
11921 + Binder.getCallingPid()
11922 + ", uid=" + Binder.getCallingUid()
11923 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011924 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 throw new SecurityException(msg);
11926 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011927 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11928 if (stickies != null) {
11929 ArrayList<Intent> list = stickies.get(intent.getAction());
11930 if (list != null) {
11931 int N = list.size();
11932 int i;
11933 for (i=0; i<N; i++) {
11934 if (intent.filterEquals(list.get(i))) {
11935 list.remove(i);
11936 break;
11937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011938 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011939 if (list.size() <= 0) {
11940 stickies.remove(intent.getAction());
11941 }
11942 }
11943 if (stickies.size() <= 0) {
11944 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011945 }
11946 }
11947 }
11948 }
11949
11950 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11951 String resultData, Bundle resultExtras, boolean resultAbort,
11952 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011953 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11954 if (r == null) {
11955 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 return false;
11957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011958
Christopher Tatef46723b2012-01-26 14:19:24 -080011959 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11960 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 }
11962
11963 public void finishReceiver(IBinder who, int resultCode, String resultData,
11964 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011965 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966
11967 // Refuse possible leaked file descriptors
11968 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11969 throw new IllegalArgumentException("File descriptors passed in Bundle");
11970 }
11971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011973 try {
11974 boolean doNext = false;
11975 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011976
Christopher Tatef46723b2012-01-26 14:19:24 -080011977 synchronized(this) {
11978 r = broadcastRecordForReceiverLocked(who);
11979 if (r != null) {
11980 doNext = r.queue.finishReceiverLocked(r, resultCode,
11981 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011983 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011984
Christopher Tatef46723b2012-01-26 14:19:24 -080011985 if (doNext) {
11986 r.queue.processNextBroadcast(false);
11987 }
11988 trimApplications();
11989 } finally {
11990 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011994 // =========================================================
11995 // INSTRUMENTATION
11996 // =========================================================
11997
11998 public boolean startInstrumentation(ComponentName className,
11999 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012000 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012001 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012002 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012003 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 // Refuse possible leaked file descriptors
12005 if (arguments != null && arguments.hasFileDescriptors()) {
12006 throw new IllegalArgumentException("File descriptors passed in Bundle");
12007 }
12008
12009 synchronized(this) {
12010 InstrumentationInfo ii = null;
12011 ApplicationInfo ai = null;
12012 try {
12013 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012014 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012015 ai = AppGlobals.getPackageManager().getApplicationInfo(
12016 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012018 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012019 }
12020 if (ii == null) {
12021 reportStartInstrumentationFailure(watcher, className,
12022 "Unable to find instrumentation info for: " + className);
12023 return false;
12024 }
12025 if (ai == null) {
12026 reportStartInstrumentationFailure(watcher, className,
12027 "Unable to find instrumentation target package: " + ii.targetPackage);
12028 return false;
12029 }
12030
12031 int match = mContext.getPackageManager().checkSignatures(
12032 ii.targetPackage, ii.packageName);
12033 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12034 String msg = "Permission Denial: starting instrumentation "
12035 + className + " from pid="
12036 + Binder.getCallingPid()
12037 + ", uid=" + Binder.getCallingPid()
12038 + " not allowed because package " + ii.packageName
12039 + " does not have a signature matching the target "
12040 + ii.targetPackage;
12041 reportStartInstrumentationFailure(watcher, className, msg);
12042 throw new SecurityException(msg);
12043 }
12044
12045 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012046 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012047 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012048 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012049 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012050 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012051 app.instrumentationProfileFile = profileFile;
12052 app.instrumentationArguments = arguments;
12053 app.instrumentationWatcher = watcher;
12054 app.instrumentationResultClass = className;
12055 Binder.restoreCallingIdentity(origId);
12056 }
12057
12058 return true;
12059 }
12060
12061 /**
12062 * Report errors that occur while attempting to start Instrumentation. Always writes the
12063 * error to the logs, but if somebody is watching, send the report there too. This enables
12064 * the "am" command to report errors with more information.
12065 *
12066 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12067 * @param cn The component name of the instrumentation.
12068 * @param report The error report.
12069 */
12070 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12071 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012072 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073 try {
12074 if (watcher != null) {
12075 Bundle results = new Bundle();
12076 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12077 results.putString("Error", report);
12078 watcher.instrumentationStatus(cn, -1, results);
12079 }
12080 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012081 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012082 }
12083 }
12084
12085 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12086 if (app.instrumentationWatcher != null) {
12087 try {
12088 // NOTE: IInstrumentationWatcher *must* be oneway here
12089 app.instrumentationWatcher.instrumentationFinished(
12090 app.instrumentationClass,
12091 resultCode,
12092 results);
12093 } catch (RemoteException e) {
12094 }
12095 }
12096 app.instrumentationWatcher = null;
12097 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012098 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012099 app.instrumentationProfileFile = null;
12100 app.instrumentationArguments = null;
12101
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012102 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 }
12104
12105 public void finishInstrumentation(IApplicationThread target,
12106 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012107 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012108 // Refuse possible leaked file descriptors
12109 if (results != null && results.hasFileDescriptors()) {
12110 throw new IllegalArgumentException("File descriptors passed in Intent");
12111 }
12112
12113 synchronized(this) {
12114 ProcessRecord app = getRecordForAppLocked(target);
12115 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012116 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 return;
12118 }
12119 final long origId = Binder.clearCallingIdentity();
12120 finishInstrumentationLocked(app, resultCode, results);
12121 Binder.restoreCallingIdentity(origId);
12122 }
12123 }
12124
12125 // =========================================================
12126 // CONFIGURATION
12127 // =========================================================
12128
12129 public ConfigurationInfo getDeviceConfigurationInfo() {
12130 ConfigurationInfo config = new ConfigurationInfo();
12131 synchronized (this) {
12132 config.reqTouchScreen = mConfiguration.touchscreen;
12133 config.reqKeyboardType = mConfiguration.keyboard;
12134 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012135 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12136 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012137 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12138 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012139 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12140 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012141 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12142 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012143 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012144 }
12145 return config;
12146 }
12147
12148 public Configuration getConfiguration() {
12149 Configuration ci;
12150 synchronized(this) {
12151 ci = new Configuration(mConfiguration);
12152 }
12153 return ci;
12154 }
12155
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012156 public void updatePersistentConfiguration(Configuration values) {
12157 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12158 "updateConfiguration()");
12159 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12160 "updateConfiguration()");
12161 if (values == null) {
12162 throw new NullPointerException("Configuration must not be null");
12163 }
12164
12165 synchronized(this) {
12166 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012167 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012168 Binder.restoreCallingIdentity(origId);
12169 }
12170 }
12171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012172 public void updateConfiguration(Configuration values) {
12173 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12174 "updateConfiguration()");
12175
12176 synchronized(this) {
12177 if (values == null && mWindowManager != null) {
12178 // sentinel: fetch the current configuration from the window manager
12179 values = mWindowManager.computeNewConfiguration();
12180 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012181
12182 if (mWindowManager != null) {
12183 mProcessList.applyDisplaySize(mWindowManager);
12184 }
12185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012187 if (values != null) {
12188 Settings.System.clearConfiguration(values);
12189 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012190 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 Binder.restoreCallingIdentity(origId);
12192 }
12193 }
12194
12195 /**
12196 * Do either or both things: (1) change the current configuration, and (2)
12197 * make sure the given activity is running with the (now) current
12198 * configuration. Returns true if the activity has been left running, or
12199 * false if <var>starting</var> is being destroyed to match the new
12200 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012201 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012203 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012204 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012205 // do nothing if we are headless
12206 if (mHeadless) return true;
12207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012208 int changes = 0;
12209
12210 boolean kept = true;
12211
12212 if (values != null) {
12213 Configuration newConfig = new Configuration(mConfiguration);
12214 changes = newConfig.updateFrom(values);
12215 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012216 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012217 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 }
12219
Doug Zongker2bec3d42009-12-04 12:52:44 -080012220 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012221
Dianne Hackborn813075a62011-11-14 17:45:19 -080012222 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 saveLocaleLocked(values.locale,
12224 !values.locale.equals(mConfiguration.locale),
12225 values.userSetLocale);
12226 }
12227
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012228 mConfigurationSeq++;
12229 if (mConfigurationSeq <= 0) {
12230 mConfigurationSeq = 1;
12231 }
12232 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012233 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012234 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012235
12236 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012237
12238 // TODO: If our config changes, should we auto dismiss any currently
12239 // showing dialogs?
12240 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012241
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012242 AttributeCache ac = AttributeCache.instance();
12243 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012244 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012246
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012247 // Make sure all resources in our process are updated
12248 // right now, so that anyone who is going to retrieve
12249 // resource values after we return will be sure to get
12250 // the new ones. This is especially important during
12251 // boot, where the first config change needs to guarantee
12252 // all resources have that config before following boot
12253 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012254 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012255
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012256 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012257 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012258 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012259 mHandler.sendMessage(msg);
12260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012261
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012262 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12263 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012264 try {
12265 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012266 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012267 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012268 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012269 }
12270 } catch (Exception e) {
12271 }
12272 }
12273 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012274 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12275 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012276 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012277 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012278 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12279 broadcastIntentLocked(null, null,
12280 new Intent(Intent.ACTION_LOCALE_CHANGED),
12281 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012282 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284 }
12285 }
12286
12287 if (changes != 0 && starting == null) {
12288 // If the configuration changed, and the caller is not already
12289 // in the process of starting an activity, then find the top
12290 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012291 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012292 }
12293
12294 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012295 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012296 // And we need to make sure at this point that all other activities
12297 // are made visible with the correct configuration.
12298 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012299 }
12300
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012301 if (values != null && mWindowManager != null) {
12302 mWindowManager.setNewConfiguration(mConfiguration);
12303 }
12304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305 return kept;
12306 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012307
12308 /**
12309 * Decide based on the configuration whether we should shouw the ANR,
12310 * crash, etc dialogs. The idea is that if there is no affordnace to
12311 * press the on-screen buttons, we shouldn't show the dialog.
12312 *
12313 * A thought: SystemUI might also want to get told about this, the Power
12314 * dialog / global actions also might want different behaviors.
12315 */
12316 private static final boolean shouldShowDialogs(Configuration config) {
12317 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12318 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320
12321 /**
12322 * Save the locale. You must be inside a synchronized (this) block.
12323 */
12324 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12325 if(isDiff) {
12326 SystemProperties.set("user.language", l.getLanguage());
12327 SystemProperties.set("user.region", l.getCountry());
12328 }
12329
12330 if(isPersist) {
12331 SystemProperties.set("persist.sys.language", l.getLanguage());
12332 SystemProperties.set("persist.sys.country", l.getCountry());
12333 SystemProperties.set("persist.sys.localevar", l.getVariant());
12334 }
12335 }
12336
Adam Powelldd8fab22012-03-22 17:47:27 -070012337 @Override
12338 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12339 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012340 return srec != null && srec.task.affinity != null &&
12341 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012342 }
12343
12344 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12345 Intent resultData) {
12346 ComponentName dest = destIntent.getComponent();
12347
12348 synchronized (this) {
12349 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012350 if (srec == null) {
12351 return false;
12352 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012353 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12354 final int start = history.indexOf(srec);
12355 if (start < 0) {
12356 // Current activity is not in history stack; do nothing.
12357 return false;
12358 }
12359 int finishTo = start - 1;
12360 ActivityRecord parent = null;
12361 boolean foundParentInTask = false;
12362 if (dest != null) {
12363 TaskRecord tr = srec.task;
12364 for (int i = start - 1; i >= 0; i--) {
12365 ActivityRecord r = history.get(i);
12366 if (tr != r.task) {
12367 // Couldn't find parent in the same task; stop at the one above this.
12368 // (Root of current task; in-app "home" behavior)
12369 // Always at least finish the current activity.
12370 finishTo = Math.min(start - 1, i + 1);
12371 parent = history.get(finishTo);
12372 break;
12373 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12374 r.info.name.equals(dest.getClassName())) {
12375 finishTo = i;
12376 parent = r;
12377 foundParentInTask = true;
12378 break;
12379 }
12380 }
12381 }
12382
12383 if (mController != null) {
12384 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12385 if (next != null) {
12386 // ask watcher if this is allowed
12387 boolean resumeOK = true;
12388 try {
12389 resumeOK = mController.activityResuming(next.packageName);
12390 } catch (RemoteException e) {
12391 mController = null;
12392 }
12393
12394 if (!resumeOK) {
12395 return false;
12396 }
12397 }
12398 }
12399 final long origId = Binder.clearCallingIdentity();
12400 for (int i = start; i > finishTo; i--) {
12401 ActivityRecord r = history.get(i);
12402 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012403 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012404 // Only return the supplied result for the first activity finished
12405 resultCode = Activity.RESULT_CANCELED;
12406 resultData = null;
12407 }
12408
12409 if (parent != null && foundParentInTask) {
12410 final int parentLaunchMode = parent.info.launchMode;
12411 final int destIntentFlags = destIntent.getFlags();
12412 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12413 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12414 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12415 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012416 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012417 } else {
12418 try {
12419 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012420 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012421 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12422 null, aInfo, parent.appToken, null,
12423 0, -1, parent.launchedFromUid, 0, null, true, null);
12424 foundParentInTask = res == ActivityManager.START_SUCCESS;
12425 } catch (RemoteException e) {
12426 foundParentInTask = false;
12427 }
12428 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012429 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012430 }
12431 }
12432 Binder.restoreCallingIdentity(origId);
12433 return foundParentInTask;
12434 }
12435 }
12436
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012437 public int getLaunchedFromUid(IBinder activityToken) {
12438 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12439 if (srec == null) {
12440 return -1;
12441 }
12442 return srec.launchedFromUid;
12443 }
12444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 // =========================================================
12446 // LIFETIME MANAGEMENT
12447 // =========================================================
12448
Christopher Tatef46723b2012-01-26 14:19:24 -080012449 // Returns which broadcast queue the app is the current [or imminent] receiver
12450 // on, or 'null' if the app is not an active broadcast recipient.
12451 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12452 BroadcastRecord r = app.curReceiver;
12453 if (r != null) {
12454 return r.queue;
12455 }
12456
12457 // It's not the current receiver, but it might be starting up to become one
12458 synchronized (this) {
12459 for (BroadcastQueue queue : mBroadcastQueues) {
12460 r = queue.mPendingBroadcast;
12461 if (r != null && r.curApp == app) {
12462 // found it; report which queue it's in
12463 return queue;
12464 }
12465 }
12466 }
12467
12468 return null;
12469 }
12470
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012471 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012472 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012473 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012474 // This adjustment has already been computed. If we are calling
12475 // from the top, we may have already computed our adjustment with
12476 // an earlier hidden adjustment that isn't really for us... if
12477 // so, use the new hidden adjustment.
12478 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012479 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12480 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012481 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012482 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012483 }
12484
12485 if (app.thread == null) {
12486 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012487 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012488 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 }
12490
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012491 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12492 app.adjSource = null;
12493 app.adjTarget = null;
12494 app.empty = false;
12495 app.hidden = false;
12496
12497 final int activitiesSize = app.activities.size();
12498
Dianne Hackborn7d608422011-08-07 16:24:18 -070012499 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012500 // The max adjustment doesn't allow this app to be anything
12501 // below foreground, so it is not worth doing work for it.
12502 app.adjType = "fixed";
12503 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012504 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012505 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012506 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012507 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012508 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012509 // System process can do UI, and when they do we want to have
12510 // them trim their memory after the user leaves the UI. To
12511 // facilitate this, here we need to determine whether or not it
12512 // is currently showing UI.
12513 app.systemNoUi = true;
12514 if (app == TOP_APP) {
12515 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012516 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012517 } else if (activitiesSize > 0) {
12518 for (int j = 0; j < activitiesSize; j++) {
12519 final ActivityRecord r = app.activities.get(j);
12520 if (r.visible) {
12521 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012522 }
12523 if (r.app == app) {
12524 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012525 }
12526 }
12527 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012528 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012529 }
12530
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012531 app.keeping = false;
12532 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012533 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012534
The Android Open Source Project4df24232009-03-05 14:34:35 -080012535 // Determine the importance of the process, starting with most
12536 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012537 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012538 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012539 boolean foregroundActivities = false;
12540 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012541 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012542 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012543 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012544 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012545 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012546 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012547 foregroundActivities = true;
12548 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012549 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012550 } else if (app.instrumentationClass != null) {
12551 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012552 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012553 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012554 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012555 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012556 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012557 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012558 // counts as being in the foreground for OOM killer purposes.
12559 // It's placed in a sched group based on the nature of the
12560 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012561 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012562 schedGroup = (queue == mFgBroadcastQueue)
12563 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012564 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012565 } else if (app.executingServices.size() > 0) {
12566 // An app that is currently executing a service callback also
12567 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012568 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012569 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012570 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012571 } else {
12572 // Assume process is hidden (has activities); we will correct
12573 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012574 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012575 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012576 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012577 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012578 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012579
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012580 boolean hasStoppingActivities = false;
12581
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012582 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012583 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012584 for (int j = 0; j < activitiesSize; j++) {
12585 final ActivityRecord r = app.activities.get(j);
12586 if (r.visible) {
12587 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012588 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12589 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012590 app.adjType = "visible";
12591 }
12592 schedGroup = Process.THREAD_GROUP_DEFAULT;
12593 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012594 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012595 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012596 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012597 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012598 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12599 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012600 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012601 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012602 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012603 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012604 } else if (r.state == ActivityState.STOPPING) {
12605 // We will apply the actual adjustment later, because
12606 // we want to allow this process to immediately go through
12607 // any memory trimming that is in effect.
12608 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012609 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012610 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012611 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012612 if (r.app == app) {
12613 app.hasActivities = true;
12614 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012615 }
12616 }
12617
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012618 if (adj == hiddenAdj && !app.hasActivities) {
12619 // Whoops, this process is completely empty as far as we know
12620 // at this point.
12621 adj = emptyAdj;
12622 app.empty = true;
12623 app.adjType = "bg-empty";
12624 }
12625
Dianne Hackborn7d608422011-08-07 16:24:18 -070012626 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012627 if (app.foregroundServices) {
12628 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012629 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012630 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012631 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012632 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012633 } else if (app.forcingToForeground != null) {
12634 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012635 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012636 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012637 app.adjType = "force-foreground";
12638 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012639 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012640 }
12641 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012642
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012643 if (app.foregroundServices) {
12644 interesting = true;
12645 }
12646
Dianne Hackborn7d608422011-08-07 16:24:18 -070012647 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012648 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012649 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012650 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012651 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012652 app.adjType = "heavy";
12653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012654
Dianne Hackborn7d608422011-08-07 16:24:18 -070012655 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012656 // This process is hosting what we currently consider to be the
12657 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012658 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012659 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012660 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012661 app.adjType = "home";
12662 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012663
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012664 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12665 && app.activities.size() > 0) {
12666 // This was the previous process that showed UI to the user.
12667 // We want to try to keep it around more aggressively, to give
12668 // a good experience around switching between two apps.
12669 adj = ProcessList.PREVIOUS_APP_ADJ;
12670 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12671 app.hidden = false;
12672 app.adjType = "previous";
12673 }
12674
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012675 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12676 + " reason=" + app.adjType);
12677
The Android Open Source Project4df24232009-03-05 14:34:35 -080012678 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679 // there are applications dependent on our services or providers, but
12680 // this gives us a baseline and makes sure we don't get into an
12681 // infinite recursion.
12682 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012683 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684
Christopher Tate6fa95972009-06-05 18:43:55 -070012685 if (mBackupTarget != null && app == mBackupTarget.app) {
12686 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012687 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012688 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012689 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012690 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012691 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012692 }
12693 }
12694
Dianne Hackborn7d608422011-08-07 16:24:18 -070012695 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012696 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012697 final long now = SystemClock.uptimeMillis();
12698 // This process is more important if the top activity is
12699 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012700 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012701 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012702 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012703 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012704 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012705 // If this process has shown some UI, let it immediately
12706 // go to the LRU list because it may be pretty heavy with
12707 // UI stuff. We'll tag it with a label just to help
12708 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012709 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012710 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012711 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012712 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012713 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012714 // This service has seen some activity within
12715 // recent memory, so we will keep its process ahead
12716 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012717 if (adj > ProcessList.SERVICE_ADJ) {
12718 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012719 app.adjType = "started-services";
12720 app.hidden = false;
12721 }
12722 }
12723 // If we have let the service slide into the background
12724 // state, still have some text describing what it is doing
12725 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012726 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012727 app.adjType = "started-bg-services";
12728 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012729 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012730 // Don't kill this process because it is doing work; it
12731 // has said it is doing work.
12732 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012734 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012735 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012736 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012737 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012738 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012739 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012740 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012741 // XXX should compute this based on the max of
12742 // all connected clients.
12743 ConnectionRecord cr = clist.get(i);
12744 if (cr.binding.client == app) {
12745 // Binding to ourself is not interesting.
12746 continue;
12747 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012748 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012749 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012750 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012751 int myHiddenAdj = hiddenAdj;
12752 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012753 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012754 myHiddenAdj = client.hiddenAdj;
12755 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012756 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012757 }
12758 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012759 int myEmptyAdj = emptyAdj;
12760 if (myEmptyAdj > client.emptyAdj) {
12761 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12762 myEmptyAdj = client.emptyAdj;
12763 } else {
12764 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12765 }
12766 }
12767 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12768 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012769 String adjType = null;
12770 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12771 // Not doing bind OOM management, so treat
12772 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012773 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012774 // If this process has shown some UI, let it immediately
12775 // go to the LRU list because it may be pretty heavy with
12776 // UI stuff. We'll tag it with a label just to help
12777 // debug and understand what is going on.
12778 if (adj > clientAdj) {
12779 adjType = "bound-bg-ui-services";
12780 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012781 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012782 clientAdj = adj;
12783 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012784 if (now >= (s.lastActivity
12785 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012786 // This service has not seen activity within
12787 // recent memory, so allow it to drop to the
12788 // LRU list if there is no other reason to keep
12789 // it around. We'll also tag it with a label just
12790 // to help debug and undertand what is going on.
12791 if (adj > clientAdj) {
12792 adjType = "bound-bg-services";
12793 }
12794 clientAdj = adj;
12795 }
12796 }
12797 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012798 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012799 // If this process has recently shown UI, and
12800 // the process that is binding to it is less
12801 // important than being visible, then we don't
12802 // care about the binding as much as we care
12803 // about letting this process get into the LRU
12804 // list to be killed and restarted if needed for
12805 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012806 if (app.hasShownUi && app != mHomeProcess
12807 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012808 adjType = "bound-bg-ui-services";
12809 } else {
12810 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12811 |Context.BIND_IMPORTANT)) != 0) {
12812 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012813 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12814 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12815 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12816 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12817 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012818 adj = clientAdj;
12819 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012820 app.pendingUiClean = true;
12821 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12822 adj = ProcessList.VISIBLE_APP_ADJ;
12823 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012824 }
12825 if (!client.hidden) {
12826 app.hidden = false;
12827 }
12828 if (client.keeping) {
12829 app.keeping = true;
12830 }
12831 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012832 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012833 }
12834 if (adjType != null) {
12835 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012836 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12837 .REASON_SERVICE_IN_USE;
12838 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012839 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012840 app.adjTarget = s.name;
12841 }
12842 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12843 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12844 schedGroup = Process.THREAD_GROUP_DEFAULT;
12845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 }
12847 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012848 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12849 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012850 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012851 (a.visible || a.state == ActivityState.RESUMED
12852 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012853 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012854 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12855 schedGroup = Process.THREAD_GROUP_DEFAULT;
12856 }
12857 app.hidden = false;
12858 app.adjType = "service";
12859 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12860 .REASON_SERVICE_IN_USE;
12861 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012862 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012863 app.adjTarget = s.name;
12864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012866 }
12867 }
12868 }
12869 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012870
Dianne Hackborn287952c2010-09-22 22:34:31 -070012871 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012872 // would like to avoid killing it unless it would prevent the current
12873 // application from running. By default we put the process in
12874 // with the rest of the background processes; as we scan through
12875 // its services we may bump it up from there.
12876 if (adj > hiddenAdj) {
12877 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012878 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012879 app.adjType = "bg-services";
12880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881 }
12882
Dianne Hackborn7d608422011-08-07 16:24:18 -070012883 if (app.pubProviders.size() != 0 && (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 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012886 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012887 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012888 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012889 for (int i = cpr.connections.size()-1;
12890 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12891 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12892 i--) {
12893 ContentProviderConnection conn = cpr.connections.get(i);
12894 ProcessRecord client = conn.client;
12895 if (client == app) {
12896 // Being our own client is not interesting.
12897 continue;
12898 }
12899 int myHiddenAdj = hiddenAdj;
12900 if (myHiddenAdj > client.hiddenAdj) {
12901 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12902 myHiddenAdj = client.hiddenAdj;
12903 } else {
12904 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012905 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012906 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012907 int myEmptyAdj = emptyAdj;
12908 if (myEmptyAdj > client.emptyAdj) {
12909 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12910 myEmptyAdj = client.emptyAdj;
12911 } else {
12912 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12913 }
12914 }
12915 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12916 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012917 if (adj > clientAdj) {
12918 if (app.hasShownUi && app != mHomeProcess
12919 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12920 app.adjType = "bg-ui-provider";
12921 } else {
12922 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12923 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12924 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012925 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012926 if (!client.hidden) {
12927 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012929 if (client.keeping) {
12930 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012931 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012932 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12933 .REASON_PROVIDER_IN_USE;
12934 app.adjSource = client;
12935 app.adjSourceOom = clientAdj;
12936 app.adjTarget = cpr.name;
12937 }
12938 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12939 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 }
12941 }
12942 // If the provider has external (non-framework) process
12943 // dependencies, ensure that its adjustment is at least
12944 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012945 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012946 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12947 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012948 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012949 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012950 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012951 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012952 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 }
12954 }
12955 }
12956 }
12957
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012958 if (adj == ProcessList.SERVICE_ADJ) {
12959 if (doingAll) {
12960 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12961 mNewNumServiceProcs++;
12962 }
12963 if (app.serviceb) {
12964 adj = ProcessList.SERVICE_B_ADJ;
12965 }
12966 } else {
12967 app.serviceb = false;
12968 }
12969
12970 app.nonStoppingAdj = adj;
12971
12972 if (hasStoppingActivities) {
12973 // Only upgrade adjustment.
12974 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12975 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12976 app.adjType = "stopping";
12977 }
12978 }
12979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012980 app.curRawAdj = adj;
12981
Joe Onorato8a9b2202010-02-26 18:56:32 -080012982 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012983 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12984 if (adj > app.maxAdj) {
12985 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012986 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012987 schedGroup = Process.THREAD_GROUP_DEFAULT;
12988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012989 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012990 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012991 app.keeping = true;
12992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012994 if (app.hasAboveClient) {
12995 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12996 // then we need to drop its adjustment to be lower than the service's
12997 // in order to honor the request. We want to drop it by one adjustment
12998 // level... but there is special meaning applied to various levels so
12999 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013000 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013001 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013002 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13003 adj = ProcessList.VISIBLE_APP_ADJ;
13004 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13005 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13006 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13007 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013008 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013009 adj++;
13010 }
13011 }
13012
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013013 int importance = app.memImportance;
13014 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13015 app.curAdj = adj;
13016 app.curSchedGroup = schedGroup;
13017 if (!interesting) {
13018 // For this reporting, if there is not something explicitly
13019 // interesting in this process then we will push it to the
13020 // background importance.
13021 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13022 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13023 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13024 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13025 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13026 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13027 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13028 } else if (adj >= ProcessList.SERVICE_ADJ) {
13029 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13030 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13031 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13032 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13033 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13034 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13035 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13036 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13037 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13038 } else {
13039 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13040 }
13041 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013042
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013043 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13044 if (foregroundActivities != app.foregroundActivities) {
13045 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13046 }
13047 if (changes != 0) {
13048 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13049 app.memImportance = importance;
13050 app.foregroundActivities = foregroundActivities;
13051 int i = mPendingProcessChanges.size()-1;
13052 ProcessChangeItem item = null;
13053 while (i >= 0) {
13054 item = mPendingProcessChanges.get(i);
13055 if (item.pid == app.pid) {
13056 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13057 break;
13058 }
13059 i--;
13060 }
13061 if (i < 0) {
13062 // No existing item in pending changes; need a new one.
13063 final int NA = mAvailProcessChanges.size();
13064 if (NA > 0) {
13065 item = mAvailProcessChanges.remove(NA-1);
13066 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13067 } else {
13068 item = new ProcessChangeItem();
13069 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13070 }
13071 item.changes = 0;
13072 item.pid = app.pid;
13073 item.uid = app.info.uid;
13074 if (mPendingProcessChanges.size() == 0) {
13075 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13076 "*** Enqueueing dispatch processes changed!");
13077 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13078 }
13079 mPendingProcessChanges.add(item);
13080 }
13081 item.changes |= changes;
13082 item.importance = importance;
13083 item.foregroundActivities = foregroundActivities;
13084 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13085 + Integer.toHexString(System.identityHashCode(item))
13086 + " " + app.toShortString() + ": changes=" + item.changes
13087 + " importance=" + item.importance
13088 + " foreground=" + item.foregroundActivities
13089 + " type=" + app.adjType + " source=" + app.adjSource
13090 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013091 }
13092
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013093 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 }
13095
13096 /**
13097 * Ask a given process to GC right now.
13098 */
13099 final void performAppGcLocked(ProcessRecord app) {
13100 try {
13101 app.lastRequestedGc = SystemClock.uptimeMillis();
13102 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013103 if (app.reportLowMemory) {
13104 app.reportLowMemory = false;
13105 app.thread.scheduleLowMemory();
13106 } else {
13107 app.thread.processInBackground();
13108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013109 }
13110 } catch (Exception e) {
13111 // whatever.
13112 }
13113 }
13114
13115 /**
13116 * Returns true if things are idle enough to perform GCs.
13117 */
Josh Bartel7f208742010-02-25 11:01:44 -060013118 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013119 boolean processingBroadcasts = false;
13120 for (BroadcastQueue q : mBroadcastQueues) {
13121 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13122 processingBroadcasts = true;
13123 }
13124 }
13125 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013126 && (mSleeping || (mMainStack.mResumedActivity != null &&
13127 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128 }
13129
13130 /**
13131 * Perform GCs on all processes that are waiting for it, but only
13132 * if things are idle.
13133 */
13134 final void performAppGcsLocked() {
13135 final int N = mProcessesToGc.size();
13136 if (N <= 0) {
13137 return;
13138 }
Josh Bartel7f208742010-02-25 11:01:44 -060013139 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013140 while (mProcessesToGc.size() > 0) {
13141 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013142 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013143 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13144 <= SystemClock.uptimeMillis()) {
13145 // To avoid spamming the system, we will GC processes one
13146 // at a time, waiting a few seconds between each.
13147 performAppGcLocked(proc);
13148 scheduleAppGcsLocked();
13149 return;
13150 } else {
13151 // It hasn't been long enough since we last GCed this
13152 // process... put it in the list to wait for its time.
13153 addProcessToGcListLocked(proc);
13154 break;
13155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013156 }
13157 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013158
13159 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013160 }
13161 }
13162
13163 /**
13164 * If all looks good, perform GCs on all processes waiting for them.
13165 */
13166 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013167 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013168 performAppGcsLocked();
13169 return;
13170 }
13171 // Still not idle, wait some more.
13172 scheduleAppGcsLocked();
13173 }
13174
13175 /**
13176 * Schedule the execution of all pending app GCs.
13177 */
13178 final void scheduleAppGcsLocked() {
13179 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013180
13181 if (mProcessesToGc.size() > 0) {
13182 // Schedule a GC for the time to the next process.
13183 ProcessRecord proc = mProcessesToGc.get(0);
13184 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13185
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013186 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013187 long now = SystemClock.uptimeMillis();
13188 if (when < (now+GC_TIMEOUT)) {
13189 when = now + GC_TIMEOUT;
13190 }
13191 mHandler.sendMessageAtTime(msg, when);
13192 }
13193 }
13194
13195 /**
13196 * Add a process to the array of processes waiting to be GCed. Keeps the
13197 * list in sorted order by the last GC time. The process can't already be
13198 * on the list.
13199 */
13200 final void addProcessToGcListLocked(ProcessRecord proc) {
13201 boolean added = false;
13202 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13203 if (mProcessesToGc.get(i).lastRequestedGc <
13204 proc.lastRequestedGc) {
13205 added = true;
13206 mProcessesToGc.add(i+1, proc);
13207 break;
13208 }
13209 }
13210 if (!added) {
13211 mProcessesToGc.add(0, proc);
13212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 }
13214
13215 /**
13216 * Set up to ask a process to GC itself. This will either do it
13217 * immediately, or put it on the list of processes to gc the next
13218 * time things are idle.
13219 */
13220 final void scheduleAppGcLocked(ProcessRecord app) {
13221 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013222 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223 return;
13224 }
13225 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013226 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013227 scheduleAppGcsLocked();
13228 }
13229 }
13230
Dianne Hackborn287952c2010-09-22 22:34:31 -070013231 final void checkExcessivePowerUsageLocked(boolean doKills) {
13232 updateCpuStatsNow();
13233
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013234 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013235 boolean doWakeKills = doKills;
13236 boolean doCpuKills = doKills;
13237 if (mLastPowerCheckRealtime == 0) {
13238 doWakeKills = false;
13239 }
13240 if (mLastPowerCheckUptime == 0) {
13241 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013242 }
13243 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013244 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013245 }
13246 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013247 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13248 final long curUptime = SystemClock.uptimeMillis();
13249 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13250 mLastPowerCheckRealtime = curRealtime;
13251 mLastPowerCheckUptime = curUptime;
13252 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13253 doWakeKills = false;
13254 }
13255 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13256 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013257 }
13258 int i = mLruProcesses.size();
13259 while (i > 0) {
13260 i--;
13261 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013262 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013263 long wtime;
13264 synchronized (stats) {
13265 wtime = stats.getProcessWakeTime(app.info.uid,
13266 app.pid, curRealtime);
13267 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013268 long wtimeUsed = wtime - app.lastWakeTime;
13269 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13270 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013271 StringBuilder sb = new StringBuilder(128);
13272 sb.append("Wake for ");
13273 app.toShortString(sb);
13274 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013275 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013276 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013277 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013278 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013279 sb.append((wtimeUsed*100)/realtimeSince);
13280 sb.append("%)");
13281 Slog.i(TAG, sb.toString());
13282 sb.setLength(0);
13283 sb.append("CPU for ");
13284 app.toShortString(sb);
13285 sb.append(": over ");
13286 TimeUtils.formatDuration(uptimeSince, sb);
13287 sb.append(" used ");
13288 TimeUtils.formatDuration(cputimeUsed, sb);
13289 sb.append(" (");
13290 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013291 sb.append("%)");
13292 Slog.i(TAG, sb.toString());
13293 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013294 // If a process has held a wake lock for more
13295 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013296 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013297 if (doWakeKills && realtimeSince > 0
13298 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13299 synchronized (stats) {
13300 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13301 realtimeSince, wtimeUsed);
13302 }
13303 Slog.w(TAG, "Excessive wake lock in " + app.processName
13304 + " (pid " + app.pid + "): held " + wtimeUsed
13305 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013306 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13307 app.processName, app.setAdj, "excessive wake lock");
13308 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013309 } else if (doCpuKills && uptimeSince > 0
13310 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13311 synchronized (stats) {
13312 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13313 uptimeSince, cputimeUsed);
13314 }
13315 Slog.w(TAG, "Excessive CPU in " + app.processName
13316 + " (pid " + app.pid + "): used " + cputimeUsed
13317 + " during " + uptimeSince);
13318 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13319 app.processName, app.setAdj, "excessive cpu");
13320 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013321 } else {
13322 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013323 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013324 }
13325 }
13326 }
13327 }
13328
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013329 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13330 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013332 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333
13334 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013335 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013336 }
13337
Dianne Hackborn287952c2010-09-22 22:34:31 -070013338 final boolean wasKeeping = app.keeping;
13339
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013340 boolean success = true;
13341
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013342 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013343
Jeff Brown10e89712011-07-08 18:52:57 -070013344 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013345 if (wasKeeping && !app.keeping) {
13346 // This app is no longer something we want to keep. Note
13347 // its current wake lock time to later know to kill it if
13348 // it is not behaving well.
13349 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13350 synchronized (stats) {
13351 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13352 app.pid, SystemClock.elapsedRealtime());
13353 }
13354 app.lastCpuTime = app.curCpuTime;
13355 }
13356
13357 app.setRawAdj = app.curRawAdj;
13358 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013359
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013360 if (app.curAdj != app.setAdj) {
13361 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013362 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013363 TAG, "Set " + app.pid + " " + app.processName +
13364 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013365 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013366 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013367 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013368 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013369 }
13370 }
13371 if (app.setSchedGroup != app.curSchedGroup) {
13372 app.setSchedGroup = app.curSchedGroup;
13373 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13374 "Setting process group of " + app.processName
13375 + " to " + app.curSchedGroup);
13376 if (app.waitingToKill != null &&
13377 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13378 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13379 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13380 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013381 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013382 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013383 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013384 } else {
13385 if (true) {
13386 long oldId = Binder.clearCallingIdentity();
13387 try {
13388 Process.setProcessGroup(app.pid, app.curSchedGroup);
13389 } catch (Exception e) {
13390 Slog.w(TAG, "Failed setting process group of " + app.pid
13391 + " to " + app.curSchedGroup);
13392 e.printStackTrace();
13393 } finally {
13394 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013395 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013396 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013397 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013398 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013399 app.thread.setSchedulingGroup(app.curSchedGroup);
13400 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013401 }
13402 }
13403 }
13404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013405 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013406 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 }
13408
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013409 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013410 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013411 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013412 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013414 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013415 }
13416 }
13417 return resumedActivity;
13418 }
13419
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013420 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013421 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013422 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13423 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013424 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13425 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013426
13427 mAdjSeq++;
13428
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013429 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13430 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013431 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13432 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013433 if (nowHidden != wasHidden) {
13434 // Changed to/from hidden state, so apps after it in the LRU
13435 // list may also be changed.
13436 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013437 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013438 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013439 }
13440
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013441 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013442 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013443 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13444
13445 if (false) {
13446 RuntimeException e = new RuntimeException();
13447 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013448 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013449 }
13450
13451 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013452 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013453
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013454 // Let's determine how many processes we have running vs.
13455 // how many slots we have for background processes; we may want
13456 // to put multiple processes in a slot of there are enough of
13457 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013458 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13459 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13460 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13461 if (emptyFactor < 1) emptyFactor = 1;
13462 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13463 if (hiddenFactor < 1) hiddenFactor = 1;
13464 int stepHidden = 0;
13465 int stepEmpty = 0;
13466 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13467 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013468 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013469 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013470 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013471
13472 mNumNonHiddenProcs = 0;
13473 mNumHiddenProcs = 0;
13474
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013475 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013476 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013477 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013478 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013479 int nextHiddenAdj = curHiddenAdj+1;
13480 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13481 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013482 while (i > 0) {
13483 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013484 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013485 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013486 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013487 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013488 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13489 // This process was assigned as a hidden process... step the
13490 // hidden level.
13491 mNumHiddenProcs++;
13492 if (curHiddenAdj != nextHiddenAdj) {
13493 stepHidden++;
13494 if (stepHidden >= hiddenFactor) {
13495 stepHidden = 0;
13496 curHiddenAdj = nextHiddenAdj;
13497 nextHiddenAdj += 2;
13498 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13499 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13500 }
13501 }
13502 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013503 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013504 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013505 Slog.i(TAG, "No longer want " + app.processName
13506 + " (pid " + app.pid + "): hidden #" + numHidden);
13507 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13508 app.processName, app.setAdj, "too many background");
13509 app.killedBackground = true;
13510 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013511 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013512 } else {
13513 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13514 // This process was assigned as an empty process... step the
13515 // empty level.
13516 if (curEmptyAdj != nextEmptyAdj) {
13517 stepEmpty++;
13518 if (stepEmpty >= emptyFactor) {
13519 stepEmpty = 0;
13520 curEmptyAdj = nextEmptyAdj;
13521 nextEmptyAdj += 2;
13522 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13523 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13524 }
13525 }
13526 }
13527 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13528 mNumNonHiddenProcs++;
13529 }
13530 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13531 numEmpty++;
13532 if (numEmpty > emptyProcessLimit) {
13533 Slog.i(TAG, "No longer want " + app.processName
13534 + " (pid " + app.pid + "): empty #" + numEmpty);
13535 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13536 app.processName, app.setAdj, "too many background");
13537 app.killedBackground = true;
13538 Process.killProcessQuiet(app.pid);
13539 }
13540 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013541 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013542 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013543 // If this is an isolated process, and there are no
13544 // services running in it, then the process is no longer
13545 // needed. We agressively kill these because we can by
13546 // definition not re-use the same process again, and it is
13547 // good to avoid having whatever code was running in them
13548 // left sitting around after no longer needed.
13549 Slog.i(TAG, "Isolated process " + app.processName
13550 + " (pid " + app.pid + ") no longer needed");
13551 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13552 app.processName, app.setAdj, "isolated not needed");
13553 app.killedBackground = true;
13554 Process.killProcessQuiet(app.pid);
13555 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013556 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13557 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13558 && !app.killedBackground) {
13559 numTrimming++;
13560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013561 }
13562 }
13563
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013564 mNumServiceProcs = mNewNumServiceProcs;
13565
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013566 // Now determine the memory trimming level of background processes.
13567 // Unfortunately we need to start at the back of the list to do this
13568 // properly. We only do this if the number of background apps we
13569 // are managing to keep around is less than half the maximum we desire;
13570 // if we are keeping a good number around, we'll let them use whatever
13571 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013572 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13573 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13574 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013575 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013576 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013577 int minFactor = 2;
13578 if (mHomeProcess != null) minFactor++;
13579 if (mPreviousProcess != null) minFactor++;
13580 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013581 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013582 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013583 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013584 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013585 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013586 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13587 } else {
13588 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13589 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013590 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013591 for (i=0; i<N; i++) {
13592 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013593 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13594 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013595 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013596 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13597 try {
13598 app.thread.scheduleTrimMemory(curLevel);
13599 } catch (RemoteException e) {
13600 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013601 if (false) {
13602 // For now we won't do this; our memory trimming seems
13603 // to be good enough at this point that destroying
13604 // activities causes more harm than good.
13605 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13606 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013607 // Need to do this on its own message because the stack may not
13608 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013609 // For these apps we will also finish their activities
13610 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013611 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013612 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013613 }
13614 }
13615 app.trimMemoryLevel = curLevel;
13616 step++;
13617 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013618 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013619 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013620 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13621 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013622 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013623 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13624 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013625 break;
13626 }
13627 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013628 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013629 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013630 && app.thread != null) {
13631 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013632 app.thread.scheduleTrimMemory(
13633 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013634 } catch (RemoteException e) {
13635 }
13636 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013637 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013638 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013639 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013640 && app.pendingUiClean) {
13641 // If this application is now in the background and it
13642 // had done UI, then give it the special trim level to
13643 // have it free UI resources.
13644 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13645 if (app.trimMemoryLevel < level && app.thread != null) {
13646 try {
13647 app.thread.scheduleTrimMemory(level);
13648 } catch (RemoteException e) {
13649 }
13650 }
13651 app.pendingUiClean = false;
13652 }
13653 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013654 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013655 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013656 } catch (RemoteException e) {
13657 }
13658 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013659 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013660 }
13661 }
13662 } else {
13663 final int N = mLruProcesses.size();
13664 for (i=0; i<N; i++) {
13665 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013666 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013667 && app.pendingUiClean) {
13668 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13669 && app.thread != null) {
13670 try {
13671 app.thread.scheduleTrimMemory(
13672 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13673 } catch (RemoteException e) {
13674 }
13675 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013676 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013677 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013678 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013679 }
13680 }
13681
13682 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013683 // Need to do this on its own message because the stack may not
13684 // be in a consistent state at this point.
13685 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 }
13688
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013689 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013690 synchronized (this) {
13691 int i;
13692
13693 // First remove any unused application processes whose package
13694 // has been removed.
13695 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13696 final ProcessRecord app = mRemovedProcesses.get(i);
13697 if (app.activities.size() == 0
13698 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013699 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 TAG, "Exiting empty application process "
13701 + app.processName + " ("
13702 + (app.thread != null ? app.thread.asBinder() : null)
13703 + ")\n");
13704 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013705 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13706 app.processName, app.setAdj, "empty");
13707 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013708 } else {
13709 try {
13710 app.thread.scheduleExit();
13711 } catch (Exception e) {
13712 // Ignore exceptions.
13713 }
13714 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013715 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013716 mRemovedProcesses.remove(i);
13717
13718 if (app.persistent) {
13719 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013720 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013721 }
13722 }
13723 }
13724 }
13725
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013726 // Now update the oom adj for all processes.
13727 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013728 }
13729 }
13730
13731 /** This method sends the specified signal to each of the persistent apps */
13732 public void signalPersistentProcesses(int sig) throws RemoteException {
13733 if (sig != Process.SIGNAL_USR1) {
13734 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13735 }
13736
13737 synchronized (this) {
13738 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13739 != PackageManager.PERMISSION_GRANTED) {
13740 throw new SecurityException("Requires permission "
13741 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13742 }
13743
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013744 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13745 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013746 if (r.thread != null && r.persistent) {
13747 Process.sendSignal(r.pid, sig);
13748 }
13749 }
13750 }
13751 }
13752
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013753 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13754 if (proc == null || proc == mProfileProc) {
13755 proc = mProfileProc;
13756 path = mProfileFile;
13757 profileType = mProfileType;
13758 clearProfilerLocked();
13759 }
13760 if (proc == null) {
13761 return;
13762 }
13763 try {
13764 proc.thread.profilerControl(false, path, null, profileType);
13765 } catch (RemoteException e) {
13766 throw new IllegalStateException("Process disappeared");
13767 }
13768 }
13769
13770 private void clearProfilerLocked() {
13771 if (mProfileFd != null) {
13772 try {
13773 mProfileFd.close();
13774 } catch (IOException e) {
13775 }
13776 }
13777 mProfileApp = null;
13778 mProfileProc = null;
13779 mProfileFile = null;
13780 mProfileType = 0;
13781 mAutoStopProfiler = false;
13782 }
13783
Dianne Hackborn1676c852012-09-10 14:52:30 -070013784 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013785 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013786
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013787 try {
13788 synchronized (this) {
13789 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13790 // its own permission.
13791 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13792 != PackageManager.PERMISSION_GRANTED) {
13793 throw new SecurityException("Requires permission "
13794 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013795 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013796
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013797 if (start && fd == null) {
13798 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013799 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013800
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013801 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013802 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013803 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013804 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013805
13806 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013807 throw new IllegalArgumentException("Unknown process: " + process);
13808 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013809
13810 if (start) {
13811 stopProfilerLocked(null, null, 0);
13812 setProfileApp(proc.info, proc.processName, path, fd, false);
13813 mProfileProc = proc;
13814 mProfileType = profileType;
13815 try {
13816 fd = fd.dup();
13817 } catch (IOException e) {
13818 fd = null;
13819 }
13820 proc.thread.profilerControl(start, path, fd, profileType);
13821 fd = null;
13822 mProfileFd = null;
13823 } else {
13824 stopProfilerLocked(proc, path, profileType);
13825 if (fd != null) {
13826 try {
13827 fd.close();
13828 } catch (IOException e) {
13829 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013830 }
13831 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013832
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013833 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013834 }
13835 } catch (RemoteException e) {
13836 throw new IllegalStateException("Process disappeared");
13837 } finally {
13838 if (fd != null) {
13839 try {
13840 fd.close();
13841 } catch (IOException e) {
13842 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013843 }
13844 }
13845 }
Andy McFadden824c5102010-07-09 16:26:57 -070013846
Dianne Hackborn1676c852012-09-10 14:52:30 -070013847 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070013848 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070013849 userId, true, true, callName, null);
13850 ProcessRecord proc = null;
13851 try {
13852 int pid = Integer.parseInt(process);
13853 synchronized (mPidsSelfLocked) {
13854 proc = mPidsSelfLocked.get(pid);
13855 }
13856 } catch (NumberFormatException e) {
13857 }
13858
13859 if (proc == null) {
13860 HashMap<String, SparseArray<ProcessRecord>> all
13861 = mProcessNames.getMap();
13862 SparseArray<ProcessRecord> procs = all.get(process);
13863 if (procs != null && procs.size() > 0) {
13864 proc = procs.valueAt(0);
13865 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13866 for (int i=1; i<procs.size(); i++) {
13867 ProcessRecord thisProc = procs.valueAt(i);
13868 if (thisProc.userId == userId) {
13869 proc = thisProc;
13870 break;
13871 }
13872 }
13873 }
13874 }
13875 }
13876
13877 return proc;
13878 }
13879
13880 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013881 String path, ParcelFileDescriptor fd) throws RemoteException {
13882
13883 try {
13884 synchronized (this) {
13885 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13886 // its own permission (same as profileControl).
13887 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13888 != PackageManager.PERMISSION_GRANTED) {
13889 throw new SecurityException("Requires permission "
13890 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13891 }
13892
13893 if (fd == null) {
13894 throw new IllegalArgumentException("null fd");
13895 }
13896
Dianne Hackborn1676c852012-09-10 14:52:30 -070013897 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013898 if (proc == null || proc.thread == null) {
13899 throw new IllegalArgumentException("Unknown process: " + process);
13900 }
13901
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013902 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13903 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013904 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13905 throw new SecurityException("Process not debuggable: " + proc);
13906 }
13907 }
13908
13909 proc.thread.dumpHeap(managed, path, fd);
13910 fd = null;
13911 return true;
13912 }
13913 } catch (RemoteException e) {
13914 throw new IllegalStateException("Process disappeared");
13915 } finally {
13916 if (fd != null) {
13917 try {
13918 fd.close();
13919 } catch (IOException e) {
13920 }
13921 }
13922 }
13923 }
13924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013925 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13926 public void monitor() {
13927 synchronized (this) { }
13928 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013929
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013930 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013931 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13932 ProcessRecord processRecord = mLruProcesses.get(i);
13933 try {
13934 if (processRecord.thread != null) {
13935 processRecord.thread.setCoreSettings(settings);
13936 }
13937 } catch (RemoteException re) {
13938 /* ignore */
13939 }
13940 }
13941 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013942
13943 // Multi-user methods
13944
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013945 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013946 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013947 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13948 != PackageManager.PERMISSION_GRANTED) {
13949 String msg = "Permission Denial: switchUser() from pid="
13950 + Binder.getCallingPid()
13951 + ", uid=" + Binder.getCallingUid()
13952 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13953 Slog.w(TAG, msg);
13954 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013955 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013956
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013957 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013958 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013959 synchronized (this) {
13960 final int oldUserId = mCurrentUserId;
13961 if (oldUserId == userId) {
13962 return true;
13963 }
13964
13965 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
13966 if (userInfo == null) {
13967 Slog.w(TAG, "No user info for user #" + userId);
13968 return false;
13969 }
13970
13971 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
13972 R.anim.screen_user_enter);
13973
13974 // If the user we are switching to is not currently started, then
13975 // we need to start it now.
13976 if (mStartedUsers.get(userId) == null) {
13977 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070013978 updateStartedUserArrayLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013979 }
13980
13981 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070013982 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013983 final Integer userIdInt = Integer.valueOf(userId);
13984 mUserLru.remove(userIdInt);
13985 mUserLru.add(userIdInt);
13986
Craig Mautnerf1b67412012-09-19 13:18:29 -070013987 mWindowManager.setCurrentUser(userId);
13988
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013989 final UserStartedState uss = mStartedUsers.get(userId);
13990
13991 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
13992 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
13993 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
13994 oldUserId, userId, uss));
13995 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
13996 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
13997 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
13998 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13999 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14000 broadcastIntentLocked(null, null, intent,
14001 null, null, 0, null, null, null,
14002 false, false, MY_PID, Process.SYSTEM_UID, userId);
14003
14004 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14005 if (userId != 0) {
14006 intent = new Intent(Intent.ACTION_USER_INITIALIZE);
14007 broadcastIntentLocked(null, null, intent, null,
14008 new IIntentReceiver.Stub() {
14009 public void performReceive(Intent intent, int resultCode,
14010 String data, Bundle extras, boolean ordered,
14011 boolean sticky, int sendingUser) {
14012 synchronized (ActivityManagerService.this) {
14013 getUserManagerLocked().makeInitialized(userInfo.id);
14014 }
14015 }
14016 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14017 userId);
14018 } else {
14019 getUserManagerLocked().makeInitialized(userInfo.id);
14020 }
14021 }
14022
14023 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14024 if (!haveActivities) {
14025 startHomeActivityLocked(userId);
14026 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014027
Amith Yamasani920ace02012-09-20 22:15:37 -070014028 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014029 sendUserSwitchBroadcastsLocked(oldUserId, userId);
14030 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014031 } finally {
14032 Binder.restoreCallingIdentity(ident);
14033 }
Amith Yamasani13593602012-03-22 16:16:17 -070014034
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014035 return true;
14036 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014037
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014038 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14039 long ident = Binder.clearCallingIdentity();
14040 try {
14041 Intent intent;
14042 if (oldUserId >= 0) {
14043 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
14044 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14045 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14046 broadcastIntentLocked(null, null, intent,
14047 null, null, 0, null, null, null,
14048 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14049 }
14050 if (newUserId >= 0) {
14051 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
14052 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14053 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14054 broadcastIntentLocked(null, null, intent,
14055 null, null, 0, null, null, null,
14056 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14057 intent = new Intent(Intent.ACTION_USER_SWITCHED);
14058 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14059 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14060 broadcastIntentLocked(null, null, intent,
14061 null, null, 0, null, null,
14062 android.Manifest.permission.MANAGE_USERS,
14063 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14064 }
14065 } finally {
14066 Binder.restoreCallingIdentity(ident);
14067 }
14068 }
14069
14070 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14071 final int newUserId) {
14072 final int N = mUserSwitchObservers.beginBroadcast();
14073 if (N > 0) {
14074 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14075 int mCount = 0;
14076 @Override
14077 public void sendResult(Bundle data) throws RemoteException {
14078 synchronized (ActivityManagerService.this) {
14079 if (mCurUserSwitchCallback == this) {
14080 mCount++;
14081 if (mCount == N) {
14082 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14083 }
14084 }
14085 }
14086 }
14087 };
14088 synchronized (this) {
14089 mCurUserSwitchCallback = callback;
14090 }
14091 for (int i=0; i<N; i++) {
14092 try {
14093 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14094 newUserId, callback);
14095 } catch (RemoteException e) {
14096 }
14097 }
14098 } else {
14099 synchronized (this) {
14100 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14101 }
14102 }
14103 mUserSwitchObservers.finishBroadcast();
14104 }
14105
14106 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14107 synchronized (this) {
14108 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14109 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14110 }
14111 }
14112
14113 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14114 mCurUserSwitchCallback = null;
14115 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14116 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14117 oldUserId, newUserId, uss));
14118 }
14119
14120 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14121 final int N = mUserSwitchObservers.beginBroadcast();
14122 for (int i=0; i<N; i++) {
14123 try {
14124 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14125 } catch (RemoteException e) {
14126 }
14127 }
14128 mUserSwitchObservers.finishBroadcast();
14129 synchronized (this) {
14130 mWindowManager.stopFreezingScreen();
14131 }
14132 }
14133
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014134 void finishUserSwitch(UserStartedState uss) {
14135 synchronized (this) {
14136 if (uss.mState == UserStartedState.STATE_BOOTING
14137 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14138 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014139 final int userId = uss.mHandle.getIdentifier();
14140 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14141 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14142 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014143 null, null, 0, null, null,
14144 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014145 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014146 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014147 int num = mUserLru.size();
14148 int i = 0;
14149 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14150 Integer oldUserId = mUserLru.get(i);
14151 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14152 if (oldUss == null) {
14153 // Shouldn't happen, but be sane if it does.
14154 mUserLru.remove(i);
14155 num--;
14156 continue;
14157 }
14158 if (oldUss.mState == UserStartedState.STATE_STOPPING) {
14159 // This user is already stopping, doesn't count.
14160 num--;
14161 i++;
14162 continue;
14163 }
14164 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14165 // Owner and current can't be stopped, but count as running.
14166 i++;
14167 continue;
14168 }
14169 // This is a user to be stopped.
14170 stopUserLocked(oldUserId, null);
14171 num--;
14172 i++;
14173 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014174 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014175 }
14176
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014177 @Override
14178 public int stopUser(final int userId, final IStopUserCallback callback) {
14179 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14180 != PackageManager.PERMISSION_GRANTED) {
14181 String msg = "Permission Denial: switchUser() from pid="
14182 + Binder.getCallingPid()
14183 + ", uid=" + Binder.getCallingUid()
14184 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14185 Slog.w(TAG, msg);
14186 throw new SecurityException(msg);
14187 }
14188 if (userId <= 0) {
14189 throw new IllegalArgumentException("Can't stop primary user " + userId);
14190 }
Amith Yamasani13593602012-03-22 16:16:17 -070014191 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014192 return stopUserLocked(userId, callback);
14193 }
14194 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014195
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014196 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14197 if (mCurrentUserId == userId) {
14198 return ActivityManager.USER_OP_IS_CURRENT;
14199 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014200
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014201 final UserStartedState uss = mStartedUsers.get(userId);
14202 if (uss == null) {
14203 // User is not started, nothing to do... but we do need to
14204 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014205 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014206 mHandler.post(new Runnable() {
14207 @Override
14208 public void run() {
14209 try {
14210 callback.userStopped(userId);
14211 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014212 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014213 }
14214 });
14215 }
14216 return ActivityManager.USER_OP_SUCCESS;
14217 }
14218
14219 if (callback != null) {
14220 uss.mStopCallbacks.add(callback);
14221 }
14222
14223 if (uss.mState != UserStartedState.STATE_STOPPING) {
14224 uss.mState = UserStartedState.STATE_STOPPING;
14225
14226 long ident = Binder.clearCallingIdentity();
14227 try {
14228 // Inform of user switch
14229 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
14230 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
14231 @Override
14232 public void performReceive(Intent intent, int resultCode, String data,
14233 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14234 finishUserStop(uss);
14235 }
14236 };
14237 broadcastIntentLocked(null, null, intent,
14238 null, resultReceiver, 0, null, null, null,
14239 true, false, MY_PID, Process.SYSTEM_UID, userId);
14240 } finally {
14241 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014242 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014243 }
Amith Yamasani13593602012-03-22 16:16:17 -070014244
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014245 return ActivityManager.USER_OP_SUCCESS;
14246 }
14247
14248 void finishUserStop(UserStartedState uss) {
14249 final int userId = uss.mHandle.getIdentifier();
14250 boolean stopped;
14251 ArrayList<IStopUserCallback> callbacks;
14252 synchronized (this) {
14253 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
14254 if (uss.mState != UserStartedState.STATE_STOPPING
14255 || mStartedUsers.get(userId) != uss) {
14256 stopped = false;
14257 } else {
14258 stopped = true;
14259 // User can no longer run.
14260 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014261 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014262 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014263
14264 // Clean up all state and processes associated with the user.
14265 // Kill all the processes for the user.
14266 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014267 }
14268 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014269
14270 for (int i=0; i<callbacks.size(); i++) {
14271 try {
14272 if (stopped) callbacks.get(i).userStopped(userId);
14273 else callbacks.get(i).userStopAborted(userId);
14274 } catch (RemoteException e) {
14275 }
14276 }
14277 }
14278
14279 @Override
14280 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014281 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14282 != PackageManager.PERMISSION_GRANTED) && (
14283 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14284 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014285 String msg = "Permission Denial: getCurrentUser() from pid="
14286 + Binder.getCallingPid()
14287 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014288 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014289 Slog.w(TAG, msg);
14290 throw new SecurityException(msg);
14291 }
14292 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014293 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014294 }
Amith Yamasani13593602012-03-22 16:16:17 -070014295 }
14296
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014297 int getCurrentUserIdLocked() {
14298 return mCurrentUserId;
14299 }
14300
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014301 @Override
14302 public boolean isUserRunning(int userId) {
14303 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14304 != PackageManager.PERMISSION_GRANTED) {
14305 String msg = "Permission Denial: isUserRunning() from pid="
14306 + Binder.getCallingPid()
14307 + ", uid=" + Binder.getCallingUid()
14308 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14309 Slog.w(TAG, msg);
14310 throw new SecurityException(msg);
14311 }
14312 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014313 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014314 }
14315 }
14316
Dianne Hackborn1676c852012-09-10 14:52:30 -070014317 boolean isUserRunningLocked(int userId) {
14318 UserStartedState state = mStartedUsers.get(userId);
14319 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014320 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014321
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014322 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014323 public int[] getRunningUserIds() {
14324 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14325 != PackageManager.PERMISSION_GRANTED) {
14326 String msg = "Permission Denial: isUserRunning() from pid="
14327 + Binder.getCallingPid()
14328 + ", uid=" + Binder.getCallingUid()
14329 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14330 Slog.w(TAG, msg);
14331 throw new SecurityException(msg);
14332 }
14333 synchronized (this) {
14334 return mStartedUserArray;
14335 }
14336 }
14337
14338 private void updateStartedUserArrayLocked() {
14339 mStartedUserArray = new int[mStartedUsers.size()];
14340 for (int i=0; i<mStartedUsers.size(); i++) {
14341 mStartedUserArray[i] = mStartedUsers.keyAt(i);
14342 }
14343 }
14344
14345 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014346 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14347 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14348 != PackageManager.PERMISSION_GRANTED) {
14349 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14350 + Binder.getCallingPid()
14351 + ", uid=" + Binder.getCallingUid()
14352 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14353 Slog.w(TAG, msg);
14354 throw new SecurityException(msg);
14355 }
14356
14357 mUserSwitchObservers.register(observer);
14358 }
14359
14360 @Override
14361 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14362 mUserSwitchObservers.unregister(observer);
14363 }
14364
Dianne Hackborn1676c852012-09-10 14:52:30 -070014365 private boolean userExists(int userId) {
14366 if (userId == 0) {
14367 return true;
14368 }
14369 UserManagerService ums = getUserManagerLocked();
14370 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14371 }
14372
14373 int[] getUsersLocked() {
14374 UserManagerService ums = getUserManagerLocked();
14375 return ums != null ? ums.getUserIds() : new int[] { 0 };
14376 }
14377
14378 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014379 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014380 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14381 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014382 }
14383 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014384 }
14385
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014386 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014387 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014388
14389 throw new SecurityException("Caller uid=" + uid
14390 + " is not privileged to communicate with user=" + userId);
14391 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014392
14393 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014394 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014395 }
14396
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014397 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014398 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014399 ApplicationInfo newInfo = new ApplicationInfo(info);
14400 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014401 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14402 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014403 return newInfo;
14404 }
14405
14406 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014407 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014408 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014409 return aInfo;
14410 }
14411
14412 ActivityInfo info = new ActivityInfo(aInfo);
14413 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14414 return info;
14415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014416}