blob: 3582a415397418bfaa27cbc22cca698f4b2637aa [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;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700118import android.os.UpdateLock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700119import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700121import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800123import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700124import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700126import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700128import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.view.Gravity;
130import android.view.LayoutInflater;
131import android.view.View;
132import android.view.WindowManager;
133import android.view.WindowManagerPolicy;
134
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700135import java.io.BufferedInputStream;
136import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700137import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.DataInputStream;
139import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.File;
141import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700142import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700144import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200145import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800146import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700148import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.lang.ref.WeakReference;
150import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700151import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700152import java.util.Collections;
153import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.util.HashMap;
155import java.util.HashSet;
156import java.util.Iterator;
157import java.util.List;
158import java.util.Locale;
159import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700160import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700161import java.util.concurrent.atomic.AtomicBoolean;
162import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700164public final class ActivityManagerService extends ActivityManagerNative
165 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700166 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700168 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400170 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final boolean DEBUG_SWITCH = localLOGV || false;
172 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700173 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_PAUSE = localLOGV || false;
175 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
176 static final boolean DEBUG_TRANSITION = localLOGV || false;
177 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800178 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700179 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700181 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_VISBILITY = localLOGV || false;
183 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700184 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700185 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700186 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800187 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700189 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700190 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700191 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700192 static final boolean DEBUG_POWER = localLOGV || false;
193 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700194 static final boolean DEBUG_MU = localLOGV || false;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700195 static final boolean DEBUG_IMMERSIVE = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 static final boolean VALIDATE_TOKENS = false;
197 static final boolean SHOW_ACTIVITY_START_TIME = true;
198
199 // Control over CPU and battery monitoring.
200 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
201 static final boolean MONITOR_CPU_USAGE = true;
202 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
203 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
204 static final boolean MONITOR_THREAD_CPU_USAGE = false;
205
Dianne Hackborn1655be42009-05-08 14:29:01 -0700206 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700207 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700208
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800209 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700211 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 // Maximum number of recent tasks that we can remember.
214 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700215
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700216 // Amount of time after a call to stopAppSwitches() during which we will
217 // prevent further untrusted switches from happening.
218 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
220 // How long we wait for a launched process to attach to the activity manager
221 // before we decide it's never going to come up for real.
222 static final int PROC_START_TIMEOUT = 10*1000;
223
Jeff Brown3f9dd282011-07-08 20:02:19 -0700224 // How long we wait for a launched process to attach to the activity manager
225 // before we decide it's never going to come up for real, when the process was
226 // started with a wrapper for instrumentation (such as Valgrind) because it
227 // could take much longer than usual.
228 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 // How long to wait after going idle before forcing apps to GC.
231 static final int GC_TIMEOUT = 5*1000;
232
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700233 // The minimum amount of time between successive GC requests for a process.
234 static final int GC_MIN_INTERVAL = 60*1000;
235
Dianne Hackborn287952c2010-09-22 22:34:31 -0700236 // The rate at which we check for apps using excessive power -- 15 mins.
237 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
238
239 // The minimum sample duration we will allow before deciding we have
240 // enough data on wake locks to start killing things.
241 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
242
243 // The minimum sample duration we will allow before deciding we have
244 // enough data on CPU usage to start killing things.
245 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800248 static final int BROADCAST_FG_TIMEOUT = 10*1000;
249 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // How long we wait until we timeout on key dispatching.
252 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // How long we wait until we timeout on key dispatching during instrumentation.
255 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
256
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700257 // Amount of time we wait for observers to handle a user switch before
258 // giving up on them and unfreezing the screen.
259 static final int USER_SWITCH_TIMEOUT = 2*1000;
260
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700261 // Maximum number of users we allow to be running at a time.
262 static final int MAX_RUNNING_USERS = 3;
263
Dan Egnor42471dd2010-01-07 17:25:22 -0800264 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265
266 static final String[] EMPTY_STRING_ARRAY = new String[0];
267
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700268 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700269
270 private final boolean mHeadless;
271
Joe Onorato54a4a412011-11-02 20:50:08 -0700272 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
273 // default actuion automatically. Important for devices without direct input
274 // devices.
275 private boolean mShowDialogs = true;
276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700278 * Description of a request to start a new activity, which has been held
279 * due to app switches being disabled.
280 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700281 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700282 ActivityRecord r;
283 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700284 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700285 }
286
287 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
288 = new ArrayList<PendingActivityLaunch>();
289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800291 BroadcastQueue mFgBroadcastQueue;
292 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800293 // Convenient for easy iteration over the queues. Foreground is first
294 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800295 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800296
297 BroadcastQueue broadcastQueueForIntent(Intent intent) {
298 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
299 if (DEBUG_BACKGROUND_BROADCAST) {
300 Slog.i(TAG, "Broadcast intent " + intent + " on "
301 + (isFg ? "foreground" : "background")
302 + " queue");
303 }
304 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
305 }
306
307 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
308 for (BroadcastQueue queue : mBroadcastQueues) {
309 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
310 if (r != null) {
311 return r;
312 }
313 }
314 return null;
315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316
317 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 * Activity we have told the window manager to have key focus.
319 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700320 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700321 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 * List of intents that were used to start the most recent tasks.
323 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700324 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700327 * Process management.
328 */
329 final ProcessList mProcessList = new ProcessList();
330
331 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 * All of the applications we currently have running organized by name.
333 * The keys are strings of the application package name (as
334 * returned by the package manager), and the keys are ApplicationRecord
335 * objects.
336 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700337 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338
339 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800340 * The currently running isolated processes.
341 */
342 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
343
344 /**
345 * Counter for assigning isolated process uids, to avoid frequently reusing the
346 * same ones.
347 */
348 int mNextIsolatedProcessUid = 0;
349
350 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700351 * The currently running heavy-weight process, if any.
352 */
353 ProcessRecord mHeavyWeightProcess = null;
354
355 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 * The last time that various processes have crashed.
357 */
358 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
359
360 /**
361 * Set of applications that we consider to be bad, and will reject
362 * incoming broadcasts from (which the user has no control over).
363 * Processes are added to this set when they have crashed twice within
364 * a minimum amount of time; they are removed from it when they are
365 * later restarted (hopefully due to some user action). The value is the
366 * time it was added to the list.
367 */
368 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
369
370 /**
371 * All of the processes we currently have running organized by pid.
372 * The keys are the pid running the application.
373 *
374 * <p>NOTE: This object is protected by its own lock, NOT the global
375 * activity manager lock!
376 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700377 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378
379 /**
380 * All of the processes that have been forced to be foreground. The key
381 * is the pid of the caller who requested it (we hold a death
382 * link on it).
383 */
384 abstract class ForegroundToken implements IBinder.DeathRecipient {
385 int pid;
386 IBinder token;
387 }
388 final SparseArray<ForegroundToken> mForegroundProcesses
389 = new SparseArray<ForegroundToken>();
390
391 /**
392 * List of records for processes that someone had tried to start before the
393 * system was ready. We don't start them at that point, but ensure they
394 * are started by the time booting is complete.
395 */
396 final ArrayList<ProcessRecord> mProcessesOnHold
397 = new ArrayList<ProcessRecord>();
398
399 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 * List of persistent applications that are in the process
401 * of being started.
402 */
403 final ArrayList<ProcessRecord> mPersistentStartingProcesses
404 = new ArrayList<ProcessRecord>();
405
406 /**
407 * Processes that are being forcibly torn down.
408 */
409 final ArrayList<ProcessRecord> mRemovedProcesses
410 = new ArrayList<ProcessRecord>();
411
412 /**
413 * List of running applications, sorted by recent usage.
414 * The first entry in the list is the least recently used.
415 * It contains ApplicationRecord objects. This list does NOT include
416 * any persistent application records (since we never want to exit them).
417 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800418 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 = new ArrayList<ProcessRecord>();
420
421 /**
422 * List of processes that should gc as soon as things are idle.
423 */
424 final ArrayList<ProcessRecord> mProcessesToGc
425 = new ArrayList<ProcessRecord>();
426
427 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800428 * This is the process holding what we currently consider to be
429 * the "home" activity.
430 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700431 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800432
433 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700434 * This is the process holding the activity the user last visited that
435 * is in a different process from the one they are currently in.
436 */
437 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800438
439 /**
440 * The time at which the previous process was last visible.
441 */
442 long mPreviousProcessVisibleTime;
443
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700444 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700445 * Which uses have been started, so are allowed to run code.
446 */
447 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
448
449 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700450 * LRU list of history of current users. Most recently current is at the end.
451 */
452 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
453
454 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700455 * Constant array of the users that are currently started.
456 */
457 int[] mStartedUserArray = new int[] { 0 };
458
459 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700460 * Registered observers of the user switching mechanics.
461 */
462 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
463 = new RemoteCallbackList<IUserSwitchObserver>();
464
465 /**
466 * Currently active user switch.
467 */
468 Object mCurUserSwitchCallback;
469
470 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400471 * Packages that the user has asked to have run in screen size
472 * compatibility mode instead of filling the screen.
473 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700474 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400475
476 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 * Set of PendingResultRecord objects that are currently active.
478 */
479 final HashSet mPendingResultRecords = new HashSet();
480
481 /**
482 * Set of IntentSenderRecord objects that are currently active.
483 */
484 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
485 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
486
487 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800488 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700489 * already logged DropBox entries for. Guarded by itself. If
490 * something (rogue user app) forces this over
491 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
492 */
493 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
494 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
495
496 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700497 * Strict Mode background batched logging state.
498 *
499 * The string buffer is guarded by itself, and its lock is also
500 * used to determine if another batched write is already
501 * in-flight.
502 */
503 private final StringBuilder mStrictModeBuffer = new StringBuilder();
504
505 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 * Keeps track of all IIntentReceivers that have been registered for
507 * broadcasts. Hash keys are the receiver IBinder, hash value is
508 * a ReceiverList.
509 */
510 final HashMap mRegisteredReceivers = new HashMap();
511
512 /**
513 * Resolver for broadcast intents to registered receivers.
514 * Holds BroadcastFilter (subclass of IntentFilter).
515 */
516 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
517 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
518 @Override
519 protected boolean allowFilterResult(
520 BroadcastFilter filter, List<BroadcastFilter> dest) {
521 IBinder target = filter.receiverList.receiver.asBinder();
522 for (int i=dest.size()-1; i>=0; i--) {
523 if (dest.get(i).receiverList.receiver.asBinder() == target) {
524 return false;
525 }
526 }
527 return true;
528 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700529
530 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700531 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700532 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
533 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700534 return super.newResult(filter, match, userId);
535 }
536 return null;
537 }
538
539 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700540 protected BroadcastFilter[] newArray(int size) {
541 return new BroadcastFilter[size];
542 }
543
544 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700545 protected String packageForFilter(BroadcastFilter filter) {
546 return filter.packageName;
547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 };
549
550 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700551 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700553 * that action (which should usually be one). The SparseArray is keyed
554 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
555 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700557 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
558 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700560 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561
562 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700563 * Backup/restore process management
564 */
565 String mBackupAppName = null;
566 BackupRecord mBackupTarget = null;
567
568 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 * List of PendingThumbnailsRecord objects of clients who are still
570 * waiting to receive all of the thumbnails for a task.
571 */
572 final ArrayList mPendingThumbnails = new ArrayList();
573
574 /**
575 * List of HistoryRecord objects that have been finished and must
576 * still report back to a pending thumbnail receiver.
577 */
578 final ArrayList mCancelledThumbnails = new ArrayList();
579
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700580 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 /**
583 * List of content providers who have clients waiting for them. The
584 * application is currently being launched and the provider will be
585 * removed from this list once it is published.
586 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700587 final ArrayList<ContentProviderRecord> mLaunchingProviders
588 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589
590 /**
591 * Global set of specific Uri permissions that have been granted.
592 */
593 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
594 = new SparseArray<HashMap<Uri, UriPermission>>();
595
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800596 CoreSettingsObserver mCoreSettingsObserver;
597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 /**
599 * Thread-local storage used to carry caller permissions over through
600 * indirect content-provider access.
601 * @see #ActivityManagerService.openContentUri()
602 */
603 private class Identity {
604 public int pid;
605 public int uid;
606
607 Identity(int _pid, int _uid) {
608 pid = _pid;
609 uid = _uid;
610 }
611 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
614
615 /**
616 * All information we have collected about the runtime performance of
617 * any user id that can impact battery performance.
618 */
619 final BatteryStatsService mBatteryStatsService;
620
621 /**
622 * information about component usage
623 */
624 final UsageStatsService mUsageStatsService;
625
626 /**
627 * Current configuration information. HistoryRecord objects are given
628 * a reference to this object to indicate which configuration they are
629 * currently running in, so this object must be kept immutable.
630 */
631 Configuration mConfiguration = new Configuration();
632
633 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800634 * Current sequencing integer of the configuration, for skipping old
635 * configurations.
636 */
637 int mConfigurationSeq = 0;
638
639 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700640 * Hardware-reported OpenGLES version.
641 */
642 final int GL_ES_VERSION;
643
644 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 * List of initialization arguments to pass to all processes when binding applications to them.
646 * For example, references to the commonly used services.
647 */
648 HashMap<String, IBinder> mAppBindArgs;
649
650 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700651 * Temporary to avoid allocations. Protected by main lock.
652 */
653 final StringBuilder mStringBuilder = new StringBuilder(256);
654
655 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 * Used to control how we initialize the service.
657 */
658 boolean mStartRunning = false;
659 ComponentName mTopComponent;
660 String mTopAction;
661 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700662 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 boolean mSystemReady = false;
664 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700665 boolean mWaitingUpdate = false;
666 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700667 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700668 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669
670 Context mContext;
671
672 int mFactoryTest;
673
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700674 boolean mCheckedForSetup;
675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700677 * The time at which we will allow normal application switches again,
678 * after a call to {@link #stopAppSwitches()}.
679 */
680 long mAppSwitchesAllowedTime;
681
682 /**
683 * This is set to true after the first switch after mAppSwitchesAllowedTime
684 * is set; any switches after that will clear the time.
685 */
686 boolean mDidAppSwitch;
687
688 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700689 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700690 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700691 long mLastPowerCheckRealtime;
692
693 /**
694 * Last time (in uptime) at which we checked for power usage.
695 */
696 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700697
698 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 * Set while we are wanting to sleep, to prevent any
700 * activities from being started/resumed.
701 */
702 boolean mSleeping = false;
703
704 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700705 * State of external calls telling us if the device is asleep.
706 */
707 boolean mWentToSleep = false;
708
709 /**
710 * State of external call telling us if the lock screen is shown.
711 */
712 boolean mLockScreenShown = false;
713
714 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700715 * Set if we are shutting down the system, similar to sleeping.
716 */
717 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718
719 /**
720 * Task identifier that activities are currently being started
721 * in. Incremented each time a new task is created.
722 * todo: Replace this with a TokenSpace class that generates non-repeating
723 * integers that won't wrap.
724 */
725 int mCurTask = 1;
726
727 /**
728 * Current sequence id for oom_adj computation traversal.
729 */
730 int mAdjSeq = 0;
731
732 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700733 * Current sequence id for process LRU updating.
734 */
735 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736
737 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700738 * Keep track of the non-hidden/empty process we last found, to help
739 * determine how to distribute hidden/empty processes next time.
740 */
741 int mNumNonHiddenProcs = 0;
742
743 /**
744 * Keep track of the number of hidden procs, to balance oom adj
745 * distribution between those and empty procs.
746 */
747 int mNumHiddenProcs = 0;
748
749 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700750 * Keep track of the number of service processes we last found, to
751 * determine on the next iteration which should be B services.
752 */
753 int mNumServiceProcs = 0;
754 int mNewNumServiceProcs = 0;
755
756 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 * System monitoring: number of processes that died since the last
758 * N procs were started.
759 */
760 int[] mProcDeaths = new int[20];
761
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700762 /**
763 * This is set if we had to do a delayed dexopt of an app before launching
764 * it, to increasing the ANR timeouts in that case.
765 */
766 boolean mDidDexOpt;
767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 String mDebugApp = null;
769 boolean mWaitForDebugger = false;
770 boolean mDebugTransient = false;
771 String mOrigDebugApp = null;
772 boolean mOrigWaitForDebugger = false;
773 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700774 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700775 String mProfileApp = null;
776 ProcessRecord mProfileProc = null;
777 String mProfileFile;
778 ParcelFileDescriptor mProfileFd;
779 int mProfileType = 0;
780 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800781 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700783 static class ProcessChangeItem {
784 static final int CHANGE_ACTIVITIES = 1<<0;
785 static final int CHANGE_IMPORTANCE= 1<<1;
786 int changes;
787 int uid;
788 int pid;
789 int importance;
790 boolean foregroundActivities;
791 }
792
Jeff Sharkeya4620792011-05-20 15:29:23 -0700793 final RemoteCallbackList<IProcessObserver> mProcessObservers
794 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700795 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
796
797 final ArrayList<ProcessChangeItem> mPendingProcessChanges
798 = new ArrayList<ProcessChangeItem>();
799 final ArrayList<ProcessChangeItem> mAvailProcessChanges
800 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 /**
803 * Callback of last caller to {@link #requestPss}.
804 */
805 Runnable mRequestPssCallback;
806
807 /**
808 * Remaining processes for which we are waiting results from the last
809 * call to {@link #requestPss}.
810 */
811 final ArrayList<ProcessRecord> mRequestPssList
812 = new ArrayList<ProcessRecord>();
813
814 /**
815 * Runtime statistics collection thread. This object's lock is used to
816 * protect all related state.
817 */
818 final Thread mProcessStatsThread;
819
820 /**
821 * Used to collect process stats when showing not responding dialog.
822 * Protected by mProcessStatsThread.
823 */
824 final ProcessStats mProcessStats = new ProcessStats(
825 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700826 final AtomicLong mLastCpuTime = new AtomicLong(0);
827 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 long mLastWriteTime = 0;
830
831 /**
Christopher Tate73c2aee2012-03-15 16:27:14 -0700832 * Used to retain an update lock when the foreground activity is in
833 * immersive mode.
834 */
835 final UpdateLock mUpdateLock = new UpdateLock("immersive");
836
837 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 * Set to true after the system has finished booting.
839 */
840 boolean mBooted = false;
841
Dianne Hackborn7d608422011-08-07 16:24:18 -0700842 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700843 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844
845 WindowManagerService mWindowManager;
846
847 static ActivityManagerService mSelf;
848 static ActivityThread mSystemThread;
849
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700850 private int mCurrentUserId = 0;
851 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700852 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 private final class AppDeathRecipient implements IBinder.DeathRecipient {
855 final ProcessRecord mApp;
856 final int mPid;
857 final IApplicationThread mAppThread;
858
859 AppDeathRecipient(ProcessRecord app, int pid,
860 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800861 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 TAG, "New death recipient " + this
863 + " for thread " + thread.asBinder());
864 mApp = app;
865 mPid = pid;
866 mAppThread = thread;
867 }
868
869 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800870 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 TAG, "Death received in " + this
872 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 synchronized(ActivityManagerService.this) {
874 appDiedLocked(mApp, mPid, mAppThread);
875 }
876 }
877 }
878
879 static final int SHOW_ERROR_MSG = 1;
880 static final int SHOW_NOT_RESPONDING_MSG = 2;
881 static final int SHOW_FACTORY_ERROR_MSG = 3;
882 static final int UPDATE_CONFIGURATION_MSG = 4;
883 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
884 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 static final int SERVICE_TIMEOUT_MSG = 12;
886 static final int UPDATE_TIME_ZONE = 13;
887 static final int SHOW_UID_ERROR_MSG = 14;
888 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700890 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700891 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800892 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700893 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
894 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700895 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700896 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700897 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700898 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700899 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700900 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700901 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700902 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700903 static final int REPORT_USER_SWITCH_MSG = 34;
904 static final int CONTINUE_USER_SWITCH_MSG = 35;
905 static final int USER_SWITCH_TIMEOUT_MSG = 36;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700906 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800908 static final int FIRST_ACTIVITY_STACK_MSG = 100;
909 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
910 static final int FIRST_COMPAT_MODE_MSG = 300;
911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700913 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700914 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915
916 final Handler mHandler = new Handler() {
917 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800918 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 //}
920
921 public void handleMessage(Message msg) {
922 switch (msg.what) {
923 case SHOW_ERROR_MSG: {
924 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700925 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
926 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 synchronized (ActivityManagerService.this) {
928 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700929 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800931 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700932 if (res != null) {
933 res.set(0);
934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 return;
936 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700937 if (!showBackground && UserHandle.getAppId(proc.uid)
938 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
939 && proc.pid != MY_PID) {
940 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
941 if (res != null) {
942 res.set(0);
943 }
944 return;
945 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700946 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700947 Dialog d = new AppErrorDialog(mContext,
948 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 d.show();
950 proc.crashDialog = d;
951 } else {
952 // The device is asleep, so just pretend that the user
953 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700954 if (res != null) {
955 res.set(0);
956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
958 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700959
960 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 } break;
962 case SHOW_NOT_RESPONDING_MSG: {
963 synchronized (ActivityManagerService.this) {
964 HashMap data = (HashMap) msg.obj;
965 ProcessRecord proc = (ProcessRecord)data.get("app");
966 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800967 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 return;
969 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800970
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700971 Intent intent = new Intent("android.intent.action.ANR");
972 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800973 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
974 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700975 }
976 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800977 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700978 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800979
Justin Kohbc52ca22012-03-29 15:11:44 -0700980 if (mShowDialogs) {
981 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -0700982 mContext, proc, (ActivityRecord)data.get("activity"),
983 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -0700984 d.show();
985 proc.anrDialog = d;
986 } else {
987 // Just kill the app if there is no dialog to be shown.
988 killAppAtUsersRequest(proc, null);
989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700991
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700992 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700994 case SHOW_STRICT_MODE_VIOLATION_MSG: {
995 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
996 synchronized (ActivityManagerService.this) {
997 ProcessRecord proc = (ProcessRecord) data.get("app");
998 if (proc == null) {
999 Slog.e(TAG, "App not found when showing strict mode dialog.");
1000 break;
1001 }
1002 if (proc.crashDialog != null) {
1003 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1004 return;
1005 }
1006 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001007 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001008 Dialog d = new StrictModeViolationDialog(mContext,
1009 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001010 d.show();
1011 proc.crashDialog = d;
1012 } else {
1013 // The device is asleep, so just pretend that the user
1014 // saw a crash dialog and hit "force quit".
1015 res.set(0);
1016 }
1017 }
1018 ensureBootCompleted();
1019 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 case SHOW_FACTORY_ERROR_MSG: {
1021 Dialog d = new FactoryErrorDialog(
1022 mContext, msg.getData().getCharSequence("msg"));
1023 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001024 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 } break;
1026 case UPDATE_CONFIGURATION_MSG: {
1027 final ContentResolver resolver = mContext.getContentResolver();
1028 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1029 } break;
1030 case GC_BACKGROUND_PROCESSES_MSG: {
1031 synchronized (ActivityManagerService.this) {
1032 performAppGcsIfAppropriateLocked();
1033 }
1034 } break;
1035 case WAIT_FOR_DEBUGGER_MSG: {
1036 synchronized (ActivityManagerService.this) {
1037 ProcessRecord app = (ProcessRecord)msg.obj;
1038 if (msg.arg1 != 0) {
1039 if (!app.waitedForDebugger) {
1040 Dialog d = new AppWaitingForDebuggerDialog(
1041 ActivityManagerService.this,
1042 mContext, app);
1043 app.waitDialog = d;
1044 app.waitedForDebugger = true;
1045 d.show();
1046 }
1047 } else {
1048 if (app.waitDialog != null) {
1049 app.waitDialog.dismiss();
1050 app.waitDialog = null;
1051 }
1052 }
1053 }
1054 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001056 if (mDidDexOpt) {
1057 mDidDexOpt = false;
1058 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1059 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001060 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001061 return;
1062 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001063 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 } break;
1065 case UPDATE_TIME_ZONE: {
1066 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001067 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1068 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 if (r.thread != null) {
1070 try {
1071 r.thread.updateTimeZone();
1072 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001073 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075 }
1076 }
1077 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001078 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001079 case CLEAR_DNS_CACHE: {
1080 synchronized (ActivityManagerService.this) {
1081 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1082 ProcessRecord r = mLruProcesses.get(i);
1083 if (r.thread != null) {
1084 try {
1085 r.thread.clearDnsCache();
1086 } catch (RemoteException ex) {
1087 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1088 }
1089 }
1090 }
1091 }
1092 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001093 case UPDATE_HTTP_PROXY: {
1094 ProxyProperties proxy = (ProxyProperties)msg.obj;
1095 String host = "";
1096 String port = "";
1097 String exclList = "";
1098 if (proxy != null) {
1099 host = proxy.getHost();
1100 port = Integer.toString(proxy.getPort());
1101 exclList = proxy.getExclusionList();
1102 }
1103 synchronized (ActivityManagerService.this) {
1104 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1105 ProcessRecord r = mLruProcesses.get(i);
1106 if (r.thread != null) {
1107 try {
1108 r.thread.setHttpProxy(host, port, exclList);
1109 } catch (RemoteException ex) {
1110 Slog.w(TAG, "Failed to update http proxy for: " +
1111 r.info.processName);
1112 }
1113 }
1114 }
1115 }
1116 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001118 String title = "System UIDs Inconsistent";
1119 String text = "UIDs on the system are inconsistent, you need to wipe your"
1120 + " data partition or your device will be unstable.";
1121 Log.e(TAG, title + ": " + text);
1122 if (mShowDialogs) {
1123 // XXX This is a temporary dialog, no need to localize.
1124 AlertDialog d = new BaseErrorDialog(mContext);
1125 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1126 d.setCancelable(false);
1127 d.setTitle(title);
1128 d.setMessage(text);
1129 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1130 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1131 mUidAlert = d;
1132 d.show();
1133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 } break;
1135 case IM_FEELING_LUCKY_MSG: {
1136 if (mUidAlert != null) {
1137 mUidAlert.dismiss();
1138 mUidAlert = null;
1139 }
1140 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001142 if (mDidDexOpt) {
1143 mDidDexOpt = false;
1144 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1145 nmsg.obj = msg.obj;
1146 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1147 return;
1148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 ProcessRecord app = (ProcessRecord)msg.obj;
1150 synchronized (ActivityManagerService.this) {
1151 processStartTimedOutLocked(app);
1152 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001153 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001154 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1155 synchronized (ActivityManagerService.this) {
1156 doPendingActivityLaunchesLocked(true);
1157 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001158 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001159 case KILL_APPLICATION_MSG: {
1160 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001161 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001162 boolean restart = (msg.arg2 == 1);
1163 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001164 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1165 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001166 }
1167 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001168 case FINALIZE_PENDING_INTENT_MSG: {
1169 ((PendingIntentRecord)msg.obj).completeFinalize();
1170 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001171 case POST_HEAVY_NOTIFICATION_MSG: {
1172 INotificationManager inm = NotificationManager.getService();
1173 if (inm == null) {
1174 return;
1175 }
1176
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001177 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001178 ProcessRecord process = root.app;
1179 if (process == null) {
1180 return;
1181 }
1182
1183 try {
1184 Context context = mContext.createPackageContext(process.info.packageName, 0);
1185 String text = mContext.getString(R.string.heavy_weight_notification,
1186 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1187 Notification notification = new Notification();
1188 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1189 notification.when = 0;
1190 notification.flags = Notification.FLAG_ONGOING_EVENT;
1191 notification.tickerText = text;
1192 notification.defaults = 0; // please be quiet
1193 notification.sound = null;
1194 notification.vibrate = null;
1195 notification.setLatestEventInfo(context, text,
1196 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001197 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1198 PendingIntent.FLAG_CANCEL_CURRENT, null,
1199 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001200
1201 try {
1202 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001203 inm.enqueueNotificationWithTag("android", null,
1204 R.string.heavy_weight_notification,
1205 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001206 } catch (RuntimeException e) {
1207 Slog.w(ActivityManagerService.TAG,
1208 "Error showing notification for heavy-weight app", e);
1209 } catch (RemoteException e) {
1210 }
1211 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001212 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001213 }
1214 } break;
1215 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1216 INotificationManager inm = NotificationManager.getService();
1217 if (inm == null) {
1218 return;
1219 }
1220 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001221 inm.cancelNotificationWithTag("android", null,
1222 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001223 } catch (RuntimeException e) {
1224 Slog.w(ActivityManagerService.TAG,
1225 "Error canceling notification for service", e);
1226 } catch (RemoteException e) {
1227 }
1228 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001229 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1230 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001231 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001232 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001233 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1234 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001235 }
1236 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001237 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1238 synchronized (ActivityManagerService.this) {
1239 ActivityRecord ar = (ActivityRecord)msg.obj;
1240 if (mCompatModeDialog != null) {
1241 if (mCompatModeDialog.mAppInfo.packageName.equals(
1242 ar.info.applicationInfo.packageName)) {
1243 return;
1244 }
1245 mCompatModeDialog.dismiss();
1246 mCompatModeDialog = null;
1247 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001248 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001249 if (mCompatModePackages.getPackageAskCompatModeLocked(
1250 ar.packageName)) {
1251 int mode = mCompatModePackages.computeCompatModeLocked(
1252 ar.info.applicationInfo);
1253 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1254 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1255 mCompatModeDialog = new CompatModeDialog(
1256 ActivityManagerService.this, mContext,
1257 ar.info.applicationInfo);
1258 mCompatModeDialog.show();
1259 }
1260 }
1261 }
1262 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001263 break;
1264 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001265 case DISPATCH_PROCESSES_CHANGED: {
1266 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001267 break;
1268 }
1269 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001270 final int pid = msg.arg1;
1271 final int uid = msg.arg2;
1272 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001273 break;
1274 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001275 case REPORT_MEM_USAGE: {
1276 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1277 if (!isDebuggable) {
1278 return;
1279 }
1280 synchronized (ActivityManagerService.this) {
1281 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001282 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1283 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001284 // avoid spamming.
1285 return;
1286 }
1287 mLastMemUsageReportTime = now;
1288 }
1289 Thread thread = new Thread() {
1290 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001291 StringBuilder dropBuilder = new StringBuilder(1024);
1292 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001293 StringWriter oomSw = new StringWriter();
1294 PrintWriter oomPw = new PrintWriter(oomSw);
1295 StringWriter catSw = new StringWriter();
1296 PrintWriter catPw = new PrintWriter(catSw);
1297 String[] emptyArgs = new String[] { };
1298 StringBuilder tag = new StringBuilder(128);
1299 StringBuilder stack = new StringBuilder(128);
1300 tag.append("Low on memory -- ");
1301 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1302 tag, stack);
1303 dropBuilder.append(stack);
1304 dropBuilder.append('\n');
1305 dropBuilder.append('\n');
1306 String oomString = oomSw.toString();
1307 dropBuilder.append(oomString);
1308 dropBuilder.append('\n');
1309 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001310 try {
1311 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1312 "procrank", });
1313 final InputStreamReader converter = new InputStreamReader(
1314 proc.getInputStream());
1315 BufferedReader in = new BufferedReader(converter);
1316 String line;
1317 while (true) {
1318 line = in.readLine();
1319 if (line == null) {
1320 break;
1321 }
1322 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001323 logBuilder.append(line);
1324 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001325 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001326 dropBuilder.append(line);
1327 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001328 }
1329 converter.close();
1330 } catch (IOException e) {
1331 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001332 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001333 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001334 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001335 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001336 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1337 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001338 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001339 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001340 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001341 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001342 addErrorToDropBox("lowmem", null, "system_server", null,
1343 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001344 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001345 synchronized (ActivityManagerService.this) {
1346 long now = SystemClock.uptimeMillis();
1347 if (mLastMemUsageReportTime < now) {
1348 mLastMemUsageReportTime = now;
1349 }
1350 }
1351 }
1352 };
1353 thread.start();
1354 break;
1355 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001356 case REPORT_USER_SWITCH_MSG: {
1357 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1358 break;
1359 }
1360 case CONTINUE_USER_SWITCH_MSG: {
1361 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1362 break;
1363 }
1364 case USER_SWITCH_TIMEOUT_MSG: {
1365 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1366 break;
1367 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001368 case IMMERSIVE_MODE_LOCK_MSG: {
1369 final boolean nextState = (msg.arg1 != 0);
1370 if (mUpdateLock.isHeld() != nextState) {
1371 if (DEBUG_IMMERSIVE) {
1372 final ActivityRecord r = (ActivityRecord) msg.obj;
1373 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1374 }
1375 if (nextState) {
1376 mUpdateLock.acquire();
1377 } else {
1378 mUpdateLock.release();
1379 }
1380 }
1381 break;
1382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384 }
1385 };
1386
1387 public static void setSystemProcess() {
1388 try {
1389 ActivityManagerService m = mSelf;
1390
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001391 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001393 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001394 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 if (MONITOR_CPU_USAGE) {
1396 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 ServiceManager.addService("permission", new PermissionController(m));
1399
1400 ApplicationInfo info =
1401 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001402 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001403 mSystemThread.installSystemApplicationInfo(info);
1404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 synchronized (mSelf) {
1406 ProcessRecord app = mSelf.newProcessRecordLocked(
1407 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001408 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001410 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001411 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001412 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 synchronized (mSelf.mPidsSelfLocked) {
1414 mSelf.mPidsSelfLocked.put(app.pid, app);
1415 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001416 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 } catch (PackageManager.NameNotFoundException e) {
1419 throw new RuntimeException(
1420 "Unable to find android system package", e);
1421 }
1422 }
1423
1424 public void setWindowManager(WindowManagerService wm) {
1425 mWindowManager = wm;
1426 }
1427
1428 public static final Context main(int factoryTest) {
1429 AThread thr = new AThread();
1430 thr.start();
1431
1432 synchronized (thr) {
1433 while (thr.mService == null) {
1434 try {
1435 thr.wait();
1436 } catch (InterruptedException e) {
1437 }
1438 }
1439 }
1440
1441 ActivityManagerService m = thr.mService;
1442 mSelf = m;
1443 ActivityThread at = ActivityThread.systemMain();
1444 mSystemThread = at;
1445 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001446 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 m.mContext = context;
1448 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001449 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450
1451 m.mBatteryStatsService.publish(context);
1452 m.mUsageStatsService.publish(context);
1453
1454 synchronized (thr) {
1455 thr.mReady = true;
1456 thr.notifyAll();
1457 }
1458
1459 m.startRunning(null, null, null, null);
1460
1461 return context;
1462 }
1463
1464 public static ActivityManagerService self() {
1465 return mSelf;
1466 }
1467
1468 static class AThread extends Thread {
1469 ActivityManagerService mService;
1470 boolean mReady = false;
1471
1472 public AThread() {
1473 super("ActivityManager");
1474 }
1475
1476 public void run() {
1477 Looper.prepare();
1478
1479 android.os.Process.setThreadPriority(
1480 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001481 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482
1483 ActivityManagerService m = new ActivityManagerService();
1484
1485 synchronized (this) {
1486 mService = m;
1487 notifyAll();
1488 }
1489
1490 synchronized (this) {
1491 while (!mReady) {
1492 try {
1493 wait();
1494 } catch (InterruptedException e) {
1495 }
1496 }
1497 }
1498
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001499 // For debug builds, log event loop stalls to dropbox for analysis.
1500 if (StrictMode.conditionallyEnableDebugLogging()) {
1501 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1502 }
1503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 Looper.loop();
1505 }
1506 }
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 static class MemBinder extends Binder {
1509 ActivityManagerService mActivityManagerService;
1510 MemBinder(ActivityManagerService activityManagerService) {
1511 mActivityManagerService = activityManagerService;
1512 }
1513
1514 @Override
1515 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001516 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1517 != PackageManager.PERMISSION_GRANTED) {
1518 pw.println("Permission Denial: can't dump meminfo from from pid="
1519 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1520 + " without permission " + android.Manifest.permission.DUMP);
1521 return;
1522 }
1523
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001524 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001525 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527 }
1528
Chet Haase9c1e23b2011-03-24 10:51:31 -07001529 static class GraphicsBinder extends Binder {
1530 ActivityManagerService mActivityManagerService;
1531 GraphicsBinder(ActivityManagerService activityManagerService) {
1532 mActivityManagerService = activityManagerService;
1533 }
1534
1535 @Override
1536 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001537 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1538 != PackageManager.PERMISSION_GRANTED) {
1539 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1540 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1541 + " without permission " + android.Manifest.permission.DUMP);
1542 return;
1543 }
1544
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001545 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001546 }
1547 }
1548
Jeff Brown6754ba22011-12-14 20:20:01 -08001549 static class DbBinder extends Binder {
1550 ActivityManagerService mActivityManagerService;
1551 DbBinder(ActivityManagerService activityManagerService) {
1552 mActivityManagerService = activityManagerService;
1553 }
1554
1555 @Override
1556 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1557 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1558 != PackageManager.PERMISSION_GRANTED) {
1559 pw.println("Permission Denial: can't dump dbinfo from from pid="
1560 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1561 + " without permission " + android.Manifest.permission.DUMP);
1562 return;
1563 }
1564
1565 mActivityManagerService.dumpDbInfo(fd, pw, args);
1566 }
1567 }
1568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 static class CpuBinder extends Binder {
1570 ActivityManagerService mActivityManagerService;
1571 CpuBinder(ActivityManagerService activityManagerService) {
1572 mActivityManagerService = activityManagerService;
1573 }
1574
1575 @Override
1576 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001577 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1578 != PackageManager.PERMISSION_GRANTED) {
1579 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1580 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1581 + " without permission " + android.Manifest.permission.DUMP);
1582 return;
1583 }
1584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001586 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1587 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1588 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590 }
1591 }
1592
1593 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001594 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001595
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001596 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1597 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1598 mBroadcastQueues[0] = mFgBroadcastQueue;
1599 mBroadcastQueues[1] = mBgBroadcastQueue;
1600
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001601 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001602 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 File dataDir = Environment.getDataDirectory();
1605 File systemDir = new File(dataDir, "system");
1606 systemDir.mkdirs();
1607 mBatteryStatsService = new BatteryStatsService(new File(
1608 systemDir, "batterystats.bin").toString());
1609 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001610 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001611 mOnBattery = DEBUG_POWER ? true
1612 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001613 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001615 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001616 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001617 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001619 // User 0 is the first and only user that runs at boot.
1620 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001621 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001622 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001623
Jack Palevichb90d28c2009-07-22 15:35:24 -07001624 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1625 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1626
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001627 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001628 mConfiguration.setLocale(Locale.getDefault());
1629
Dianne Hackborn813075a62011-11-14 17:45:19 -08001630 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 mProcessStats.init();
1632
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001633 mCompatModePackages = new CompatModePackages(this, systemDir);
1634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 // Add ourself to the Watchdog monitors.
1636 Watchdog.getInstance().addMonitor(this);
1637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 mProcessStatsThread = new Thread("ProcessStats") {
1639 public void run() {
1640 while (true) {
1641 try {
1642 try {
1643 synchronized(this) {
1644 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001645 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001647 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 // + ", write delay=" + nextWriteDelay);
1649 if (nextWriteDelay < nextCpuDelay) {
1650 nextCpuDelay = nextWriteDelay;
1651 }
1652 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001653 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 this.wait(nextCpuDelay);
1655 }
1656 }
1657 } catch (InterruptedException e) {
1658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 updateCpuStatsNow();
1660 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663 }
1664 }
1665 };
1666 mProcessStatsThread.start();
1667 }
1668
1669 @Override
1670 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1671 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001672 if (code == SYSPROPS_TRANSACTION) {
1673 // We need to tell all apps about the system property change.
1674 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1675 synchronized(this) {
1676 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1677 final int NA = apps.size();
1678 for (int ia=0; ia<NA; ia++) {
1679 ProcessRecord app = apps.valueAt(ia);
1680 if (app.thread != null) {
1681 procs.add(app.thread.asBinder());
1682 }
1683 }
1684 }
1685 }
1686
1687 int N = procs.size();
1688 for (int i=0; i<N; i++) {
1689 Parcel data2 = Parcel.obtain();
1690 try {
1691 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1692 } catch (RemoteException e) {
1693 }
1694 data2.recycle();
1695 }
1696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 try {
1698 return super.onTransact(code, data, reply, flags);
1699 } catch (RuntimeException e) {
1700 // The activity manager only throws security exceptions, so let's
1701 // log all others.
1702 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001703 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 throw e;
1706 }
1707 }
1708
1709 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001710 final long now = SystemClock.uptimeMillis();
1711 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1712 return;
1713 }
1714 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1715 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 mProcessStatsThread.notify();
1717 }
1718 }
1719 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 void updateCpuStatsNow() {
1722 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001723 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 final long now = SystemClock.uptimeMillis();
1725 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001728 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1729 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 haveNewCpuStats = true;
1731 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001732 //Slog.i(TAG, mProcessStats.printCurrentState());
1733 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 // + mProcessStats.getTotalCpuPercent() + "%");
1735
Joe Onorato8a9b2202010-02-26 18:56:32 -08001736 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 if ("true".equals(SystemProperties.get("events.cpu"))) {
1738 int user = mProcessStats.getLastUserTime();
1739 int system = mProcessStats.getLastSystemTime();
1740 int iowait = mProcessStats.getLastIoWaitTime();
1741 int irq = mProcessStats.getLastIrqTime();
1742 int softIrq = mProcessStats.getLastSoftIrqTime();
1743 int idle = mProcessStats.getLastIdleTime();
1744
1745 int total = user + system + iowait + irq + softIrq + idle;
1746 if (total == 0) total = 1;
1747
Doug Zongker2bec3d42009-12-04 12:52:44 -08001748 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 ((user+system+iowait+irq+softIrq) * 100) / total,
1750 (user * 100) / total,
1751 (system * 100) / total,
1752 (iowait * 100) / total,
1753 (irq * 100) / total,
1754 (softIrq * 100) / total);
1755 }
1756 }
1757
Amith Yamasanie43530a2009-08-21 13:11:37 -07001758 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001759 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001760 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 synchronized(mPidsSelfLocked) {
1762 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001763 if (mOnBattery) {
1764 int perc = bstats.startAddingCpuLocked();
1765 int totalUTime = 0;
1766 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001767 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001769 ProcessStats.Stats st = mProcessStats.getStats(i);
1770 if (!st.working) {
1771 continue;
1772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001774 int otherUTime = (st.rel_utime*perc)/100;
1775 int otherSTime = (st.rel_stime*perc)/100;
1776 totalUTime += otherUTime;
1777 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 if (pr != null) {
1779 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001780 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1781 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001782 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001783 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001784 } else {
1785 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001786 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001787 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001788 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1789 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001790 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 }
1793 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001794 bstats.finishAddingCpuLocked(perc, totalUTime,
1795 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 }
1798 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1801 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001802 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
1805 }
1806 }
1807
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001808 @Override
1809 public void batteryNeedsCpuUpdate() {
1810 updateCpuStatsNow();
1811 }
1812
1813 @Override
1814 public void batteryPowerChanged(boolean onBattery) {
1815 // When plugging in, update the CPU stats first before changing
1816 // the plug state.
1817 updateCpuStatsNow();
1818 synchronized (this) {
1819 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001820 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001821 }
1822 }
1823 }
1824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 /**
1826 * Initialize the application bind args. These are passed to each
1827 * process when the bindApplication() IPC is sent to the process. They're
1828 * lazily setup to make sure the services are running when they're asked for.
1829 */
1830 private HashMap<String, IBinder> getCommonServicesLocked() {
1831 if (mAppBindArgs == null) {
1832 mAppBindArgs = new HashMap<String, IBinder>();
1833
1834 // Setup the application init args
1835 mAppBindArgs.put("package", ServiceManager.getService("package"));
1836 mAppBindArgs.put("window", ServiceManager.getService("window"));
1837 mAppBindArgs.put(Context.ALARM_SERVICE,
1838 ServiceManager.getService(Context.ALARM_SERVICE));
1839 }
1840 return mAppBindArgs;
1841 }
1842
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001843 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 if (mFocusedActivity != r) {
1845 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001846 if (r != null) {
1847 mWindowManager.setFocusedApp(r.appToken, true);
1848 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001849 applyUpdateLockStateLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 }
1852
Christopher Tate73c2aee2012-03-15 16:27:14 -07001853 final void applyUpdateLockStateLocked(ActivityRecord r) {
1854 // Modifications to the UpdateLock state are done on our handler, outside
1855 // the activity manager's locks. The new state is determined based on the
1856 // state *now* of the relevant activity record. The object is passed to
1857 // the handler solely for logging detail, not to be consulted/modified.
1858 final boolean nextState = r != null && r.immersive;
1859 mHandler.sendMessage(
1860 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
1861 }
1862
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001863 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001865 int lrui = mLruProcesses.indexOf(app);
1866 if (lrui >= 0) mLruProcesses.remove(lrui);
1867
1868 int i = mLruProcesses.size()-1;
1869 int skipTop = 0;
1870
Dianne Hackborn906497c2010-05-10 15:57:38 -07001871 app.lruSeq = mLruSeq;
1872
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001873 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001874 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001875 if (app.activities.size() > 0) {
1876 // If this process has activities, we more strongly want to keep
1877 // it around.
1878 app.lruWeight = app.lastActivityTime;
1879 } else if (app.pubProviders.size() > 0) {
1880 // If this process contains content providers, we want to keep
1881 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001882 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001883 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001884 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001885 } else {
1886 // If this process doesn't have activities, we less strongly
1887 // want to keep it around, and generally want to avoid getting
1888 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001889 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001890 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001891 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001892 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001893
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001894 while (i >= 0) {
1895 ProcessRecord p = mLruProcesses.get(i);
1896 // If this app shouldn't be in front of the first N background
1897 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001898 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001899 skipTop--;
1900 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001901 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001902 mLruProcesses.add(i+1, app);
1903 break;
1904 }
1905 i--;
1906 }
1907 if (i < 0) {
1908 mLruProcesses.add(0, app);
1909 }
1910
Dianne Hackborn906497c2010-05-10 15:57:38 -07001911 // If the app is currently using a content provider or service,
1912 // bump those processes as well.
1913 if (app.connections.size() > 0) {
1914 for (ConnectionRecord cr : app.connections) {
1915 if (cr.binding != null && cr.binding.service != null
1916 && cr.binding.service.app != null
1917 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001918 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001919 }
1920 }
1921 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001922 for (int j=app.conProviders.size()-1; j>=0; j--) {
1923 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1924 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001925 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001926 }
1927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
1929
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001930 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001931 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001932 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001933 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001934
1935 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1936 if (oomAdj) {
1937 updateOomAdjLocked();
1938 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001939 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001940
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001941 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001943 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001944 // The system gets to run in any process. If there are multiple
1945 // processes with the same uid, just pick the first (this
1946 // should never happen).
1947 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1948 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001949 if (procs == null) return null;
1950 final int N = procs.size();
1951 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001952 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
1955 ProcessRecord proc = mProcessNames.get(processName, uid);
1956 return proc;
1957 }
1958
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001959 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001960 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001961 try {
1962 if (pm.performDexOpt(packageName)) {
1963 mDidDexOpt = true;
1964 }
1965 } catch (RemoteException e) {
1966 }
1967 }
1968
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001969 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 int transit = mWindowManager.getPendingAppTransition();
1971 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1972 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1973 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1974 }
1975
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001976 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001978 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1979 boolean isolated) {
1980 ProcessRecord app;
1981 if (!isolated) {
1982 app = getProcessRecordLocked(processName, info.uid);
1983 } else {
1984 // If this is an isolated process, it can't re-use an existing process.
1985 app = null;
1986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 // We don't have to do anything more if:
1988 // (1) There is an existing application record; and
1989 // (2) The caller doesn't think it is dead, OR there is no thread
1990 // object attached to it so we know it couldn't have crashed; and
1991 // (3) There is a pid assigned to it, so it is either starting or
1992 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001993 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 + " app=" + app + " knownToBeDead=" + knownToBeDead
1995 + " thread=" + (app != null ? app.thread : null)
1996 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001997 if (app != null && app.pid > 0) {
1998 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001999 // We already have the app running, or are waiting for it to
2000 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002001 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002002 // If this is a new package in the process, add the package to the list
2003 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002004 return app;
2005 } else {
2006 // An application record is attached to a previous process,
2007 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002008 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002009 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 String hostingNameStr = hostingName != null
2014 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002015
2016 if (!isolated) {
2017 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2018 // If we are in the background, then check to see if this process
2019 // is bad. If so, we will just silently fail.
2020 if (mBadProcesses.get(info.processName, info.uid) != null) {
2021 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2022 + "/" + info.processName);
2023 return null;
2024 }
2025 } else {
2026 // When the user is explicitly starting a process, then clear its
2027 // crash count so that we won't make it bad until they see at
2028 // least one crash dialog again, and make the process good again
2029 // if it had been bad.
2030 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002031 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002032 mProcessCrashTimes.remove(info.processName, info.uid);
2033 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002034 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2035 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002036 info.processName);
2037 mBadProcesses.remove(info.processName, info.uid);
2038 if (app != null) {
2039 app.bad = false;
2040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042 }
2043 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002046 app = newProcessRecordLocked(null, info, processName, isolated);
2047 if (app == null) {
2048 Slog.w(TAG, "Failed making new process record for "
2049 + processName + "/" + info.uid + " isolated=" + isolated);
2050 return null;
2051 }
2052 mProcessNames.put(processName, app.uid, app);
2053 if (isolated) {
2054 mIsolatedProcesses.put(app.uid, app);
2055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 } else {
2057 // If this is a new package in the process, add the package to the list
2058 app.addPackage(info.packageName);
2059 }
2060
2061 // If the system is not ready yet, then hold off on starting this
2062 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002063 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002064 && !isAllowedWhileBooting(info)
2065 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 if (!mProcessesOnHold.contains(app)) {
2067 mProcessesOnHold.add(app);
2068 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002069 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 return app;
2071 }
2072
2073 startProcessLocked(app, hostingType, hostingNameStr);
2074 return (app.pid != 0) ? app : null;
2075 }
2076
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002077 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2078 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2079 }
2080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 private final void startProcessLocked(ProcessRecord app,
2082 String hostingType, String hostingNameStr) {
2083 if (app.pid > 0 && app.pid != MY_PID) {
2084 synchronized (mPidsSelfLocked) {
2085 mPidsSelfLocked.remove(app.pid);
2086 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2087 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002088 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002091 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2092 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 mProcessesOnHold.remove(app);
2094
2095 updateCpuStats();
2096
2097 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2098 mProcDeaths[0] = 0;
2099
2100 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002101 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002104 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002105 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002106 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002107 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002108 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002109 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002110
2111 if (Environment.isExternalStorageEmulated()) {
2112 if (pm.checkPermission(
2113 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2114 app.info.packageName) == PERMISSION_GRANTED) {
2115 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2116 } else {
2117 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2118 }
2119 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002120 } catch (PackageManager.NameNotFoundException e) {
2121 Slog.w(TAG, "Unable to retrieve gids", e);
2122 }
Kenny Roote091f222012-09-11 15:01:26 -07002123
2124 /*
2125 * Add shared application GID so applications can share some
2126 * resources like shared libraries
2127 */
2128 if (permGids == null) {
2129 gids = new int[1];
2130 } else {
2131 gids = new int[permGids.length + 1];
2132 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2133 }
2134 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2137 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2138 && mTopComponent != null
2139 && app.processName.equals(mTopComponent.getPackageName())) {
2140 uid = 0;
2141 }
2142 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2143 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2144 uid = 0;
2145 }
2146 }
2147 int debugFlags = 0;
2148 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2149 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002150 // Also turn on CheckJNI for debuggable apps. It's quite
2151 // awkward to turn on otherwise.
2152 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002154 // Run the app in safe mode if its manifest requests so or the
2155 // system is booted in safe mode.
2156 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2157 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002158 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2161 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2162 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002163 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2164 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 if ("1".equals(SystemProperties.get("debug.assert"))) {
2167 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2168 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002169
2170 // Start the process. It will either succeed and return a result containing
2171 // the PID of the new process, or else throw a RuntimeException.
2172 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002173 app.processName, uid, uid, gids, debugFlags, mountExternal,
Robert Craigd3f8d032013-03-25 06:33:03 -04002174 app.info.targetSdkVersion, app.info.seinfo, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2177 synchronized (bs) {
2178 if (bs.isOnBattery()) {
2179 app.batteryStats.incStartsLocked();
2180 }
2181 }
2182
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002183 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2184 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 app.processName, hostingType,
2186 hostingNameStr != null ? hostingNameStr : "");
2187
2188 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002189 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 }
2191
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002192 StringBuilder buf = mStringBuilder;
2193 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 buf.append("Start proc ");
2195 buf.append(app.processName);
2196 buf.append(" for ");
2197 buf.append(hostingType);
2198 if (hostingNameStr != null) {
2199 buf.append(" ");
2200 buf.append(hostingNameStr);
2201 }
2202 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002203 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 buf.append(" uid=");
2205 buf.append(uid);
2206 buf.append(" gids={");
2207 if (gids != null) {
2208 for (int gi=0; gi<gids.length; gi++) {
2209 if (gi != 0) buf.append(", ");
2210 buf.append(gids[gi]);
2211
2212 }
2213 }
2214 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002215 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002216 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002217 app.usingWrapper = startResult.usingWrapper;
2218 app.removed = false;
2219 synchronized (mPidsSelfLocked) {
2220 this.mPidsSelfLocked.put(startResult.pid, app);
2221 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2222 msg.obj = app;
2223 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2224 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 }
2226 } catch (RuntimeException e) {
2227 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002228 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002229 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
2231 }
2232
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002233 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 if (resumed) {
2235 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2236 } else {
2237 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2238 }
2239 }
2240
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002241 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002242 if (mHeadless) {
2243 // Added because none of the other calls to ensureBootCompleted seem to fire
2244 // when running headless.
2245 ensureBootCompleted();
2246 return false;
2247 }
2248
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002249 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2250 && mTopAction == null) {
2251 // We are running in factory test mode, but unable to find
2252 // the factory test app, so just sit around displaying the
2253 // error message and don't try to start anything.
2254 return false;
2255 }
2256 Intent intent = new Intent(
2257 mTopAction,
2258 mTopData != null ? Uri.parse(mTopData) : null);
2259 intent.setComponent(mTopComponent);
2260 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2261 intent.addCategory(Intent.CATEGORY_HOME);
2262 }
2263 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002264 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002265 if (aInfo != null) {
2266 intent.setComponent(new ComponentName(
2267 aInfo.applicationInfo.packageName, aInfo.name));
2268 // Don't do this if the home app is currently being
2269 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002270 aInfo = new ActivityInfo(aInfo);
2271 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002272 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2273 aInfo.applicationInfo.uid);
2274 if (app == null || app.instrumentationClass == null) {
2275 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002276 mMainStack.startActivityLocked(null, intent, null, aInfo,
2277 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002278 }
2279 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002280
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002281 return true;
2282 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002283
Amith Yamasani259d5e52012-08-31 15:11:01 -07002284 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2285 ActivityInfo ai = null;
2286 ComponentName comp = intent.getComponent();
2287 try {
2288 if (comp != null) {
2289 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2290 } else {
2291 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2292 intent,
2293 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2294 flags, userId);
2295
2296 if (info != null) {
2297 ai = info.activityInfo;
2298 }
2299 }
2300 } catch (RemoteException e) {
2301 // ignore
2302 }
2303
2304 return ai;
2305 }
2306
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002307 /**
2308 * Starts the "new version setup screen" if appropriate.
2309 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002310 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002311 // Only do this once per boot.
2312 if (mCheckedForSetup) {
2313 return;
2314 }
2315
2316 // We will show this screen if the current one is a different
2317 // version than the last one shown, and we are not running in
2318 // low-level factory test mode.
2319 final ContentResolver resolver = mContext.getContentResolver();
2320 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002321 Settings.Global.getInt(resolver,
2322 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002323 mCheckedForSetup = true;
2324
2325 // See if we should be showing the platform update setup UI.
2326 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2327 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2328 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2329
2330 // We don't allow third party apps to replace this.
2331 ResolveInfo ri = null;
2332 for (int i=0; ris != null && i<ris.size(); i++) {
2333 if ((ris.get(i).activityInfo.applicationInfo.flags
2334 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2335 ri = ris.get(i);
2336 break;
2337 }
2338 }
2339
2340 if (ri != null) {
2341 String vers = ri.activityInfo.metaData != null
2342 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2343 : null;
2344 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2345 vers = ri.activityInfo.applicationInfo.metaData.getString(
2346 Intent.METADATA_SETUP_VERSION);
2347 }
2348 String lastVers = Settings.Secure.getString(
2349 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2350 if (vers != null && !vers.equals(lastVers)) {
2351 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2352 intent.setComponent(new ComponentName(
2353 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002354 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2355 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002356 }
2357 }
2358 }
2359 }
2360
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002361 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002362 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002363 }
2364
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002365 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002366 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002367 throw new SecurityException("Isolated process not allowed to call " + caller);
2368 }
2369 }
2370
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002371 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002372 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002373 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002374 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2375 }
2376 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002377
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002378 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002379 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2380 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002381 synchronized (this) {
2382 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2383 }
2384 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002385
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002386 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002387 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002388 synchronized (this) {
2389 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2390 }
2391 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002392
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002393 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002394 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2395 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002396 synchronized (this) {
2397 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002398 }
2399 }
2400
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002401 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002402 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002403 synchronized (this) {
2404 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2405 }
2406 }
2407
2408 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002409 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2410 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002411 synchronized (this) {
2412 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2413 }
2414 }
2415
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002416 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002417 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002418 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002421 private void dispatchProcessesChanged() {
2422 int N;
2423 synchronized (this) {
2424 N = mPendingProcessChanges.size();
2425 if (mActiveProcessChanges.length < N) {
2426 mActiveProcessChanges = new ProcessChangeItem[N];
2427 }
2428 mPendingProcessChanges.toArray(mActiveProcessChanges);
2429 mAvailProcessChanges.addAll(mPendingProcessChanges);
2430 mPendingProcessChanges.clear();
2431 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2432 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002433 int i = mProcessObservers.beginBroadcast();
2434 while (i > 0) {
2435 i--;
2436 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2437 if (observer != null) {
2438 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002439 for (int j=0; j<N; j++) {
2440 ProcessChangeItem item = mActiveProcessChanges[j];
2441 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2442 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2443 + item.pid + " uid=" + item.uid + ": "
2444 + item.foregroundActivities);
2445 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2446 item.foregroundActivities);
2447 }
2448 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2449 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2450 + item.pid + " uid=" + item.uid + ": " + item.importance);
2451 observer.onImportanceChanged(item.pid, item.uid,
2452 item.importance);
2453 }
2454 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002455 } catch (RemoteException e) {
2456 }
2457 }
2458 }
2459 mProcessObservers.finishBroadcast();
2460 }
2461
2462 private void dispatchProcessDied(int pid, int uid) {
2463 int i = mProcessObservers.beginBroadcast();
2464 while (i > 0) {
2465 i--;
2466 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2467 if (observer != null) {
2468 try {
2469 observer.onProcessDied(pid, uid);
2470 } catch (RemoteException e) {
2471 }
2472 }
2473 }
2474 mProcessObservers.finishBroadcast();
2475 }
2476
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002477 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002478 final int N = mPendingActivityLaunches.size();
2479 if (N <= 0) {
2480 return;
2481 }
2482 for (int i=0; i<N; i++) {
2483 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002484 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002485 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002486 }
2487 mPendingActivityLaunches.clear();
2488 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002489
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002490 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002491 Intent intent, String resolvedType, IBinder resultTo,
2492 String resultWho, int requestCode, int startFlags,
2493 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002494 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002495 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002496 }
2497
2498 public final int startActivityAsUser(IApplicationThread caller,
2499 Intent intent, String resolvedType, IBinder resultTo,
2500 String resultWho, int requestCode, int startFlags,
2501 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002502 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002503 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002504 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002505 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002506 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2507 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002508 }
2509
2510 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002511 Intent intent, String resolvedType, IBinder resultTo,
2512 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002513 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002514 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002515 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002516 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002517 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002518 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002519 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002520 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002521 return res;
2522 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002523
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002524 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002525 Intent intent, String resolvedType, IBinder resultTo,
2526 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002527 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002528 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002529 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002530 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002531 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002532 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002533 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002534 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002535 }
2536
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002537 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002538 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002539 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002540 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002541 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002542 // Refuse possible leaked file descriptors
2543 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2544 throw new IllegalArgumentException("File descriptors passed in Intent");
2545 }
2546
2547 IIntentSender sender = intent.getTarget();
2548 if (!(sender instanceof PendingIntentRecord)) {
2549 throw new IllegalArgumentException("Bad PendingIntent object");
2550 }
2551
2552 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002553
2554 synchronized (this) {
2555 // If this is coming from the currently resumed activity, it is
2556 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002557 if (mMainStack.mResumedActivity != null
2558 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002559 Binder.getCallingUid()) {
2560 mAppSwitchesAllowedTime = 0;
2561 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002562 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002563 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2564 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002565 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002566 }
2567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002569 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 // Refuse possible leaked file descriptors
2571 if (intent != null && intent.hasFileDescriptors() == true) {
2572 throw new IllegalArgumentException("File descriptors passed in Intent");
2573 }
2574
2575 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002576 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2577 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002578 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 return false;
2580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 if (r.app == null || r.app.thread == null) {
2582 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002583 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 return false;
2585 }
2586 intent = new Intent(intent);
2587 // The caller is not allowed to change the data.
2588 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2589 // And we are resetting to find the next component...
2590 intent.setComponent(null);
2591
2592 ActivityInfo aInfo = null;
2593 try {
2594 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002595 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002597 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002598 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599
2600 // Look for the original activity in the list...
2601 final int N = resolves != null ? resolves.size() : 0;
2602 for (int i=0; i<N; i++) {
2603 ResolveInfo rInfo = resolves.get(i);
2604 if (rInfo.activityInfo.packageName.equals(r.packageName)
2605 && rInfo.activityInfo.name.equals(r.info.name)) {
2606 // We found the current one... the next matching is
2607 // after it.
2608 i++;
2609 if (i<N) {
2610 aInfo = resolves.get(i).activityInfo;
2611 }
2612 break;
2613 }
2614 }
2615 } catch (RemoteException e) {
2616 }
2617
2618 if (aInfo == null) {
2619 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002620 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 return false;
2622 }
2623
2624 intent.setComponent(new ComponentName(
2625 aInfo.applicationInfo.packageName, aInfo.name));
2626 intent.setFlags(intent.getFlags()&~(
2627 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2628 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2629 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2630 Intent.FLAG_ACTIVITY_NEW_TASK));
2631
2632 // Okay now we need to start the new activity, replacing the
2633 // currently running activity. This is a little tricky because
2634 // we want to start the new one as if the current one is finished,
2635 // but not finish the current one first so that there is no flicker.
2636 // And thus...
2637 final boolean wasFinishing = r.finishing;
2638 r.finishing = true;
2639
2640 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002641 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 final String resultWho = r.resultWho;
2643 final int requestCode = r.requestCode;
2644 r.resultTo = null;
2645 if (resultTo != null) {
2646 resultTo.removeResultsLocked(r, resultWho, requestCode);
2647 }
2648
2649 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002650 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002651 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2652 resultWho, requestCode, -1, r.launchedFromUid, 0,
2653 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 Binder.restoreCallingIdentity(origId);
2655
2656 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002657 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 return false;
2659 }
2660 return true;
2661 }
2662 }
2663
Dianne Hackborn41203752012-08-31 14:05:51 -07002664 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002666 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2667
Dianne Hackborn139748f2012-09-24 11:36:57 -07002668 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002669 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670
Amith Yamasani742a6712011-05-04 14:49:28 -07002671 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002672 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002673 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002674 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002675 }
2676
2677 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002678 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2679 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002680 enforceNotIsolatedCaller("startActivities");
Amith Yamasani95293862012-09-24 18:14:47 -07002681 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002682 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002683 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002684 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002685 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002686 }
2687
Dianne Hackborn41203752012-08-31 14:05:51 -07002688 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002689 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002690 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002691
Dianne Hackborn139748f2012-09-24 11:36:57 -07002692 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002693 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002694 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002695 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002696 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 }
2698
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002699 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002701 // Quick case: check if the top-most recent task is the same.
2702 if (N > 0 && mRecentTasks.get(0) == task) {
2703 return;
2704 }
2705 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 for (int i=0; i<N; i++) {
2707 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002708 if (task.userId == tr.userId
2709 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2710 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 mRecentTasks.remove(i);
2712 i--;
2713 N--;
2714 if (task.intent == null) {
2715 // If the new recent task we are adding is not fully
2716 // specified, then replace it with the existing recent task.
2717 task = tr;
2718 }
2719 }
2720 }
2721 if (N >= MAX_RECENT_TASKS) {
2722 mRecentTasks.remove(N-1);
2723 }
2724 mRecentTasks.add(0, task);
2725 }
2726
2727 public void setRequestedOrientation(IBinder token,
2728 int requestedOrientation) {
2729 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002730 ActivityRecord r = mMainStack.isInStackLocked(token);
2731 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 return;
2733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002735 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002737 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002738 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 if (config != null) {
2740 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002741 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002742 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 }
2744 }
2745 Binder.restoreCallingIdentity(origId);
2746 }
2747 }
2748
2749 public int getRequestedOrientation(IBinder token) {
2750 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002751 ActivityRecord r = mMainStack.isInStackLocked(token);
2752 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2754 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002755 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
2757 }
2758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 /**
2760 * This is the internal entry point for handling Activity.finish().
2761 *
2762 * @param token The Binder token referencing the Activity we want to finish.
2763 * @param resultCode Result code, if any, from this Activity.
2764 * @param resultData Result data (Intent), if any, from this Activity.
2765 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002766 * @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 -08002767 */
2768 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2769 // Refuse possible leaked file descriptors
2770 if (resultData != null && resultData.hasFileDescriptors() == true) {
2771 throw new IllegalArgumentException("File descriptors passed in Intent");
2772 }
2773
2774 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002775 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 if (next != null) {
2779 // ask watcher if this is allowed
2780 boolean resumeOK = true;
2781 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002782 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002784 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 }
2786
2787 if (!resumeOK) {
2788 return false;
2789 }
2790 }
2791 }
2792 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002793 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002794 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 Binder.restoreCallingIdentity(origId);
2796 return res;
2797 }
2798 }
2799
Dianne Hackborn860755f2010-06-03 18:47:52 -07002800 public final void finishHeavyWeightApp() {
2801 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2802 != PackageManager.PERMISSION_GRANTED) {
2803 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2804 + Binder.getCallingPid()
2805 + ", uid=" + Binder.getCallingUid()
2806 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2807 Slog.w(TAG, msg);
2808 throw new SecurityException(msg);
2809 }
2810
2811 synchronized(this) {
2812 if (mHeavyWeightProcess == null) {
2813 return;
2814 }
2815
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002816 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002817 mHeavyWeightProcess.activities);
2818 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002819 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002820 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002821 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002822 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002823 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002824 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002825 }
2826 }
2827 }
2828
Dianne Hackborn41203752012-08-31 14:05:51 -07002829 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2830 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002831 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002832 }
2833 }
2834
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002835 public void crashApplication(int uid, int initialPid, String packageName,
2836 String message) {
2837 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2838 != PackageManager.PERMISSION_GRANTED) {
2839 String msg = "Permission Denial: crashApplication() from pid="
2840 + Binder.getCallingPid()
2841 + ", uid=" + Binder.getCallingUid()
2842 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2843 Slog.w(TAG, msg);
2844 throw new SecurityException(msg);
2845 }
2846
2847 synchronized(this) {
2848 ProcessRecord proc = null;
2849
2850 // Figure out which process to kill. We don't trust that initialPid
2851 // still has any relation to current pids, so must scan through the
2852 // list.
2853 synchronized (mPidsSelfLocked) {
2854 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2855 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002856 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002857 continue;
2858 }
2859 if (p.pid == initialPid) {
2860 proc = p;
2861 break;
2862 }
2863 for (String str : p.pkgList) {
2864 if (str.equals(packageName)) {
2865 proc = p;
2866 }
2867 }
2868 }
2869 }
2870
2871 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002872 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002873 + " initialPid=" + initialPid
2874 + " packageName=" + packageName);
2875 return;
2876 }
2877
2878 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002879 if (proc.pid == Process.myPid()) {
2880 Log.w(TAG, "crashApplication: trying to crash self!");
2881 return;
2882 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002883 long ident = Binder.clearCallingIdentity();
2884 try {
2885 proc.thread.scheduleCrash(message);
2886 } catch (RemoteException e) {
2887 }
2888 Binder.restoreCallingIdentity(ident);
2889 }
2890 }
2891 }
2892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 public final void finishSubActivity(IBinder token, String resultWho,
2894 int requestCode) {
2895 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002897 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 Binder.restoreCallingIdentity(origId);
2899 }
2900 }
2901
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002902 public boolean finishActivityAffinity(IBinder token) {
2903 synchronized(this) {
2904 final long origId = Binder.clearCallingIdentity();
2905 boolean res = mMainStack.finishActivityAffinityLocked(token);
2906 Binder.restoreCallingIdentity(origId);
2907 return res;
2908 }
2909 }
2910
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002911 public boolean willActivityBeVisible(IBinder token) {
2912 synchronized(this) {
2913 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002914 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2915 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002916 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002917 return true;
2918 }
2919 if (r.fullscreen && !r.finishing) {
2920 return false;
2921 }
2922 }
2923 return true;
2924 }
2925 }
2926
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002927 public void overridePendingTransition(IBinder token, String packageName,
2928 int enterAnim, int exitAnim) {
2929 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002930 ActivityRecord self = mMainStack.isInStackLocked(token);
2931 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002932 return;
2933 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002934
2935 final long origId = Binder.clearCallingIdentity();
2936
2937 if (self.state == ActivityState.RESUMED
2938 || self.state == ActivityState.PAUSING) {
2939 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002940 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002941 }
2942
2943 Binder.restoreCallingIdentity(origId);
2944 }
2945 }
2946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 * Main function for removing an existing process from the activity manager
2949 * as a result of that process going away. Clears out all connections
2950 * to the process.
2951 */
2952 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002953 boolean restarting, boolean allowRestart) {
2954 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002956 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 }
2958
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002959 if (mProfileProc == app) {
2960 clearProfilerLocked();
2961 }
2962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002964 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002965 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2966 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002967 mMainStack.mPausingActivity = null;
2968 }
2969 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2970 mMainStack.mLastPausedActivity = null;
2971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972
2973 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002974 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975
2976 app.activities.clear();
2977
2978 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002979 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 + " running instrumentation " + app.instrumentationClass);
2981 Bundle info = new Bundle();
2982 info.putString("shortMsg", "Process crashed.");
2983 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2984 }
2985
2986 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002987 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 // If there was nothing to resume, and we are not already
2989 // restarting this process, but there is a visible activity that
2990 // is hosted by the process... then make sure all visible
2991 // activities are running, taking care of restarting this
2992 // process.
2993 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002994 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 }
2996 }
2997 }
2998 }
2999
3000 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3001 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003003 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3004 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3006 return i;
3007 }
3008 }
3009 return -1;
3010 }
3011
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003012 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 IApplicationThread thread) {
3014 if (thread == null) {
3015 return null;
3016 }
3017
3018 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003019 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 }
3021
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003022 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 IApplicationThread thread) {
3024
3025 mProcDeaths[0]++;
3026
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003027 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3028 synchronized (stats) {
3029 stats.noteProcessDiedLocked(app.info.uid, pid);
3030 }
3031
Magnus Edlund7bb25812010-02-24 15:45:06 +01003032 // Clean up already done if the process has been re-started.
3033 if (app.pid == pid && app.thread != null &&
3034 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003035 if (!app.killedBackground) {
3036 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3037 + ") has died.");
3038 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003039 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003040 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 TAG, "Dying app: " + app + ", pid: " + pid
3042 + ", thread: " + thread.asBinder());
3043 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003044 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045
3046 if (doLowMem) {
3047 // If there are no longer any background processes running,
3048 // and the app that died was not running instrumentation,
3049 // then tell everyone we are now low on memory.
3050 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003051 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3052 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003053 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 haveBg = true;
3055 break;
3056 }
3057 }
3058
3059 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003060 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003061 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003062 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3063 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003064 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003065 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3066 // The low memory report is overriding any current
3067 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003068 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003069 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003070 rec.lastRequestedGc = 0;
3071 } else {
3072 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003074 rec.reportLowMemory = true;
3075 rec.lastLowMemory = now;
3076 mProcessesToGc.remove(rec);
3077 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 }
3079 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003080 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003081 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 }
3083 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003084 } else if (app.pid != pid) {
3085 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003086 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003087 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003088 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003089 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003090 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 + thread.asBinder());
3092 }
3093 }
3094
Dan Egnor42471dd2010-01-07 17:25:22 -08003095 /**
3096 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003097 * @param clearTraces causes the dump file to be erased prior to the new
3098 * traces being written, if true; when false, the new traces will be
3099 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003100 * @param firstPids of dalvik VM processes to dump stack traces for first
3101 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003102 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003103 * @return file containing stack traces, or null if no dump file is configured
3104 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003105 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003106 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003107 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3108 if (tracesPath == null || tracesPath.length() == 0) {
3109 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003111
3112 File tracesFile = new File(tracesPath);
3113 try {
3114 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003115 if (!tracesDir.exists()) {
3116 tracesFile.mkdirs();
3117 if (!SELinux.restorecon(tracesDir)) {
3118 return null;
3119 }
3120 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003121 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3122
Christopher Tate6ee412d2010-05-28 12:01:56 -07003123 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003124 tracesFile.createNewFile();
3125 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3126 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003127 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003128 return null;
3129 }
3130
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003131 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003132 return tracesFile;
3133 }
3134
3135 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003136 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003137 // Use a FileObserver to detect when traces finish writing.
3138 // The order of traces is considered important to maintain for legibility.
3139 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3140 public synchronized void onEvent(int event, String path) { notify(); }
3141 };
3142
3143 try {
3144 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003145
3146 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003147 if (firstPids != null) {
3148 try {
3149 int num = firstPids.size();
3150 for (int i = 0; i < num; i++) {
3151 synchronized (observer) {
3152 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3153 observer.wait(200); // Wait for write-close, give up after 200msec
3154 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003155 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003156 } catch (InterruptedException e) {
3157 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003158 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003159 }
3160
3161 // Next measure CPU usage.
3162 if (processStats != null) {
3163 processStats.init();
3164 System.gc();
3165 processStats.update();
3166 try {
3167 synchronized (processStats) {
3168 processStats.wait(500); // measure over 1/2 second.
3169 }
3170 } catch (InterruptedException e) {
3171 }
3172 processStats.update();
3173
3174 // We'll take the stack crawls of just the top apps using CPU.
3175 final int N = processStats.countWorkingStats();
3176 int numProcs = 0;
3177 for (int i=0; i<N && numProcs<5; i++) {
3178 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3179 if (lastPids.indexOfKey(stats.pid) >= 0) {
3180 numProcs++;
3181 try {
3182 synchronized (observer) {
3183 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3184 observer.wait(200); // Wait for write-close, give up after 200msec
3185 }
3186 } catch (InterruptedException e) {
3187 Log.wtf(TAG, e);
3188 }
3189
3190 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003191 }
3192 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003193
Dan Egnor42471dd2010-01-07 17:25:22 -08003194 } finally {
3195 observer.stopWatching();
3196 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003197
3198 if (nativeProcs != null) {
3199 int[] pids = Process.getPidsForCommands(nativeProcs);
3200 if (pids != null) {
3201 for (int pid : pids) {
3202 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3203 }
3204 }
3205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
3207
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003208 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003209 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003210 return;
3211 }
3212 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3213 if (tracesPath == null || tracesPath.length() == 0) {
3214 return;
3215 }
3216
3217 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3218 StrictMode.allowThreadDiskWrites();
3219 try {
3220 final File tracesFile = new File(tracesPath);
3221 final File tracesDir = tracesFile.getParentFile();
3222 final File tracesTmp = new File(tracesDir, "__tmp__");
3223 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003224 if (!tracesDir.exists()) {
3225 tracesFile.mkdirs();
3226 if (!SELinux.restorecon(tracesDir.getPath())) {
3227 return;
3228 }
3229 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003230 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3231
3232 if (tracesFile.exists()) {
3233 tracesTmp.delete();
3234 tracesFile.renameTo(tracesTmp);
3235 }
3236 StringBuilder sb = new StringBuilder();
3237 Time tobj = new Time();
3238 tobj.set(System.currentTimeMillis());
3239 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3240 sb.append(": ");
3241 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3242 sb.append(" since ");
3243 sb.append(msg);
3244 FileOutputStream fos = new FileOutputStream(tracesFile);
3245 fos.write(sb.toString().getBytes());
3246 if (app == null) {
3247 fos.write("\n*** No application process!".getBytes());
3248 }
3249 fos.close();
3250 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3251 } catch (IOException e) {
3252 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3253 return;
3254 }
3255
3256 if (app != null) {
3257 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3258 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003259 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003260 }
3261
3262 File lastTracesFile = null;
3263 File curTracesFile = null;
3264 for (int i=9; i>=0; i--) {
3265 String name = String.format("slow%02d.txt", i);
3266 curTracesFile = new File(tracesDir, name);
3267 if (curTracesFile.exists()) {
3268 if (lastTracesFile != null) {
3269 curTracesFile.renameTo(lastTracesFile);
3270 } else {
3271 curTracesFile.delete();
3272 }
3273 }
3274 lastTracesFile = curTracesFile;
3275 }
3276 tracesFile.renameTo(curTracesFile);
3277 if (tracesTmp.exists()) {
3278 tracesTmp.renameTo(tracesFile);
3279 }
3280 } finally {
3281 StrictMode.setThreadPolicy(oldPolicy);
3282 }
3283 }
3284
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003285 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003286 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003287 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3288 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3289
Dianne Hackborn287952c2010-09-22 22:34:31 -07003290 if (mController != null) {
3291 try {
3292 // 0 == continue, -1 = kill process immediately
3293 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3294 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3295 } catch (RemoteException e) {
3296 mController = null;
3297 }
3298 }
3299
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003300 long anrTime = SystemClock.uptimeMillis();
3301 if (MONITOR_CPU_USAGE) {
3302 updateCpuStatsNow();
3303 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003304
3305 synchronized (this) {
3306 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3307 if (mShuttingDown) {
3308 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3309 return;
3310 } else if (app.notResponding) {
3311 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3312 return;
3313 } else if (app.crashing) {
3314 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3315 return;
3316 }
3317
3318 // In case we come through here for the same app before completing
3319 // this one, mark as anring now so we will bail out.
3320 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003321
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003322 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003323 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3324 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003325
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003326 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003327 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003328
3329 int parentPid = app.pid;
3330 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003331 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003332
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003333 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003334
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003335 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3336 ProcessRecord r = mLruProcesses.get(i);
3337 if (r != null && r.thread != null) {
3338 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003339 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3340 if (r.persistent) {
3341 firstPids.add(pid);
3342 } else {
3343 lastPids.put(pid, Boolean.TRUE);
3344 }
3345 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 }
3348 }
3349
Dan Egnor42471dd2010-01-07 17:25:22 -08003350 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003351 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003352 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003353 info.append("ANR in ").append(app.processName);
3354 if (activity != null && activity.shortComponentName != null) {
3355 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003356 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003357 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003359 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003361 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003362 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364
Dianne Hackborn287952c2010-09-22 22:34:31 -07003365 final ProcessStats processStats = new ProcessStats(true);
3366
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003367 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003368
Dan Egnor42471dd2010-01-07 17:25:22 -08003369 String cpuInfo = null;
3370 if (MONITOR_CPU_USAGE) {
3371 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003372 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003373 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003374 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003375 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003376 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
3378
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003379 info.append(processStats.printCurrentState(anrTime));
3380
Joe Onorato8a9b2202010-02-26 18:56:32 -08003381 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003382 if (tracesFile == null) {
3383 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3384 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3385 }
3386
Jeff Sharkeya353d262011-10-28 11:12:06 -07003387 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3388 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003389
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003390 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003392 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3393 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003395 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3396 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
3398 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003399 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
3401 }
3402
Dan Egnor42471dd2010-01-07 17:25:22 -08003403 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3404 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3405 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003406
3407 synchronized (this) {
3408 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003409 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003410 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003411 app.processName, app.setAdj, "background ANR");
3412 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003413 return;
3414 }
3415
3416 // Set the app's notResponding state, and look up the errorReportReceiver
3417 makeAppNotRespondingLocked(app,
3418 activity != null ? activity.shortComponentName : null,
3419 annotation != null ? "ANR " + annotation : "ANR",
3420 info.toString());
3421
3422 // Bring up the infamous App Not Responding dialog
3423 Message msg = Message.obtain();
3424 HashMap map = new HashMap();
3425 msg.what = SHOW_NOT_RESPONDING_MSG;
3426 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003427 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003428 map.put("app", app);
3429 if (activity != null) {
3430 map.put("activity", activity);
3431 }
3432
3433 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 }
3436
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003437 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3438 if (!mLaunchWarningShown) {
3439 mLaunchWarningShown = true;
3440 mHandler.post(new Runnable() {
3441 @Override
3442 public void run() {
3443 synchronized (ActivityManagerService.this) {
3444 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3445 d.show();
3446 mHandler.postDelayed(new Runnable() {
3447 @Override
3448 public void run() {
3449 synchronized (ActivityManagerService.this) {
3450 d.dismiss();
3451 mLaunchWarningShown = false;
3452 }
3453 }
3454 }, 4000);
3455 }
3456 }
3457 });
3458 }
3459 }
3460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003462 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003463 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 int uid = Binder.getCallingUid();
3465 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003466 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003467 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 long callingId = Binder.clearCallingIdentity();
3469 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003470 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 int pkgUid = -1;
3472 synchronized(this) {
3473 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003474 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 } catch (RemoteException e) {
3476 }
3477 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003478 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 return false;
3480 }
3481 if (uid == pkgUid || checkComponentPermission(
3482 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003483 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003485 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 } else {
3487 throw new SecurityException(pid+" does not have permission:"+
3488 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3489 "for process:"+packageName);
3490 }
3491 }
3492
3493 try {
3494 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003495 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3497 Uri.fromParts("package", packageName, null));
3498 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003499 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003500 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 } catch (RemoteException e) {
3502 }
3503 } finally {
3504 Binder.restoreCallingIdentity(callingId);
3505 }
3506 return true;
3507 }
3508
Dianne Hackborn1676c852012-09-10 14:52:30 -07003509 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003510 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3511 != PackageManager.PERMISSION_GRANTED &&
3512 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3513 != PackageManager.PERMISSION_GRANTED) {
3514 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 + Binder.getCallingPid()
3516 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003517 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003518 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 throw new SecurityException(msg);
3520 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003521
Dianne Hackborn139748f2012-09-24 11:36:57 -07003522 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003523 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 long callingId = Binder.clearCallingIdentity();
3525 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003526 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003528 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003530 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 } catch (RemoteException e) {
3532 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003533 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003534 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 return;
3536 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003537 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003538 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3539 }
3540 } finally {
3541 Binder.restoreCallingIdentity(callingId);
3542 }
3543 }
3544
3545 public void killAllBackgroundProcesses() {
3546 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3547 != PackageManager.PERMISSION_GRANTED) {
3548 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3549 + Binder.getCallingPid()
3550 + ", uid=" + Binder.getCallingUid()
3551 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3552 Slog.w(TAG, msg);
3553 throw new SecurityException(msg);
3554 }
3555
3556 long callingId = Binder.clearCallingIdentity();
3557 try {
3558 synchronized(this) {
3559 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3560 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3561 final int NA = apps.size();
3562 for (int ia=0; ia<NA; ia++) {
3563 ProcessRecord app = apps.valueAt(ia);
3564 if (app.persistent) {
3565 // we don't kill persistent processes
3566 continue;
3567 }
3568 if (app.removed) {
3569 procs.add(app);
3570 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3571 app.removed = true;
3572 procs.add(app);
3573 }
3574 }
3575 }
3576
3577 int N = procs.size();
3578 for (int i=0; i<N; i++) {
3579 removeProcessLocked(procs.get(i), false, true, "kill all background");
3580 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003581 }
3582 } finally {
3583 Binder.restoreCallingIdentity(callingId);
3584 }
3585 }
3586
Dianne Hackborn1676c852012-09-10 14:52:30 -07003587 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003588 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3589 != PackageManager.PERMISSION_GRANTED) {
3590 String msg = "Permission Denial: forceStopPackage() from pid="
3591 + Binder.getCallingPid()
3592 + ", uid=" + Binder.getCallingUid()
3593 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003594 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003595 throw new SecurityException(msg);
3596 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003597 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003598 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 long callingId = Binder.clearCallingIdentity();
3600 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003601 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003602 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003603 int[] users = userId == UserHandle.USER_ALL
3604 ? getUsersLocked() : new int[] { userId };
3605 for (int user : users) {
3606 int pkgUid = -1;
3607 try {
3608 pkgUid = pm.getPackageUid(packageName, user);
3609 } catch (RemoteException e) {
3610 }
3611 if (pkgUid == -1) {
3612 Slog.w(TAG, "Invalid packageName: " + packageName);
3613 continue;
3614 }
3615 try {
3616 pm.setPackageStoppedState(packageName, true, user);
3617 } catch (RemoteException e) {
3618 } catch (IllegalArgumentException e) {
3619 Slog.w(TAG, "Failed trying to unstop package "
3620 + packageName + ": " + e);
3621 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003622 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003623 forceStopPackageLocked(packageName, pkgUid);
3624 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 }
3627 } finally {
3628 Binder.restoreCallingIdentity(callingId);
3629 }
3630 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003631
3632 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003633 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003634 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003635 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003636 if (pkg == null) {
3637 return;
3638 }
3639 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003640 if (appid < 0) {
3641 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003642 return;
3643 }
3644 int callerUid = Binder.getCallingUid();
3645 // Only the system server can kill an application
3646 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003647 // Post an aysnc message to kill the application
3648 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003649 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003650 msg.arg2 = 0;
3651 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003652 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003653 } else {
3654 throw new SecurityException(callerUid + " cannot kill pkg: " +
3655 pkg);
3656 }
3657 }
3658
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003659 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003660 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003661
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003662 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003663 final int uid = Binder.getCallingUid();
3664 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003665 try {
3666 synchronized (this) {
3667 // Only allow this from foreground processes, so that background
3668 // applications can't abuse it to prevent system UI from being shown.
3669 if (uid >= Process.FIRST_APPLICATION_UID) {
3670 ProcessRecord proc;
3671 synchronized (mPidsSelfLocked) {
3672 proc = mPidsSelfLocked.get(pid);
3673 }
3674 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3675 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3676 + " from background process " + proc);
3677 return;
3678 }
3679 }
3680 closeSystemDialogsLocked(reason);
3681 }
3682 } finally {
3683 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003684 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003685 }
3686
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003687 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003688 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003689 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3690 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003691 if (reason != null) {
3692 intent.putExtra("reason", reason);
3693 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003694 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003695
Dianne Hackborne302a162012-05-15 14:58:32 -07003696 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3697 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003698 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003699 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003700 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003701 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003702 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003703
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003704 broadcastIntentLocked(null, null, intent, null,
3705 null, 0, null, null, null, false, false, -1,
3706 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003707 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003708
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003709 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003710 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003711 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003712 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3713 for (int i=pids.length-1; i>=0; i--) {
3714 infos[i] = new Debug.MemoryInfo();
3715 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003716 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003717 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003718 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003719
Dianne Hackbornb437e092011-08-05 17:50:29 -07003720 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003721 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003722 long[] pss = new long[pids.length];
3723 for (int i=pids.length-1; i>=0; i--) {
3724 pss[i] = Debug.getPss(pids[i]);
3725 }
3726 return pss;
3727 }
3728
Christopher Tate5e1ab332009-09-01 20:32:49 -07003729 public void killApplicationProcess(String processName, int uid) {
3730 if (processName == null) {
3731 return;
3732 }
3733
3734 int callerUid = Binder.getCallingUid();
3735 // Only the system server can kill an application
3736 if (callerUid == Process.SYSTEM_UID) {
3737 synchronized (this) {
3738 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003739 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003740 try {
3741 app.thread.scheduleSuicide();
3742 } catch (RemoteException e) {
3743 // If the other end already died, then our work here is done.
3744 }
3745 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003746 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003747 + processName + " / " + uid);
3748 }
3749 }
3750 } else {
3751 throw new SecurityException(callerUid + " cannot kill app process: " +
3752 processName);
3753 }
3754 }
3755
Dianne Hackborn03abb812010-01-04 18:43:19 -08003756 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003757 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3758 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3760 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003761 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003762 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3763 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003764 }
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);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003776 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3777 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003778 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3779 broadcastIntentLocked(null, null, intent,
3780 null, null, 0, null, null, null,
3781 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003782 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003783 }
3784
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003785 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003786 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3787 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003788 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789
Dianne Hackborn03abb812010-01-04 18:43:19 -08003790 // Remove all processes this package may have touched: all with the
3791 // same UID (except for the system or root user), and all whose name
3792 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003793 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003794 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3795 final int NA = apps.size();
3796 for (int ia=0; ia<NA; ia++) {
3797 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003798 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003799 // we don't kill persistent processes
3800 continue;
3801 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003802 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003803 if (doit) {
3804 procs.add(app);
3805 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003806 continue;
3807 }
3808
3809 // Skip process if it doesn't meet our oom adj requirement.
3810 if (app.setAdj < minOomAdj) {
3811 continue;
3812 }
3813
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003814 // If no package is specified, we call all processes under the
3815 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003816 if (packageName == null) {
3817 if (app.userId != userId) {
3818 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003819 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003820 // Package has been specified, we want to hit all processes
3821 // that match it. We need to qualify this by the processes
3822 // that are running under the specified app and user ID.
3823 } else {
3824 if (UserHandle.getAppId(app.uid) != appId) {
3825 continue;
3826 }
3827 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3828 continue;
3829 }
3830 if (!app.pkgList.contains(packageName)) {
3831 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003832 }
3833 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003834
3835 // Process has passed all conditions, kill it!
3836 if (!doit) {
3837 return true;
3838 }
3839 app.removed = true;
3840 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003841 }
3842 }
3843
3844 int N = procs.size();
3845 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003846 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003847 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003848 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003849 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003850
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003851 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003852 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003853 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003854 int i;
3855 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003857 if (userId == UserHandle.USER_ALL && name == null) {
3858 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3859 }
3860
3861 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003863 appId = UserHandle.getAppId(
3864 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 } catch (RemoteException e) {
3866 }
3867 }
3868
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003869 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003870 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003871 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3872 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003873 } else {
3874 Slog.i(TAG, "Force stopping user " + userId);
3875 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003876
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003877 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3878 while (badApps.hasNext()) {
3879 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003880 for (i=ba.size()-1; i>=0; i--) {
3881 boolean remove = false;
3882 final int entUid = ba.keyAt(i);
3883 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003884 if (userId == UserHandle.USER_ALL) {
3885 if (UserHandle.getAppId(entUid) == appId) {
3886 remove = true;
3887 }
3888 } else {
3889 if (entUid == UserHandle.getUid(userId, appId)) {
3890 remove = true;
3891 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003892 }
3893 } else if (UserHandle.getUserId(entUid) == userId) {
3894 remove = true;
3895 }
3896 if (remove) {
3897 ba.removeAt(i);
3898 }
3899 }
3900 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003901 badApps.remove();
3902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 }
3904 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003905
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003906 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003907 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003908 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003910 TaskRecord lastTask = null;
3911 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003912 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003913 final boolean samePackage = r.packageName.equals(name)
3914 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003915 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003916 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003917 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003918 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003919 if (r.finishing) {
3920 // If this activity is just finishing, then it is not
3921 // interesting as far as something to stop.
3922 continue;
3923 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003924 return true;
3925 }
3926 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003927 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003928 if (samePackage) {
3929 if (r.app != null) {
3930 r.app.removed = true;
3931 }
3932 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003934 lastTask = r.task;
3935 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003936 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003937 i--;
3938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
3940 }
3941
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003942 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3943 if (!doit) {
3944 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003946 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003948
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003949 if (name == null) {
3950 // Remove all sticky broadcasts from this user.
3951 mStickyBroadcasts.remove(userId);
3952 }
3953
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003954 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003955 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3956 userId, providers)) {
3957 if (!doit) {
3958 return true;
3959 }
3960 didSomething = true;
3961 }
3962 N = providers.size();
3963 for (i=0; i<N; i++) {
3964 removeDyingProviderLocked(null, providers.get(i), true);
3965 }
3966
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003967 if (name == null) {
3968 // Remove pending intents. For now we only do this when force
3969 // stopping users, because we have some problems when doing this
3970 // for packages -- app widgets are not currently cleaned up for
3971 // such packages, so they can be left with bad pending intents.
3972 if (mIntentSenderRecords.size() > 0) {
3973 Iterator<WeakReference<PendingIntentRecord>> it
3974 = mIntentSenderRecords.values().iterator();
3975 while (it.hasNext()) {
3976 WeakReference<PendingIntentRecord> wpir = it.next();
3977 if (wpir == null) {
3978 it.remove();
3979 continue;
3980 }
3981 PendingIntentRecord pir = wpir.get();
3982 if (pir == null) {
3983 it.remove();
3984 continue;
3985 }
3986 if (name == null) {
3987 // Stopping user, remove all objects for the user.
3988 if (pir.key.userId != userId) {
3989 // Not the same user, skip it.
3990 continue;
3991 }
3992 } else {
3993 if (UserHandle.getAppId(pir.uid) != appId) {
3994 // Different app id, skip it.
3995 continue;
3996 }
3997 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3998 // Different user, skip it.
3999 continue;
4000 }
4001 if (!pir.key.packageName.equals(name)) {
4002 // Different package, skip it.
4003 continue;
4004 }
4005 }
4006 if (!doit) {
4007 return true;
4008 }
4009 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004010 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004011 pir.canceled = true;
4012 if (pir.key.activity != null) {
4013 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004014 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004015 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004016 }
4017 }
4018
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004019 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004020 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004021 AttributeCache ac = AttributeCache.instance();
4022 if (ac != null) {
4023 ac.removePackage(name);
4024 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004025 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004026 if (mBooted) {
4027 mMainStack.resumeTopActivityLocked(null);
4028 mMainStack.scheduleIdleLocked();
4029 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004030 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004031
4032 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
4034
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004035 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004036 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004038 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004040 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 + "/" + uid + ")");
4042
4043 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004044 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004045 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004046 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4047 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004048 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004050 boolean needRestart = false;
4051 if (app.pid > 0 && app.pid != MY_PID) {
4052 int pid = app.pid;
4053 synchronized (mPidsSelfLocked) {
4054 mPidsSelfLocked.remove(pid);
4055 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4056 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004057 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004058 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004059 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004060 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004062 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004064 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 } else {
4066 needRestart = true;
4067 }
4068 }
4069 } else {
4070 mRemovedProcesses.add(app);
4071 }
4072
4073 return needRestart;
4074 }
4075
4076 private final void processStartTimedOutLocked(ProcessRecord app) {
4077 final int pid = app.pid;
4078 boolean gone = false;
4079 synchronized (mPidsSelfLocked) {
4080 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4081 if (knownApp != null && knownApp.thread == null) {
4082 mPidsSelfLocked.remove(pid);
4083 gone = true;
4084 }
4085 }
4086
4087 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004088 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004089 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4090 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004091 mProcessNames.remove(app.processName, app.uid);
4092 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004093 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004094 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4095 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004096 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004097 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004098 // Take care of any launching providers waiting for this process.
4099 checkAppInLaunchingProvidersLocked(app, true);
4100 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004101 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004102 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004103 app.processName, app.setAdj, "start timeout");
4104 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004105 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004106 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004107 try {
4108 IBackupManager bm = IBackupManager.Stub.asInterface(
4109 ServiceManager.getService(Context.BACKUP_SERVICE));
4110 bm.agentDisconnected(app.info.packageName);
4111 } catch (RemoteException e) {
4112 // Can't happen; the backup manager is local
4113 }
4114 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004115 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004116 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004117 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004120 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 }
4122 }
4123
4124 private final boolean attachApplicationLocked(IApplicationThread thread,
4125 int pid) {
4126
4127 // Find the application record that is being attached... either via
4128 // the pid if we are running in multiple processes, or just pull the
4129 // next app record if we are emulating process with anonymous threads.
4130 ProcessRecord app;
4131 if (pid != MY_PID && pid >= 0) {
4132 synchronized (mPidsSelfLocked) {
4133 app = mPidsSelfLocked.get(pid);
4134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 } else {
4136 app = null;
4137 }
4138
4139 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004140 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004142 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004144 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 } else {
4146 try {
4147 thread.scheduleExit();
4148 } catch (Exception e) {
4149 // Ignore exceptions.
4150 }
4151 }
4152 return false;
4153 }
4154
4155 // If this application record is still attached to a previous
4156 // process, clean it up now.
4157 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004158 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
4160
4161 // Tell the process all about itself.
4162
Joe Onorato8a9b2202010-02-26 18:56:32 -08004163 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 TAG, "Binding process pid " + pid + " to record " + app);
4165
4166 String processName = app.processName;
4167 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004168 AppDeathRecipient adr = new AppDeathRecipient(
4169 app, pid, thread);
4170 thread.asBinder().linkToDeath(adr, 0);
4171 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 } catch (RemoteException e) {
4173 app.resetPackageList();
4174 startProcessLocked(app, "link fail", processName);
4175 return false;
4176 }
4177
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004178 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179
4180 app.thread = thread;
4181 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004182 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4183 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 app.forcingToForeground = null;
4185 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004186 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 app.debugging = false;
4188
4189 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4190
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004191 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004192 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004194 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004195 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004196 }
4197
Joe Onorato8a9b2202010-02-26 18:56:32 -08004198 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 TAG, "New app record " + app
4200 + " thread=" + thread.asBinder() + " pid=" + pid);
4201 try {
4202 int testMode = IApplicationThread.DEBUG_OFF;
4203 if (mDebugApp != null && mDebugApp.equals(processName)) {
4204 testMode = mWaitForDebugger
4205 ? IApplicationThread.DEBUG_WAIT
4206 : IApplicationThread.DEBUG_ON;
4207 app.debugging = true;
4208 if (mDebugTransient) {
4209 mDebugApp = mOrigDebugApp;
4210 mWaitForDebugger = mOrigWaitForDebugger;
4211 }
4212 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004213 String profileFile = app.instrumentationProfileFile;
4214 ParcelFileDescriptor profileFd = null;
4215 boolean profileAutoStop = false;
4216 if (mProfileApp != null && mProfileApp.equals(processName)) {
4217 mProfileProc = app;
4218 profileFile = mProfileFile;
4219 profileFd = mProfileFd;
4220 profileAutoStop = mAutoStopProfiler;
4221 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004222 boolean enableOpenGlTrace = false;
4223 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4224 enableOpenGlTrace = true;
4225 mOpenGlTraceApp = null;
4226 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004227
Christopher Tate181fafa2009-05-14 11:12:14 -07004228 // If the app is being launched for restore or full backup, set it up specially
4229 boolean isRestrictedBackupMode = false;
4230 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4231 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004232 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004233 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4234 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004235
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004236 ensurePackageDexOpt(app.instrumentationInfo != null
4237 ? app.instrumentationInfo.packageName
4238 : app.info.packageName);
4239 if (app.instrumentationClass != null) {
4240 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004241 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004242 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004243 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004244 ApplicationInfo appInfo = app.instrumentationInfo != null
4245 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004246 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004247 if (profileFd != null) {
4248 profileFd = profileFd.dup();
4249 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004250 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004251 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004252 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4253 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004254 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004255 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004256 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004257 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 } catch (Exception e) {
4259 // todo: Yikes! What should we do? For now we will try to
4260 // start another process, but that could easily get us in
4261 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004262 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263
4264 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004265 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 startProcessLocked(app, "bind fail", processName);
4267 return false;
4268 }
4269
4270 // Remove this record from the list of starting applications.
4271 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004272 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4273 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 mProcessesOnHold.remove(app);
4275
4276 boolean badApp = false;
4277 boolean didSomething = false;
4278
4279 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004280 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004281 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004282 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 && processName.equals(hr.processName)) {
4284 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004285 if (mHeadless) {
4286 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4287 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 didSomething = true;
4289 }
4290 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004291 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 + hr.intent.getComponent().flattenToShortString(), e);
4293 badApp = true;
4294 }
4295 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004296 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 }
4298 }
4299
4300 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004301 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004303 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 badApp = true;
4306 }
4307 }
4308
Christopher Tatef46723b2012-01-26 14:19:24 -08004309 // Check if a next-broadcast receiver is in this process...
4310 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004312 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004314 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
4317 }
4318
Christopher Tate181fafa2009-05-14 11:12:14 -07004319 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004320 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004321 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004322 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004323 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004324 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4325 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4326 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004327 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004328 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004329 e.printStackTrace();
4330 }
4331 }
4332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 if (badApp) {
4334 // todo: Also need to kill application to deal with all
4335 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004336 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 return false;
4338 }
4339
4340 if (!didSomething) {
4341 updateOomAdjLocked();
4342 }
4343
4344 return true;
4345 }
4346
4347 public final void attachApplication(IApplicationThread thread) {
4348 synchronized (this) {
4349 int callingPid = Binder.getCallingPid();
4350 final long origId = Binder.clearCallingIdentity();
4351 attachApplicationLocked(thread, callingPid);
4352 Binder.restoreCallingIdentity(origId);
4353 }
4354 }
4355
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004356 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004358 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4359 if (stopProfiling) {
4360 synchronized (this) {
4361 if (mProfileProc == r.app) {
4362 if (mProfileFd != null) {
4363 try {
4364 mProfileFd.close();
4365 } catch (IOException e) {
4366 }
4367 clearProfilerLocked();
4368 }
4369 }
4370 }
4371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 Binder.restoreCallingIdentity(origId);
4373 }
4374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004376 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004377 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004379
4380 synchronized (this) {
4381 updateEventDispatchingLocked();
4382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 }
4384
Dianne Hackborn661cd522011-08-22 00:26:20 -07004385 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004386 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004387 mWindowManager.showBootMessage(msg, always);
4388 }
4389
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004390 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004391 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004392 final long token = Binder.clearCallingIdentity();
4393 try {
4394 synchronized (this) {
4395 if (mLockScreenShown) {
4396 mLockScreenShown = false;
4397 comeOutOfSleepIfNeededLocked();
4398 }
4399 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004400 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004401 } finally {
4402 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004403 }
4404 }
4405
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004406 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004407 IntentFilter pkgFilter = new IntentFilter();
4408 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4409 pkgFilter.addDataScheme("package");
4410 mContext.registerReceiver(new BroadcastReceiver() {
4411 @Override
4412 public void onReceive(Context context, Intent intent) {
4413 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4414 if (pkgs != null) {
4415 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004416 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004417 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4418 setResultCode(Activity.RESULT_OK);
4419 return;
4420 }
4421 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004422 }
4423 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004424 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004425 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004426
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004427 synchronized (this) {
4428 // Ensure that any processes we had put on hold are now started
4429 // up.
4430 final int NP = mProcessesOnHold.size();
4431 if (NP > 0) {
4432 ArrayList<ProcessRecord> procs =
4433 new ArrayList<ProcessRecord>(mProcessesOnHold);
4434 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004435 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4436 + procs.get(ip));
4437 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004438 }
4439 }
4440
4441 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004442 // Start looking for apps that are abusing wake locks.
4443 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004444 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004445 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004446 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004447 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004448 for (int i=0; i<mStartedUsers.size(); i++) {
4449 UserStartedState uss = mStartedUsers.valueAt(i);
4450 if (uss.mState == UserStartedState.STATE_BOOTING) {
4451 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004452 final int userId = mStartedUsers.keyAt(i);
4453 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4454 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4455 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004456 null, null, 0, null, null,
4457 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004458 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004459 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004460 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004461 }
4462 }
4463 }
4464
4465 final void ensureBootCompleted() {
4466 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004467 boolean enableScreen;
4468 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004469 booting = mBooting;
4470 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004471 enableScreen = !mBooted;
4472 mBooted = true;
4473 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004474
4475 if (booting) {
4476 finishBooting();
4477 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004478
4479 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004480 enableScreenAfterBoot();
4481 }
4482 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004483
4484 public final void activityResumed(IBinder token) {
4485 final long origId = Binder.clearCallingIdentity();
4486 mMainStack.activityResumed(token);
4487 Binder.restoreCallingIdentity(origId);
4488 }
4489
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004490 public final void activityPaused(IBinder token) {
4491 final long origId = Binder.clearCallingIdentity();
4492 mMainStack.activityPaused(token, false);
4493 Binder.restoreCallingIdentity(origId);
4494 }
4495
4496 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4497 CharSequence description) {
4498 if (localLOGV) Slog.v(
4499 TAG, "Activity stopped: token=" + token);
4500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 // Refuse possible leaked file descriptors
4502 if (icicle != null && icicle.hasFileDescriptors()) {
4503 throw new IllegalArgumentException("File descriptors passed in Bundle");
4504 }
4505
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004506 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507
4508 final long origId = Binder.clearCallingIdentity();
4509
4510 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004511 r = mMainStack.isInStackLocked(token);
4512 if (r != null) {
4513 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 }
4515 }
4516
4517 if (r != null) {
4518 sendPendingThumbnail(r, null, null, null, false);
4519 }
4520
4521 trimApplications();
4522
4523 Binder.restoreCallingIdentity(origId);
4524 }
4525
4526 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004527 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004528 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 }
4530
4531 public String getCallingPackage(IBinder token) {
4532 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004533 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004534 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 }
4536 }
4537
4538 public ComponentName getCallingActivity(IBinder token) {
4539 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004540 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 return r != null ? r.intent.getComponent() : null;
4542 }
4543 }
4544
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004545 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004546 ActivityRecord r = mMainStack.isInStackLocked(token);
4547 if (r == null) {
4548 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004550 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 }
4552
4553 public ComponentName getActivityClassForToken(IBinder token) {
4554 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004555 ActivityRecord r = mMainStack.isInStackLocked(token);
4556 if (r == null) {
4557 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004558 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004559 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 }
4561 }
4562
4563 public String getPackageForToken(IBinder token) {
4564 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004565 ActivityRecord r = mMainStack.isInStackLocked(token);
4566 if (r == null) {
4567 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004569 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 }
4571 }
4572
4573 public IIntentSender getIntentSender(int type,
4574 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004575 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004576 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004577 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004579 if (intents != null) {
4580 if (intents.length < 1) {
4581 throw new IllegalArgumentException("Intents array length must be >= 1");
4582 }
4583 for (int i=0; i<intents.length; i++) {
4584 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004585 if (intent != null) {
4586 if (intent.hasFileDescriptors()) {
4587 throw new IllegalArgumentException("File descriptors passed in Intent");
4588 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004589 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004590 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4591 throw new IllegalArgumentException(
4592 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4593 }
4594 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004595 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004596 }
4597 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004598 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004599 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004600 }
4601 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004602 if (options != null) {
4603 if (options.hasFileDescriptors()) {
4604 throw new IllegalArgumentException("File descriptors passed in options");
4605 }
4606 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 synchronized(this) {
4609 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004610 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004611 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004612 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004613 "getIntentSender", null);
4614 if (origUserId == UserHandle.USER_CURRENT) {
4615 // We don't want to evaluate this until the pending intent is
4616 // actually executed. However, we do want to always do the
4617 // security checking for it above.
4618 userId = UserHandle.USER_CURRENT;
4619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004621 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004622 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004623 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4624 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 String msg = "Permission Denial: getIntentSender() from pid="
4626 + Binder.getCallingPid()
4627 + ", uid=" + Binder.getCallingUid()
4628 + ", (need uid=" + uid + ")"
4629 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004630 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 throw new SecurityException(msg);
4632 }
4633 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004634
4635 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004636 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 } catch (RemoteException e) {
4639 throw new SecurityException(e);
4640 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004641 }
4642 }
4643
Dianne Hackborn41203752012-08-31 14:05:51 -07004644 IIntentSender getIntentSenderLocked(int type, String packageName,
4645 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004646 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4647 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004648 if (DEBUG_MU)
4649 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004650 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004651 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004652 activity = mMainStack.isInStackLocked(token);
4653 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004654 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004656 if (activity.finishing) {
4657 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004658 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004659 }
4660
4661 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4662 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4663 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4664 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4665 |PendingIntent.FLAG_UPDATE_CURRENT);
4666
4667 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4668 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004669 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004670 WeakReference<PendingIntentRecord> ref;
4671 ref = mIntentSenderRecords.get(key);
4672 PendingIntentRecord rec = ref != null ? ref.get() : null;
4673 if (rec != null) {
4674 if (!cancelCurrent) {
4675 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004676 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004677 rec.key.requestIntent.replaceExtras(intents != null ?
4678 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004679 }
4680 if (intents != null) {
4681 intents[intents.length-1] = rec.key.requestIntent;
4682 rec.key.allIntents = intents;
4683 rec.key.allResolvedTypes = resolvedTypes;
4684 } else {
4685 rec.key.allIntents = null;
4686 rec.key.allResolvedTypes = null;
4687 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 return rec;
4690 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004691 rec.canceled = true;
4692 mIntentSenderRecords.remove(key);
4693 }
4694 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 return rec;
4696 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004697 rec = new PendingIntentRecord(this, key, callingUid);
4698 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004699 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004700 if (activity.pendingResults == null) {
4701 activity.pendingResults
4702 = new HashSet<WeakReference<PendingIntentRecord>>();
4703 }
4704 activity.pendingResults.add(rec.ref);
4705 }
4706 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
4708
4709 public void cancelIntentSender(IIntentSender sender) {
4710 if (!(sender instanceof PendingIntentRecord)) {
4711 return;
4712 }
4713 synchronized(this) {
4714 PendingIntentRecord rec = (PendingIntentRecord)sender;
4715 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004716 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004717 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4718 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 String msg = "Permission Denial: cancelIntentSender() from pid="
4720 + Binder.getCallingPid()
4721 + ", uid=" + Binder.getCallingUid()
4722 + " is not allowed to cancel packges "
4723 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004724 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004725 throw new SecurityException(msg);
4726 }
4727 } catch (RemoteException e) {
4728 throw new SecurityException(e);
4729 }
4730 cancelIntentSenderLocked(rec, true);
4731 }
4732 }
4733
4734 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4735 rec.canceled = true;
4736 mIntentSenderRecords.remove(rec.key);
4737 if (cleanActivity && rec.key.activity != null) {
4738 rec.key.activity.pendingResults.remove(rec.ref);
4739 }
4740 }
4741
4742 public String getPackageForIntentSender(IIntentSender pendingResult) {
4743 if (!(pendingResult instanceof PendingIntentRecord)) {
4744 return null;
4745 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004746 try {
4747 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4748 return res.key.packageName;
4749 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 }
4751 return null;
4752 }
4753
Christopher Tatec4a07d12012-04-06 14:19:13 -07004754 public int getUidForIntentSender(IIntentSender sender) {
4755 if (sender instanceof PendingIntentRecord) {
4756 try {
4757 PendingIntentRecord res = (PendingIntentRecord)sender;
4758 return res.uid;
4759 } catch (ClassCastException e) {
4760 }
4761 }
4762 return -1;
4763 }
4764
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004765 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4766 if (!(pendingResult instanceof PendingIntentRecord)) {
4767 return false;
4768 }
4769 try {
4770 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4771 if (res.key.allIntents == null) {
4772 return false;
4773 }
4774 for (int i=0; i<res.key.allIntents.length; i++) {
4775 Intent intent = res.key.allIntents[i];
4776 if (intent.getPackage() != null && intent.getComponent() != null) {
4777 return false;
4778 }
4779 }
4780 return true;
4781 } catch (ClassCastException e) {
4782 }
4783 return false;
4784 }
4785
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004786 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4787 if (!(pendingResult instanceof PendingIntentRecord)) {
4788 return false;
4789 }
4790 try {
4791 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4792 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4793 return true;
4794 }
4795 return false;
4796 } catch (ClassCastException e) {
4797 }
4798 return false;
4799 }
4800
Dianne Hackborn81038902012-11-26 17:04:09 -08004801 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4802 if (!(pendingResult instanceof PendingIntentRecord)) {
4803 return null;
4804 }
4805 try {
4806 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4807 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4808 } catch (ClassCastException e) {
4809 }
4810 return null;
4811 }
4812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 public void setProcessLimit(int max) {
4814 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4815 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004816 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004817 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004818 mProcessLimitOverride = max;
4819 }
4820 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004821 }
4822
4823 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004824 synchronized (this) {
4825 return mProcessLimitOverride;
4826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 }
4828
4829 void foregroundTokenDied(ForegroundToken token) {
4830 synchronized (ActivityManagerService.this) {
4831 synchronized (mPidsSelfLocked) {
4832 ForegroundToken cur
4833 = mForegroundProcesses.get(token.pid);
4834 if (cur != token) {
4835 return;
4836 }
4837 mForegroundProcesses.remove(token.pid);
4838 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4839 if (pr == null) {
4840 return;
4841 }
4842 pr.forcingToForeground = null;
4843 pr.foregroundServices = false;
4844 }
4845 updateOomAdjLocked();
4846 }
4847 }
4848
4849 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4850 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4851 "setProcessForeground()");
4852 synchronized(this) {
4853 boolean changed = false;
4854
4855 synchronized (mPidsSelfLocked) {
4856 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004857 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004858 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004859 return;
4860 }
4861 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4862 if (oldToken != null) {
4863 oldToken.token.unlinkToDeath(oldToken, 0);
4864 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004865 if (pr != null) {
4866 pr.forcingToForeground = null;
4867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 changed = true;
4869 }
4870 if (isForeground && token != null) {
4871 ForegroundToken newToken = new ForegroundToken() {
4872 public void binderDied() {
4873 foregroundTokenDied(this);
4874 }
4875 };
4876 newToken.pid = pid;
4877 newToken.token = token;
4878 try {
4879 token.linkToDeath(newToken, 0);
4880 mForegroundProcesses.put(pid, newToken);
4881 pr.forcingToForeground = token;
4882 changed = true;
4883 } catch (RemoteException e) {
4884 // If the process died while doing this, we will later
4885 // do the cleanup with the process death link.
4886 }
4887 }
4888 }
4889
4890 if (changed) {
4891 updateOomAdjLocked();
4892 }
4893 }
4894 }
4895
4896 // =========================================================
4897 // PERMISSIONS
4898 // =========================================================
4899
4900 static class PermissionController extends IPermissionController.Stub {
4901 ActivityManagerService mActivityManagerService;
4902 PermissionController(ActivityManagerService activityManagerService) {
4903 mActivityManagerService = activityManagerService;
4904 }
4905
4906 public boolean checkPermission(String permission, int pid, int uid) {
4907 return mActivityManagerService.checkPermission(permission, pid,
4908 uid) == PackageManager.PERMISSION_GRANTED;
4909 }
4910 }
4911
4912 /**
4913 * This can be called with or without the global lock held.
4914 */
4915 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004916 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917 // We might be performing an operation on behalf of an indirect binder
4918 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4919 // client identity accordingly before proceeding.
4920 Identity tlsIdentity = sCallerIdentity.get();
4921 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004922 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4924 uid = tlsIdentity.uid;
4925 pid = tlsIdentity.pid;
4926 }
4927
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004928 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 return PackageManager.PERMISSION_GRANTED;
4930 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004931
4932 return ActivityManager.checkComponentPermission(permission, uid,
4933 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004934 }
4935
4936 /**
4937 * As the only public entry point for permissions checking, this method
4938 * can enforce the semantic that requesting a check on a null global
4939 * permission is automatically denied. (Internally a null permission
4940 * string is used when calling {@link #checkComponentPermission} in cases
4941 * when only uid-based security is needed.)
4942 *
4943 * This can be called with or without the global lock held.
4944 */
4945 public int checkPermission(String permission, int pid, int uid) {
4946 if (permission == null) {
4947 return PackageManager.PERMISSION_DENIED;
4948 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004949 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004950 }
4951
4952 /**
4953 * Binder IPC calls go through the public entry point.
4954 * This can be called with or without the global lock held.
4955 */
4956 int checkCallingPermission(String permission) {
4957 return checkPermission(permission,
4958 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004959 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961
4962 /**
4963 * This can be called with or without the global lock held.
4964 */
4965 void enforceCallingPermission(String permission, String func) {
4966 if (checkCallingPermission(permission)
4967 == PackageManager.PERMISSION_GRANTED) {
4968 return;
4969 }
4970
4971 String msg = "Permission Denial: " + func + " from pid="
4972 + Binder.getCallingPid()
4973 + ", uid=" + Binder.getCallingUid()
4974 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004975 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 throw new SecurityException(msg);
4977 }
4978
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004979 /**
4980 * Determine if UID is holding permissions required to access {@link Uri} in
4981 * the given {@link ProviderInfo}. Final permission checking is always done
4982 * in {@link ContentProvider}.
4983 */
4984 private final boolean checkHoldingPermissionsLocked(
4985 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004986 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4987 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004988
4989 if (pi.applicationInfo.uid == uid) {
4990 return true;
4991 } else if (!pi.exported) {
4992 return false;
4993 }
4994
4995 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4996 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004998 // check if target holds top-level <provider> permissions
4999 if (!readMet && pi.readPermission != null
5000 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
5001 readMet = true;
5002 }
5003 if (!writeMet && pi.writePermission != null
5004 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
5005 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005006 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005007
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005008 // track if unprotected read/write is allowed; any denied
5009 // <path-permission> below removes this ability
5010 boolean allowDefaultRead = pi.readPermission == null;
5011 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07005012
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005013 // check if target holds any <path-permission> that match uri
5014 final PathPermission[] pps = pi.pathPermissions;
5015 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005016 final String path = uri.getPath();
5017 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005018 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005019 i--;
5020 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005021 if (pp.match(path)) {
5022 if (!readMet) {
5023 final String pprperm = pp.getReadPermission();
5024 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5025 + pprperm + " for " + pp.getPath()
5026 + ": match=" + pp.match(path)
5027 + " check=" + pm.checkUidPermission(pprperm, uid));
5028 if (pprperm != null) {
5029 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5030 readMet = true;
5031 } else {
5032 allowDefaultRead = false;
5033 }
5034 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005035 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005036 if (!writeMet) {
5037 final String ppwperm = pp.getWritePermission();
5038 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5039 + ppwperm + " for " + pp.getPath()
5040 + ": match=" + pp.match(path)
5041 + " check=" + pm.checkUidPermission(ppwperm, uid));
5042 if (ppwperm != null) {
5043 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5044 writeMet = true;
5045 } else {
5046 allowDefaultWrite = false;
5047 }
5048 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005049 }
5050 }
5051 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005052 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005053
5054 // grant unprotected <provider> read/write, if not blocked by
5055 // <path-permission> above
5056 if (allowDefaultRead) readMet = true;
5057 if (allowDefaultWrite) writeMet = true;
5058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 } catch (RemoteException e) {
5060 return false;
5061 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005062
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005063 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 }
5065
5066 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5067 int modeFlags) {
5068 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005069 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 return true;
5071 }
5072 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5073 if (perms == null) return false;
5074 UriPermission perm = perms.get(uri);
5075 if (perm == null) return false;
5076 return (modeFlags&perm.modeFlags) == modeFlags;
5077 }
5078
5079 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005080 enforceNotIsolatedCaller("checkUriPermission");
5081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 // Another redirected-binder-call permissions check as in
5083 // {@link checkComponentPermission}.
5084 Identity tlsIdentity = sCallerIdentity.get();
5085 if (tlsIdentity != null) {
5086 uid = tlsIdentity.uid;
5087 pid = tlsIdentity.pid;
5088 }
5089
5090 // Our own process gets to do everything.
5091 if (pid == MY_PID) {
5092 return PackageManager.PERMISSION_GRANTED;
5093 }
5094 synchronized(this) {
5095 return checkUriPermissionLocked(uri, uid, modeFlags)
5096 ? PackageManager.PERMISSION_GRANTED
5097 : PackageManager.PERMISSION_DENIED;
5098 }
5099 }
5100
Dianne Hackborn39792d22010-08-19 18:01:52 -07005101 /**
5102 * Check if the targetPkg can be granted permission to access uri by
5103 * the callingUid using the given modeFlags. Throws a security exception
5104 * if callingUid is not allowed to do this. Returns the uid of the target
5105 * if the URI permission grant should be performed; returns -1 if it is not
5106 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005107 * If you already know the uid of the target, you can supply it in
5108 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005109 */
5110 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005111 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5113 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5114 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005115 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 }
5117
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005118 if (targetPkg != null) {
5119 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5120 "Checking grant " + targetPkg + " permission to " + uri);
5121 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005122
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005123 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124
5125 // If this is not a content: uri, we can't do anything with it.
5126 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005127 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005128 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005129 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 }
5131
5132 String name = uri.getAuthority();
5133 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005134 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005135 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 if (cpr != null) {
5137 pi = cpr.info;
5138 } else {
5139 try {
5140 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005141 PackageManager.GET_URI_PERMISSION_PATTERNS,
5142 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 } catch (RemoteException ex) {
5144 }
5145 }
5146 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005147 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005148 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 }
5150
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005151 int targetUid = lastTargetUid;
5152 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005153 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005154 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005155 if (targetUid < 0) {
5156 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5157 "Can't grant URI permission no uid for: " + targetPkg);
5158 return -1;
5159 }
5160 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005161 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 }
5164
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005165 if (targetUid >= 0) {
5166 // First... does the target actually need this permission?
5167 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5168 // No need to grant the target this permission.
5169 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5170 "Target " + targetPkg + " already has full permission to " + uri);
5171 return -1;
5172 }
5173 } else {
5174 // First... there is no target package, so can anyone access it?
5175 boolean allowed = pi.exported;
5176 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5177 if (pi.readPermission != null) {
5178 allowed = false;
5179 }
5180 }
5181 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5182 if (pi.writePermission != null) {
5183 allowed = false;
5184 }
5185 }
5186 if (allowed) {
5187 return -1;
5188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005189 }
5190
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005191 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 if (!pi.grantUriPermissions) {
5193 throw new SecurityException("Provider " + pi.packageName
5194 + "/" + pi.name
5195 + " does not allow granting of Uri permissions (uri "
5196 + uri + ")");
5197 }
5198 if (pi.uriPermissionPatterns != null) {
5199 final int N = pi.uriPermissionPatterns.length;
5200 boolean allowed = false;
5201 for (int i=0; i<N; i++) {
5202 if (pi.uriPermissionPatterns[i] != null
5203 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5204 allowed = true;
5205 break;
5206 }
5207 }
5208 if (!allowed) {
5209 throw new SecurityException("Provider " + pi.packageName
5210 + "/" + pi.name
5211 + " does not allow granting of permission to path of Uri "
5212 + uri);
5213 }
5214 }
5215
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005216 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005218 if (callingUid != Process.myUid()) {
5219 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5220 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5221 throw new SecurityException("Uid " + callingUid
5222 + " does not have permission to uri " + uri);
5223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 }
5225 }
5226
Dianne Hackborn39792d22010-08-19 18:01:52 -07005227 return targetUid;
5228 }
5229
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005230 public int checkGrantUriPermission(int callingUid, String targetPkg,
5231 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005232 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005233 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005234 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005235 }
5236 }
5237
Dianne Hackborn39792d22010-08-19 18:01:52 -07005238 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5239 Uri uri, int modeFlags, UriPermissionOwner owner) {
5240 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5241 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5242 if (modeFlags == 0) {
5243 return;
5244 }
5245
5246 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005247 // to the uri, and the target doesn't. Let's now give this to
5248 // the target.
5249
Joe Onorato8a9b2202010-02-26 18:56:32 -08005250 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005251 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253 HashMap<Uri, UriPermission> targetUris
5254 = mGrantedUriPermissions.get(targetUid);
5255 if (targetUris == null) {
5256 targetUris = new HashMap<Uri, UriPermission>();
5257 mGrantedUriPermissions.put(targetUid, targetUris);
5258 }
5259
5260 UriPermission perm = targetUris.get(uri);
5261 if (perm == null) {
5262 perm = new UriPermission(targetUid, uri);
5263 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005267 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005269 } else {
5270 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5271 perm.readOwners.add(owner);
5272 owner.addReadPermission(perm);
5273 }
5274 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5275 perm.writeOwners.add(owner);
5276 owner.addWritePermission(perm);
5277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 }
5279 }
5280
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005281 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5282 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005283 if (targetPkg == null) {
5284 throw new NullPointerException("targetPkg");
5285 }
5286
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005287 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005288 if (targetUid < 0) {
5289 return;
5290 }
5291
5292 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5293 }
5294
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005295 static class NeededUriGrants extends ArrayList<Uri> {
5296 final String targetPkg;
5297 final int targetUid;
5298 final int flags;
5299
5300 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5301 targetPkg = _targetPkg;
5302 targetUid = _targetUid;
5303 flags = _flags;
5304 }
5305 }
5306
Dianne Hackborn39792d22010-08-19 18:01:52 -07005307 /**
5308 * Like checkGrantUriPermissionLocked, but takes an Intent.
5309 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005310 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5311 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005312 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005313 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5314 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005315 + " from " + intent + "; flags=0x"
5316 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5317
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005318 if (targetPkg == null) {
5319 throw new NullPointerException("targetPkg");
5320 }
5321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005323 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 }
5325 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005326 ClipData clip = intent.getClipData();
5327 if (data == null && clip == null) {
5328 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005329 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005330 if (data != null) {
5331 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5332 mode, needed != null ? needed.targetUid : -1);
5333 if (target > 0) {
5334 if (needed == null) {
5335 needed = new NeededUriGrants(targetPkg, target, mode);
5336 }
5337 needed.add(data);
5338 }
5339 }
5340 if (clip != null) {
5341 for (int i=0; i<clip.getItemCount(); i++) {
5342 Uri uri = clip.getItemAt(i).getUri();
5343 if (uri != null) {
5344 int target = -1;
5345 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5346 mode, needed != null ? needed.targetUid : -1);
5347 if (target > 0) {
5348 if (needed == null) {
5349 needed = new NeededUriGrants(targetPkg, target, mode);
5350 }
5351 needed.add(uri);
5352 }
5353 } else {
5354 Intent clipIntent = clip.getItemAt(i).getIntent();
5355 if (clipIntent != null) {
5356 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5357 callingUid, targetPkg, clipIntent, mode, needed);
5358 if (newNeeded != null) {
5359 needed = newNeeded;
5360 }
5361 }
5362 }
5363 }
5364 }
5365
5366 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005367 }
5368
5369 /**
5370 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5371 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005372 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5373 UriPermissionOwner owner) {
5374 if (needed != null) {
5375 for (int i=0; i<needed.size(); i++) {
5376 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5377 needed.get(i), needed.flags, owner);
5378 }
5379 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005380 }
5381
5382 void grantUriPermissionFromIntentLocked(int callingUid,
5383 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005384 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005385 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005386 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 return;
5388 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005389
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005390 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 }
5392
5393 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5394 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005395 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396 synchronized(this) {
5397 final ProcessRecord r = getRecordForAppLocked(caller);
5398 if (r == null) {
5399 throw new SecurityException("Unable to find app for caller "
5400 + caller
5401 + " when granting permission to uri " + uri);
5402 }
5403 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005404 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 }
5406 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005407 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 }
5409
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005410 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 null);
5412 }
5413 }
5414
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005415 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5417 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5418 HashMap<Uri, UriPermission> perms
5419 = mGrantedUriPermissions.get(perm.uid);
5420 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005421 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005422 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 perms.remove(perm.uri);
5424 if (perms.size() == 0) {
5425 mGrantedUriPermissions.remove(perm.uid);
5426 }
5427 }
5428 }
5429 }
5430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5432 int modeFlags) {
5433 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5434 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5435 if (modeFlags == 0) {
5436 return;
5437 }
5438
Joe Onorato8a9b2202010-02-26 18:56:32 -08005439 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005440 "Revoking all granted permissions to " + uri);
5441
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005442 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443
5444 final String authority = uri.getAuthority();
5445 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005446 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005447 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 if (cpr != null) {
5449 pi = cpr.info;
5450 } else {
5451 try {
5452 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005453 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 } catch (RemoteException ex) {
5455 }
5456 }
5457 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005458 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 return;
5460 }
5461
5462 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005463 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 // Right now, if you are not the original owner of the permission,
5465 // you are not allowed to revoke it.
5466 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5467 throw new SecurityException("Uid " + callingUid
5468 + " does not have permission to uri " + uri);
5469 //}
5470 }
5471
5472 // Go through all of the permissions and remove any that match.
5473 final List<String> SEGMENTS = uri.getPathSegments();
5474 if (SEGMENTS != null) {
5475 final int NS = SEGMENTS.size();
5476 int N = mGrantedUriPermissions.size();
5477 for (int i=0; i<N; i++) {
5478 HashMap<Uri, UriPermission> perms
5479 = mGrantedUriPermissions.valueAt(i);
5480 Iterator<UriPermission> it = perms.values().iterator();
5481 toploop:
5482 while (it.hasNext()) {
5483 UriPermission perm = it.next();
5484 Uri targetUri = perm.uri;
5485 if (!authority.equals(targetUri.getAuthority())) {
5486 continue;
5487 }
5488 List<String> targetSegments = targetUri.getPathSegments();
5489 if (targetSegments == null) {
5490 continue;
5491 }
5492 if (targetSegments.size() < NS) {
5493 continue;
5494 }
5495 for (int j=0; j<NS; j++) {
5496 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5497 continue toploop;
5498 }
5499 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005500 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005501 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 perm.clearModes(modeFlags);
5503 if (perm.modeFlags == 0) {
5504 it.remove();
5505 }
5506 }
5507 if (perms.size() == 0) {
5508 mGrantedUriPermissions.remove(
5509 mGrantedUriPermissions.keyAt(i));
5510 N--;
5511 i--;
5512 }
5513 }
5514 }
5515 }
5516
5517 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5518 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005519 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 synchronized(this) {
5521 final ProcessRecord r = getRecordForAppLocked(caller);
5522 if (r == null) {
5523 throw new SecurityException("Unable to find app for caller "
5524 + caller
5525 + " when revoking permission to uri " + uri);
5526 }
5527 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005528 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 return;
5530 }
5531
5532 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5533 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5534 if (modeFlags == 0) {
5535 return;
5536 }
5537
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005538 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539
5540 final String authority = uri.getAuthority();
5541 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005542 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 if (cpr != null) {
5544 pi = cpr.info;
5545 } else {
5546 try {
5547 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005548 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 } catch (RemoteException ex) {
5550 }
5551 }
5552 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005553 Slog.w(TAG, "No content provider found for permission revoke: "
5554 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555 return;
5556 }
5557
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005558 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 }
5560 }
5561
Dianne Hackborn7e269642010-08-25 19:50:20 -07005562 @Override
5563 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005564 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005565 synchronized(this) {
5566 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5567 return owner.getExternalTokenLocked();
5568 }
5569 }
5570
5571 @Override
5572 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5573 Uri uri, int modeFlags) {
5574 synchronized(this) {
5575 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5576 if (owner == null) {
5577 throw new IllegalArgumentException("Unknown owner: " + token);
5578 }
5579 if (fromUid != Binder.getCallingUid()) {
5580 if (Binder.getCallingUid() != Process.myUid()) {
5581 // Only system code can grant URI permissions on behalf
5582 // of other users.
5583 throw new SecurityException("nice try");
5584 }
5585 }
5586 if (targetPkg == null) {
5587 throw new IllegalArgumentException("null target");
5588 }
5589 if (uri == null) {
5590 throw new IllegalArgumentException("null uri");
5591 }
5592
5593 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5594 }
5595 }
5596
5597 @Override
5598 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5599 synchronized(this) {
5600 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5601 if (owner == null) {
5602 throw new IllegalArgumentException("Unknown owner: " + token);
5603 }
5604
5605 if (uri == null) {
5606 owner.removeUriPermissionsLocked(mode);
5607 } else {
5608 owner.removeUriPermissionLocked(uri, mode);
5609 }
5610 }
5611 }
5612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5614 synchronized (this) {
5615 ProcessRecord app =
5616 who != null ? getRecordForAppLocked(who) : null;
5617 if (app == null) return;
5618
5619 Message msg = Message.obtain();
5620 msg.what = WAIT_FOR_DEBUGGER_MSG;
5621 msg.obj = app;
5622 msg.arg1 = waiting ? 1 : 0;
5623 mHandler.sendMessage(msg);
5624 }
5625 }
5626
5627 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005628 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5629 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005631 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005632 outInfo.threshold = homeAppMem;
5633 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5634 outInfo.hiddenAppThreshold = hiddenAppMem;
5635 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005636 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005637 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5638 ProcessList.VISIBLE_APP_ADJ);
5639 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5640 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 }
5642
5643 // =========================================================
5644 // TASK MANAGEMENT
5645 // =========================================================
5646
5647 public List getTasks(int maxNum, int flags,
5648 IThumbnailReceiver receiver) {
5649 ArrayList list = new ArrayList();
5650
5651 PendingThumbnailsRecord pending = null;
5652 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005653 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654
5655 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005656 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5658 + ", receiver=" + receiver);
5659
5660 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5661 != PackageManager.PERMISSION_GRANTED) {
5662 if (receiver != null) {
5663 // If the caller wants to wait for pending thumbnails,
5664 // it ain't gonna get them.
5665 try {
5666 receiver.finished();
5667 } catch (RemoteException ex) {
5668 }
5669 }
5670 String msg = "Permission Denial: getTasks() from pid="
5671 + Binder.getCallingPid()
5672 + ", uid=" + Binder.getCallingUid()
5673 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005674 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 throw new SecurityException(msg);
5676 }
5677
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005678 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005679 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005680 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005681 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 TaskRecord curTask = null;
5683 int numActivities = 0;
5684 int numRunning = 0;
5685 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005686 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005688 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689
5690 // Initialize state for next task if needed.
5691 if (top == null ||
5692 (top.state == ActivityState.INITIALIZING
5693 && top.task == r.task)) {
5694 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 curTask = r.task;
5696 numActivities = numRunning = 0;
5697 }
5698
5699 // Add 'r' into the current task.
5700 numActivities++;
5701 if (r.app != null && r.app.thread != null) {
5702 numRunning++;
5703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704
Joe Onorato8a9b2202010-02-26 18:56:32 -08005705 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 TAG, r.intent.getComponent().flattenToShortString()
5707 + ": task=" + r.task);
5708
5709 // If the next one is a different task, generate a new
5710 // TaskInfo entry for what we have.
5711 if (next == null || next.task != curTask) {
5712 ActivityManager.RunningTaskInfo ci
5713 = new ActivityManager.RunningTaskInfo();
5714 ci.id = curTask.taskId;
5715 ci.baseActivity = r.intent.getComponent();
5716 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005717 if (top.thumbHolder != null) {
5718 ci.description = top.thumbHolder.lastDescription;
5719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 ci.numActivities = numActivities;
5721 ci.numRunning = numRunning;
5722 //System.out.println(
5723 // "#" + maxNum + ": " + " descr=" + ci.description);
5724 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005725 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 TAG, "State=" + top.state + "Idle=" + top.idle
5727 + " app=" + top.app
5728 + " thr=" + (top.app != null ? top.app.thread : null));
5729 if (top.state == ActivityState.RESUMED
5730 || top.state == ActivityState.PAUSING) {
5731 if (top.idle && top.app != null
5732 && top.app.thread != null) {
5733 topRecord = top;
5734 topThumbnail = top.app.thread;
5735 } else {
5736 top.thumbnailNeeded = true;
5737 }
5738 }
5739 if (pending == null) {
5740 pending = new PendingThumbnailsRecord(receiver);
5741 }
5742 pending.pendingRecords.add(top);
5743 }
5744 list.add(ci);
5745 maxNum--;
5746 top = null;
5747 }
5748 }
5749
5750 if (pending != null) {
5751 mPendingThumbnails.add(pending);
5752 }
5753 }
5754
Joe Onorato8a9b2202010-02-26 18:56:32 -08005755 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756
5757 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005758 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005760 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005762 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005763 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005764 }
5765 }
5766
5767 if (pending == null && receiver != null) {
5768 // In this case all thumbnails were available and the client
5769 // is being asked to be told when the remaining ones come in...
5770 // which is unusually, since the top-most currently running
5771 // activity should never have a canned thumbnail! Oh well.
5772 try {
5773 receiver.finished();
5774 } catch (RemoteException ex) {
5775 }
5776 }
5777
5778 return list;
5779 }
5780
5781 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005782 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005783 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5784 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 synchronized (this) {
5787 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5788 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005789 final boolean detailed = checkCallingPermission(
5790 android.Manifest.permission.GET_DETAILED_TASKS)
5791 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005793 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 final int N = mRecentTasks.size();
5796 ArrayList<ActivityManager.RecentTaskInfo> res
5797 = new ArrayList<ActivityManager.RecentTaskInfo>(
5798 maxNum < N ? maxNum : N);
5799 for (int i=0; i<N && maxNum > 0; i++) {
5800 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005801 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005802 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005803 // Return the entry if desired by the caller. We always return
5804 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005805 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005806 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5807 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005808
Dianne Hackborn905577f2011-09-07 18:31:28 -07005809 if (i == 0
5810 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 || (tr.intent == null)
5812 || ((tr.intent.getFlags()
5813 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5814 ActivityManager.RecentTaskInfo rti
5815 = new ActivityManager.RecentTaskInfo();
5816 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005817 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 rti.baseIntent = new Intent(
5819 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005820 if (!detailed) {
5821 rti.baseIntent.replaceExtras((Bundle)null);
5822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005824 rti.description = tr.lastDescription;
5825
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005826 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5827 // Check whether this activity is currently available.
5828 try {
5829 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005830 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005831 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005832 continue;
5833 }
5834 } else if (rti.baseIntent != null) {
5835 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005836 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005837 continue;
5838 }
5839 }
5840 } catch (RemoteException e) {
5841 // Will never happen.
5842 }
5843 }
5844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 res.add(rti);
5846 maxNum--;
5847 }
5848 }
5849 return res;
5850 }
5851 }
5852
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005853 private TaskRecord taskForIdLocked(int id) {
5854 final int N = mRecentTasks.size();
5855 for (int i=0; i<N; i++) {
5856 TaskRecord tr = mRecentTasks.get(i);
5857 if (tr.taskId == id) {
5858 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005859 }
5860 }
5861 return null;
5862 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005863
5864 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5865 synchronized (this) {
5866 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5867 "getTaskThumbnails()");
5868 TaskRecord tr = taskForIdLocked(id);
5869 if (tr != null) {
5870 return mMainStack.getTaskThumbnailsLocked(tr);
5871 }
5872 }
5873 return null;
5874 }
5875
Dianne Hackborn15491c62012-09-19 10:59:14 -07005876 public Bitmap getTaskTopThumbnail(int id) {
5877 synchronized (this) {
5878 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5879 "getTaskTopThumbnail()");
5880 TaskRecord tr = taskForIdLocked(id);
5881 if (tr != null) {
5882 return mMainStack.getTaskTopThumbnailLocked(tr);
5883 }
5884 }
5885 return null;
5886 }
5887
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005888 public boolean removeSubTask(int taskId, int subTaskIndex) {
5889 synchronized (this) {
5890 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5891 "removeSubTask()");
5892 long ident = Binder.clearCallingIdentity();
5893 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005894 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5895 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005896 } finally {
5897 Binder.restoreCallingIdentity(ident);
5898 }
5899 }
5900 }
5901
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005902 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5903 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005904 Intent baseIntent = new Intent(
5905 tr.intent != null ? tr.intent : tr.affinityIntent);
5906 ComponentName component = baseIntent.getComponent();
5907 if (component == null) {
5908 Slog.w(TAG, "Now component for base intent of task: " + tr);
5909 return;
5910 }
5911
5912 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005913 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005914
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005915 if (killProcesses) {
5916 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005917 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005918 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005919 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5920 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5921 for (int i=0; i<uids.size(); i++) {
5922 ProcessRecord proc = uids.valueAt(i);
5923 if (proc.userId != tr.userId) {
5924 continue;
5925 }
5926 if (!proc.pkgList.contains(pkg)) {
5927 continue;
5928 }
5929 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005930 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005931 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005932
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005933 // Kill the running processes.
5934 for (int i=0; i<procs.size(); i++) {
5935 ProcessRecord pr = procs.get(i);
5936 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5937 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005938 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005939 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005940 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005941 Process.killProcessQuiet(pr.pid);
5942 } else {
5943 pr.waitingToKill = "remove task";
5944 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005945 }
5946 }
5947 }
5948
5949 public boolean removeTask(int taskId, int flags) {
5950 synchronized (this) {
5951 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5952 "removeTask()");
5953 long ident = Binder.clearCallingIdentity();
5954 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005955 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5956 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005957 if (r != null) {
5958 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005959 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005960 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005961 } else {
5962 TaskRecord tr = null;
5963 int i=0;
5964 while (i < mRecentTasks.size()) {
5965 TaskRecord t = mRecentTasks.get(i);
5966 if (t.taskId == taskId) {
5967 tr = t;
5968 break;
5969 }
5970 i++;
5971 }
5972 if (tr != null) {
5973 if (tr.numActivities <= 0) {
5974 // Caller is just removing a recent task that is
5975 // not actively running. That is easy!
5976 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005977 cleanUpRemovedTaskLocked(tr, flags);
5978 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005979 } else {
5980 Slog.w(TAG, "removeTask: task " + taskId
5981 + " does not have activities to remove, "
5982 + " but numActivities=" + tr.numActivities
5983 + ": " + tr);
5984 }
5985 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005986 }
5987 } finally {
5988 Binder.restoreCallingIdentity(ident);
5989 }
5990 }
5991 return false;
5992 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5995 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005996 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 TaskRecord jt = startTask;
5998
5999 // First look backwards
6000 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006001 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 if (r.task != jt) {
6003 jt = r.task;
6004 if (affinity.equals(jt.affinity)) {
6005 return j;
6006 }
6007 }
6008 }
6009
6010 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006011 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 jt = startTask;
6013 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006014 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 if (r.task != jt) {
6016 if (affinity.equals(jt.affinity)) {
6017 return j;
6018 }
6019 jt = r.task;
6020 }
6021 }
6022
6023 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006024 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 return N-1;
6026 }
6027
6028 return -1;
6029 }
6030
6031 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006032 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006034 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6036 "moveTaskToFront()");
6037
6038 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006039 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6040 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006041 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006042 return;
6043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 final long origId = Binder.clearCallingIdentity();
6045 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006046 TaskRecord tr = taskForIdLocked(task);
6047 if (tr != null) {
6048 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6049 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006051 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6052 // Caller wants the home activity moved with it. To accomplish this,
6053 // we'll just move the home task to the top first.
6054 mMainStack.moveHomeToFrontLocked();
6055 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006056 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006057 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006059 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6060 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006062 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6063 mMainStack.mUserLeaving = true;
6064 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006065 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6066 // Caller wants the home activity moved with it. To accomplish this,
6067 // we'll just move the home task to the top first.
6068 mMainStack.moveHomeToFrontLocked();
6069 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006070 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 return;
6072 }
6073 }
6074 } finally {
6075 Binder.restoreCallingIdentity(origId);
6076 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006077 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 }
6079 }
6080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 public void moveTaskToBack(int task) {
6082 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6083 "moveTaskToBack()");
6084
6085 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006086 if (mMainStack.mResumedActivity != null
6087 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006088 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6089 Binder.getCallingUid(), "Task to back")) {
6090 return;
6091 }
6092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006094 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 Binder.restoreCallingIdentity(origId);
6096 }
6097 }
6098
6099 /**
6100 * Moves an activity, and all of the other activities within the same task, to the bottom
6101 * of the history stack. The activity's order within the task is unchanged.
6102 *
6103 * @param token A reference to the activity we wish to move
6104 * @param nonRoot If false then this only works if the activity is the root
6105 * of a task; if true it will work for any activity in a task.
6106 * @return Returns true if the move completed, false if not.
6107 */
6108 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006109 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 synchronized(this) {
6111 final long origId = Binder.clearCallingIdentity();
6112 int taskId = getTaskForActivityLocked(token, !nonRoot);
6113 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006114 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 }
6116 Binder.restoreCallingIdentity(origId);
6117 }
6118 return false;
6119 }
6120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 public void moveTaskBackwards(int task) {
6122 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6123 "moveTaskBackwards()");
6124
6125 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006126 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6127 Binder.getCallingUid(), "Task backwards")) {
6128 return;
6129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 final long origId = Binder.clearCallingIdentity();
6131 moveTaskBackwardsLocked(task);
6132 Binder.restoreCallingIdentity(origId);
6133 }
6134 }
6135
6136 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006137 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 }
6139
6140 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6141 synchronized(this) {
6142 return getTaskForActivityLocked(token, onlyRoot);
6143 }
6144 }
6145
6146 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006147 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 TaskRecord lastTask = null;
6149 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006150 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006151 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 if (!onlyRoot || lastTask != r.task) {
6153 return r.task.taskId;
6154 }
6155 return -1;
6156 }
6157 lastTask = r.task;
6158 }
6159
6160 return -1;
6161 }
6162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 // =========================================================
6164 // THUMBNAILS
6165 // =========================================================
6166
6167 public void reportThumbnail(IBinder token,
6168 Bitmap thumbnail, CharSequence description) {
6169 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6170 final long origId = Binder.clearCallingIdentity();
6171 sendPendingThumbnail(null, token, thumbnail, description, true);
6172 Binder.restoreCallingIdentity(origId);
6173 }
6174
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006175 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 Bitmap thumbnail, CharSequence description, boolean always) {
6177 TaskRecord task = null;
6178 ArrayList receivers = null;
6179
6180 //System.out.println("Send pending thumbnail: " + r);
6181
6182 synchronized(this) {
6183 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006184 r = mMainStack.isInStackLocked(token);
6185 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 return;
6187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006189 if (thumbnail == null && r.thumbHolder != null) {
6190 thumbnail = r.thumbHolder.lastThumbnail;
6191 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 }
6193 if (thumbnail == null && !always) {
6194 // If there is no thumbnail, and this entry is not actually
6195 // going away, then abort for now and pick up the next
6196 // thumbnail we get.
6197 return;
6198 }
6199 task = r.task;
6200
6201 int N = mPendingThumbnails.size();
6202 int i=0;
6203 while (i<N) {
6204 PendingThumbnailsRecord pr =
6205 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6206 //System.out.println("Looking in " + pr.pendingRecords);
6207 if (pr.pendingRecords.remove(r)) {
6208 if (receivers == null) {
6209 receivers = new ArrayList();
6210 }
6211 receivers.add(pr);
6212 if (pr.pendingRecords.size() == 0) {
6213 pr.finished = true;
6214 mPendingThumbnails.remove(i);
6215 N--;
6216 continue;
6217 }
6218 }
6219 i++;
6220 }
6221 }
6222
6223 if (receivers != null) {
6224 final int N = receivers.size();
6225 for (int i=0; i<N; i++) {
6226 try {
6227 PendingThumbnailsRecord pr =
6228 (PendingThumbnailsRecord)receivers.get(i);
6229 pr.receiver.newThumbnail(
6230 task != null ? task.taskId : -1, thumbnail, description);
6231 if (pr.finished) {
6232 pr.receiver.finished();
6233 }
6234 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006235 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 }
6237 }
6238 }
6239 }
6240
6241 // =========================================================
6242 // CONTENT PROVIDERS
6243 // =========================================================
6244
Jeff Brown10e89712011-07-08 18:52:57 -07006245 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6246 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006248 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006249 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006250 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 } catch (RemoteException ex) {
6252 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006253 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006254 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6255 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006257 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 for (int i=0; i<N; i++) {
6259 ProviderInfo cpi =
6260 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006261 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6262 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006263 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006264 // This is a singleton provider, but a user besides the
6265 // default user is asking to initialize a process it runs
6266 // in... well, no, it doesn't actually run in this process,
6267 // it runs in the process of the default user. Get rid of it.
6268 providers.remove(i);
6269 N--;
Jun Succa09652013-05-21 17:24:32 +08006270 i--;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006271 continue;
6272 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006273
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006274 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006275 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006277 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006278 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006280 if (DEBUG_MU)
6281 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 app.pubProviders.put(cpi.name, cpr);
6283 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006284 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 }
6286 }
6287 return providers;
6288 }
6289
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006290 /**
6291 * Check if {@link ProcessRecord} has a possible chance at accessing the
6292 * given {@link ProviderInfo}. Final permission checking is always done
6293 * in {@link ContentProvider}.
6294 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006296 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006298 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006300 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006301 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 return null;
6303 }
6304 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006305 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 == PackageManager.PERMISSION_GRANTED) {
6307 return null;
6308 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006309
6310 PathPermission[] pps = cpi.pathPermissions;
6311 if (pps != null) {
6312 int i = pps.length;
6313 while (i > 0) {
6314 i--;
6315 PathPermission pp = pps[i];
6316 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006317 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006318 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006319 return null;
6320 }
6321 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006322 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006323 == PackageManager.PERMISSION_GRANTED) {
6324 return null;
6325 }
6326 }
6327 }
6328
Dianne Hackbornb424b632010-08-18 15:59:05 -07006329 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6330 if (perms != null) {
6331 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6332 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6333 return null;
6334 }
6335 }
6336 }
6337
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006338 String msg;
6339 if (!cpi.exported) {
6340 msg = "Permission Denial: opening provider " + cpi.name
6341 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6342 + ", uid=" + callingUid + ") that is not exported from uid "
6343 + cpi.applicationInfo.uid;
6344 } else {
6345 msg = "Permission Denial: opening provider " + cpi.name
6346 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6347 + ", uid=" + callingUid + ") requires "
6348 + cpi.readPermission + " or " + cpi.writePermission;
6349 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006350 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 return msg;
6352 }
6353
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006354 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6355 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006356 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006357 for (int i=0; i<r.conProviders.size(); i++) {
6358 ContentProviderConnection conn = r.conProviders.get(i);
6359 if (conn.provider == cpr) {
6360 if (DEBUG_PROVIDER) Slog.v(TAG,
6361 "Adding provider requested by "
6362 + r.processName + " from process "
6363 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6364 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6365 if (stable) {
6366 conn.stableCount++;
6367 conn.numStableIncs++;
6368 } else {
6369 conn.unstableCount++;
6370 conn.numUnstableIncs++;
6371 }
6372 return conn;
6373 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006374 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006375 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6376 if (stable) {
6377 conn.stableCount = 1;
6378 conn.numStableIncs = 1;
6379 } else {
6380 conn.unstableCount = 1;
6381 conn.numUnstableIncs = 1;
6382 }
6383 cpr.connections.add(conn);
6384 r.conProviders.add(conn);
6385 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006386 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006387 cpr.addExternalProcessHandleLocked(externalProcessToken);
6388 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006389 }
6390
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006391 boolean decProviderCountLocked(ContentProviderConnection conn,
6392 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6393 if (conn != null) {
6394 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006395 if (DEBUG_PROVIDER) Slog.v(TAG,
6396 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006397 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006398 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006399 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6400 if (stable) {
6401 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006402 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006403 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006404 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006405 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6406 cpr.connections.remove(conn);
6407 conn.client.conProviders.remove(conn);
6408 return true;
6409 }
6410 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006411 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006412 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006413 return false;
6414 }
6415
Amith Yamasani742a6712011-05-04 14:49:28 -07006416 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006417 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006419 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 ProviderInfo cpi = null;
6421
6422 synchronized(this) {
6423 ProcessRecord r = null;
6424 if (caller != null) {
6425 r = getRecordForAppLocked(caller);
6426 if (r == null) {
6427 throw new SecurityException(
6428 "Unable to find app for caller " + caller
6429 + " (pid=" + Binder.getCallingPid()
6430 + ") when getting content provider " + name);
6431 }
6432 }
6433
6434 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006435 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006436 boolean providerRunning = cpr != null;
6437 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006439 String msg;
6440 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6441 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 }
6443
6444 if (r != null && cpr.canRunHere(r)) {
6445 // This provider has been published or is in the process
6446 // of being published... but it is also allowed to run
6447 // in the caller's process, so don't make a connection
6448 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006449 ContentProviderHolder holder = cpr.newHolder(null);
6450 // don't give caller the provider object, it needs
6451 // to make its own.
6452 holder.provider = null;
6453 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
6455
6456 final long origId = Binder.clearCallingIdentity();
6457
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006458 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006460 conn = incProviderCountLocked(r, cpr, token, stable);
6461 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006462 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006463 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006464 // make sure to count it as being accessed and thus
6465 // back up on the LRU list. This is good because
6466 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006467 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006468 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006469 }
6470
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006471 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006472 if (false) {
6473 if (cpr.name.flattenToShortString().equals(
6474 "com.android.providers.calendar/.CalendarProvider2")) {
6475 Slog.v(TAG, "****************** KILLING "
6476 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006477 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006478 }
6479 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006480 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006481 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6482 // NOTE: there is still a race here where a signal could be
6483 // pending on the process even though we managed to update its
6484 // adj level. Not sure what to do about this, but at least
6485 // the race is now smaller.
6486 if (!success) {
6487 // Uh oh... it looks like the provider's process
6488 // has been killed on us. We need to wait for a new
6489 // process to be started, and make sure its death
6490 // doesn't kill our process.
6491 Slog.i(TAG,
6492 "Existing provider " + cpr.name.flattenToShortString()
6493 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006494 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006495 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006496 if (!lastRef) {
6497 // This wasn't the last ref our process had on
6498 // the provider... we have now been killed, bail.
6499 return null;
6500 }
6501 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006502 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 }
6505
6506 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006509 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006510 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006512 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006513 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006514 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 } catch (RemoteException ex) {
6516 }
6517 if (cpi == null) {
6518 return null;
6519 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006520 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6521 cpi.name, cpi.flags);
6522 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006523 userId = 0;
6524 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006525 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006526
Dianne Hackbornb424b632010-08-18 15:59:05 -07006527 String msg;
6528 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6529 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 }
6531
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006532 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006533 && !cpi.processName.equals("system")) {
6534 // If this content provider does not run in the system
6535 // process, and the system is not yet ready to run other
6536 // processes, then fail fast instead of hanging.
6537 throw new IllegalArgumentException(
6538 "Attempt to launch content provider before system ready");
6539 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006540
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006541 // Make sure that the user who owns this provider is started. If not,
6542 // we don't want to allow it to run.
6543 if (mStartedUsers.get(userId) == null) {
6544 Slog.w(TAG, "Unable to launch app "
6545 + cpi.applicationInfo.packageName + "/"
6546 + cpi.applicationInfo.uid + " for provider "
6547 + name + ": user " + userId + " is stopped");
6548 return null;
6549 }
6550
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006551 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006552 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 final boolean firstClass = cpr == null;
6554 if (firstClass) {
6555 try {
6556 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006557 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 getApplicationInfo(
6559 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006560 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006562 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 + cpi.name);
6564 return null;
6565 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006566 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006567 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 } catch (RemoteException ex) {
6569 // pm is in same process, this will never happen.
6570 }
6571 }
6572
6573 if (r != null && cpr.canRunHere(r)) {
6574 // If this is a multiprocess provider, then just return its
6575 // info and allow the caller to instantiate it. Only do
6576 // this if the provider is the same user as the caller's
6577 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006578 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 }
6580
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006581 if (DEBUG_PROVIDER) {
6582 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006583 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006584 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 }
6586
6587 // This is single process, and our app is now connecting to it.
6588 // See if we are already in the process of launching this
6589 // provider.
6590 final int N = mLaunchingProviders.size();
6591 int i;
6592 for (i=0; i<N; i++) {
6593 if (mLaunchingProviders.get(i) == cpr) {
6594 break;
6595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 }
6597
6598 // If the provider is not already being launched, then get it
6599 // started.
6600 if (i >= N) {
6601 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006602
6603 try {
6604 // Content provider is now in use, its package can't be stopped.
6605 try {
6606 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006607 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006608 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006609 } catch (IllegalArgumentException e) {
6610 Slog.w(TAG, "Failed trying to unstop package "
6611 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006612 }
6613
6614 ProcessRecord proc = startProcessLocked(cpi.processName,
6615 cpr.appInfo, false, 0, "content provider",
6616 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006617 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006618 if (proc == null) {
6619 Slog.w(TAG, "Unable to launch app "
6620 + cpi.applicationInfo.packageName + "/"
6621 + cpi.applicationInfo.uid + " for provider "
6622 + name + ": process is bad");
6623 return null;
6624 }
6625 cpr.launchingApp = proc;
6626 mLaunchingProviders.add(cpr);
6627 } finally {
6628 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 }
6631
6632 // Make sure the provider is published (the same provider class
6633 // may be published under multiple names).
6634 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006635 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006637
Amith Yamasani742a6712011-05-04 14:49:28 -07006638 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006639 conn = incProviderCountLocked(r, cpr, token, stable);
6640 if (conn != null) {
6641 conn.waiting = true;
6642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 }
6644 }
6645
6646 // Wait for the provider to be published...
6647 synchronized (cpr) {
6648 while (cpr.provider == null) {
6649 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006650 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 + cpi.applicationInfo.packageName + "/"
6652 + cpi.applicationInfo.uid + " for provider "
6653 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006654 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006655 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 cpi.applicationInfo.packageName,
6657 cpi.applicationInfo.uid, name);
6658 return null;
6659 }
6660 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006661 if (DEBUG_MU) {
6662 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6663 + cpr.launchingApp);
6664 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006665 if (conn != null) {
6666 conn.waiting = true;
6667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 cpr.wait();
6669 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006670 } finally {
6671 if (conn != null) {
6672 conn.waiting = false;
6673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 }
6675 }
6676 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006677 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006678 }
6679
6680 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006681 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006682 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 if (caller == null) {
6684 String msg = "null IApplicationThread when getting content provider "
6685 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006686 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 throw new SecurityException(msg);
6688 }
6689
Dianne Hackborn139748f2012-09-24 11:36:57 -07006690 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006691 false, true, "getContentProvider", null);
6692 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 }
6694
Jeff Sharkey6d515712012-09-20 16:06:08 -07006695 public ContentProviderHolder getContentProviderExternal(
6696 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006697 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6698 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006699 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006700 false, true, "getContentProvider", null);
6701 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006702 }
6703
Dianne Hackborn41203752012-08-31 14:05:51 -07006704 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6705 IBinder token, int userId) {
6706 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 }
6708
6709 /**
6710 * Drop a content provider from a ProcessRecord's bookkeeping
6711 * @param cpr
6712 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006713 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006714 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006716 ContentProviderConnection conn;
6717 try {
6718 conn = (ContentProviderConnection)connection;
6719 } catch (ClassCastException e) {
6720 String msg ="removeContentProvider: " + connection
6721 + " not a ContentProviderConnection";
6722 Slog.w(TAG, msg);
6723 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006725 if (conn == null) {
6726 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006728 if (decProviderCountLocked(conn, null, null, stable)) {
6729 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 }
6732 }
6733
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006734 public void removeContentProviderExternal(String name, IBinder token) {
6735 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6736 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006737 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006738 }
6739
Dianne Hackborn41203752012-08-31 14:05:51 -07006740 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006742 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 if(cpr == null) {
6744 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006745 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 return;
6747 }
6748
6749 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006750 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006751 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006752 if (localCpr.hasExternalProcessHandles()) {
6753 if (localCpr.removeExternalProcessHandleLocked(token)) {
6754 updateOomAdjLocked();
6755 } else {
6756 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6757 + " with no external reference for token: "
6758 + token + ".");
6759 }
6760 } else {
6761 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6762 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 }
6765 }
6766
6767 public final void publishContentProviders(IApplicationThread caller,
6768 List<ContentProviderHolder> providers) {
6769 if (providers == null) {
6770 return;
6771 }
6772
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006773 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006774 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006776 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006777 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 if (r == null) {
6779 throw new SecurityException(
6780 "Unable to find app for caller " + caller
6781 + " (pid=" + Binder.getCallingPid()
6782 + ") when publishing content providers");
6783 }
6784
6785 final long origId = Binder.clearCallingIdentity();
6786
6787 final int N = providers.size();
6788 for (int i=0; i<N; i++) {
6789 ContentProviderHolder src = providers.get(i);
6790 if (src == null || src.info == null || src.provider == null) {
6791 continue;
6792 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006793 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006794 if (DEBUG_MU)
6795 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006797 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006798 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 String names[] = dst.info.authority.split(";");
6800 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006801 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 }
6803
6804 int NL = mLaunchingProviders.size();
6805 int j;
6806 for (j=0; j<NL; j++) {
6807 if (mLaunchingProviders.get(j) == dst) {
6808 mLaunchingProviders.remove(j);
6809 j--;
6810 NL--;
6811 }
6812 }
6813 synchronized (dst) {
6814 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006815 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 dst.notifyAll();
6817 }
6818 updateOomAdjLocked(r);
6819 }
6820 }
6821
6822 Binder.restoreCallingIdentity(origId);
6823 }
6824 }
6825
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006826 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6827 ContentProviderConnection conn;
6828 try {
6829 conn = (ContentProviderConnection)connection;
6830 } catch (ClassCastException e) {
6831 String msg ="refContentProvider: " + connection
6832 + " not a ContentProviderConnection";
6833 Slog.w(TAG, msg);
6834 throw new IllegalArgumentException(msg);
6835 }
6836 if (conn == null) {
6837 throw new NullPointerException("connection is null");
6838 }
6839
6840 synchronized (this) {
6841 if (stable > 0) {
6842 conn.numStableIncs += stable;
6843 }
6844 stable = conn.stableCount + stable;
6845 if (stable < 0) {
6846 throw new IllegalStateException("stableCount < 0: " + stable);
6847 }
6848
6849 if (unstable > 0) {
6850 conn.numUnstableIncs += unstable;
6851 }
6852 unstable = conn.unstableCount + unstable;
6853 if (unstable < 0) {
6854 throw new IllegalStateException("unstableCount < 0: " + unstable);
6855 }
6856
6857 if ((stable+unstable) <= 0) {
6858 throw new IllegalStateException("ref counts can't go to zero here: stable="
6859 + stable + " unstable=" + unstable);
6860 }
6861 conn.stableCount = stable;
6862 conn.unstableCount = unstable;
6863 return !conn.dead;
6864 }
6865 }
6866
6867 public void unstableProviderDied(IBinder connection) {
6868 ContentProviderConnection conn;
6869 try {
6870 conn = (ContentProviderConnection)connection;
6871 } catch (ClassCastException e) {
6872 String msg ="refContentProvider: " + connection
6873 + " not a ContentProviderConnection";
6874 Slog.w(TAG, msg);
6875 throw new IllegalArgumentException(msg);
6876 }
6877 if (conn == null) {
6878 throw new NullPointerException("connection is null");
6879 }
6880
6881 // Safely retrieve the content provider associated with the connection.
6882 IContentProvider provider;
6883 synchronized (this) {
6884 provider = conn.provider.provider;
6885 }
6886
6887 if (provider == null) {
6888 // Um, yeah, we're way ahead of you.
6889 return;
6890 }
6891
6892 // Make sure the caller is being honest with us.
6893 if (provider.asBinder().pingBinder()) {
6894 // Er, no, still looks good to us.
6895 synchronized (this) {
6896 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6897 + " says " + conn + " died, but we don't agree");
6898 return;
6899 }
6900 }
6901
6902 // Well look at that! It's dead!
6903 synchronized (this) {
6904 if (conn.provider.provider != provider) {
6905 // But something changed... good enough.
6906 return;
6907 }
6908
6909 ProcessRecord proc = conn.provider.proc;
6910 if (proc == null || proc.thread == null) {
6911 // Seems like the process is already cleaned up.
6912 return;
6913 }
6914
6915 // As far as we're concerned, this is just like receiving a
6916 // death notification... just a bit prematurely.
6917 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6918 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006919 final long ident = Binder.clearCallingIdentity();
6920 try {
6921 appDiedLocked(proc, proc.pid, proc.thread);
6922 } finally {
6923 Binder.restoreCallingIdentity(ident);
6924 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006925 }
6926 }
6927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006928 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006929 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006930 synchronized (mSelf) {
6931 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6932 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006933 if (providers != null) {
6934 for (int i=providers.size()-1; i>=0; i--) {
6935 ProviderInfo pi = (ProviderInfo)providers.get(i);
6936 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6937 Slog.w(TAG, "Not installing system proc provider " + pi.name
6938 + ": not system .apk");
6939 providers.remove(i);
6940 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006941 }
6942 }
6943 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006944 if (providers != null) {
6945 mSystemThread.installSystemProviders(providers);
6946 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006947
6948 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006949
6950 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 }
6952
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006953 /**
6954 * Allows app to retrieve the MIME type of a URI without having permission
6955 * to access its content provider.
6956 *
6957 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6958 *
6959 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6960 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6961 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006962 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006963 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006964 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006965 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006966 final String name = uri.getAuthority();
6967 final long ident = Binder.clearCallingIdentity();
6968 ContentProviderHolder holder = null;
6969
6970 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006971 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006972 if (holder != null) {
6973 return holder.provider.getType(uri);
6974 }
6975 } catch (RemoteException e) {
6976 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6977 return null;
6978 } finally {
6979 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006980 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006981 }
6982 Binder.restoreCallingIdentity(ident);
6983 }
6984
6985 return null;
6986 }
6987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 // =========================================================
6989 // GLOBAL MANAGEMENT
6990 // =========================================================
6991
6992 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006993 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006994 String proc = customProcess != null ? customProcess : info.processName;
6995 BatteryStatsImpl.Uid.Proc ps = null;
6996 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006997 int uid = info.uid;
6998 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006999 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007000 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7001 uid = 0;
7002 while (true) {
7003 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7004 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7005 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7006 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007007 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007008 mNextIsolatedProcessUid++;
7009 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7010 // No process for this uid, use it.
7011 break;
7012 }
7013 stepsLeft--;
7014 if (stepsLeft <= 0) {
7015 return null;
7016 }
7017 }
7018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 synchronized (stats) {
7020 ps = stats.getProcessStatsLocked(info.uid, proc);
7021 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007022 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 }
7024
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007025 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7026 ProcessRecord app;
7027 if (!isolated) {
7028 app = getProcessRecordLocked(info.processName, info.uid);
7029 } else {
7030 app = null;
7031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032
7033 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007034 app = newProcessRecordLocked(null, info, null, isolated);
7035 mProcessNames.put(info.processName, app.uid, app);
7036 if (isolated) {
7037 mIsolatedProcesses.put(app.uid, app);
7038 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007039 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 }
7041
Dianne Hackborne7f97212011-02-24 14:40:20 -08007042 // This package really, really can not be stopped.
7043 try {
7044 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007045 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007046 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007047 } catch (IllegalArgumentException e) {
7048 Slog.w(TAG, "Failed trying to unstop package "
7049 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007050 }
7051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7053 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7054 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007055 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 }
7057 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7058 mPersistentStartingProcesses.add(app);
7059 startProcessLocked(app, "added application", app.processName);
7060 }
7061
7062 return app;
7063 }
7064
7065 public void unhandledBack() {
7066 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7067 "unhandledBack()");
7068
7069 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007070 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007071 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 TAG, "Performing unhandledBack(): stack size = " + count);
7073 if (count > 1) {
7074 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007075 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007076 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 Binder.restoreCallingIdentity(origId);
7078 }
7079 }
7080 }
7081
7082 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007083 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007084 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007086 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 ParcelFileDescriptor pfd = null;
7088 if (cph != null) {
7089 // We record the binder invoker's uid in thread-local storage before
7090 // going to the content provider to open the file. Later, in the code
7091 // that handles all permissions checks, we look for this uid and use
7092 // that rather than the Activity Manager's own uid. The effect is that
7093 // we do the check against the caller's permissions even though it looks
7094 // to the content provider like the Activity Manager itself is making
7095 // the request.
7096 sCallerIdentity.set(new Identity(
7097 Binder.getCallingPid(), Binder.getCallingUid()));
7098 try {
7099 pfd = cph.provider.openFile(uri, "r");
7100 } catch (FileNotFoundException e) {
7101 // do nothing; pfd will be returned null
7102 } finally {
7103 // Ensure that whatever happens, we clean up the identity state
7104 sCallerIdentity.remove();
7105 }
7106
7107 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007108 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007110 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007111 }
7112 return pfd;
7113 }
7114
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007115 // Actually is sleeping or shutting down or whatever else in the future
7116 // is an inactive state.
7117 public boolean isSleeping() {
7118 return mSleeping || mShuttingDown;
7119 }
7120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007122 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7123 != PackageManager.PERMISSION_GRANTED) {
7124 throw new SecurityException("Requires permission "
7125 + android.Manifest.permission.DEVICE_POWER);
7126 }
7127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007129 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007130 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007132 if (!mSleeping) {
7133 mSleeping = true;
7134 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007135
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007136 // Initialize the wake times of all processes.
7137 checkExcessivePowerUsageLocked(false);
7138 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7139 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7140 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 }
7143 }
7144
Dianne Hackborn55280a92009-05-07 15:53:46 -07007145 public boolean shutdown(int timeout) {
7146 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7147 != PackageManager.PERMISSION_GRANTED) {
7148 throw new SecurityException("Requires permission "
7149 + android.Manifest.permission.SHUTDOWN);
7150 }
7151
7152 boolean timedout = false;
7153
7154 synchronized(this) {
7155 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007156 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007157
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007158 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007159 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007160 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007161 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007162 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007163 long delay = endTime - System.currentTimeMillis();
7164 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007165 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007166 timedout = true;
7167 break;
7168 }
7169 try {
7170 this.wait();
7171 } catch (InterruptedException e) {
7172 }
7173 }
7174 }
7175 }
7176
7177 mUsageStatsService.shutdown();
7178 mBatteryStatsService.shutdown();
7179
7180 return timedout;
7181 }
7182
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007183 public final void activitySlept(IBinder token) {
7184 if (localLOGV) Slog.v(
7185 TAG, "Activity slept: token=" + token);
7186
7187 ActivityRecord r = null;
7188
7189 final long origId = Binder.clearCallingIdentity();
7190
7191 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007192 r = mMainStack.isInStackLocked(token);
7193 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007194 mMainStack.activitySleptLocked(r);
7195 }
7196 }
7197
7198 Binder.restoreCallingIdentity(origId);
7199 }
7200
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007201 private void comeOutOfSleepIfNeededLocked() {
7202 if (!mWentToSleep && !mLockScreenShown) {
7203 if (mSleeping) {
7204 mSleeping = false;
7205 mMainStack.awakeFromSleepingLocked();
7206 mMainStack.resumeTopActivityLocked(null);
7207 }
7208 }
7209 }
7210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007212 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7213 != PackageManager.PERMISSION_GRANTED) {
7214 throw new SecurityException("Requires permission "
7215 + android.Manifest.permission.DEVICE_POWER);
7216 }
7217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007219 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007220 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007221 comeOutOfSleepIfNeededLocked();
7222 }
7223 }
7224
Jeff Brownc042ee22012-05-08 13:03:42 -07007225 private void updateEventDispatchingLocked() {
7226 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7227 }
7228
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007229 public void setLockScreenShown(boolean shown) {
7230 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7231 != PackageManager.PERMISSION_GRANTED) {
7232 throw new SecurityException("Requires permission "
7233 + android.Manifest.permission.DEVICE_POWER);
7234 }
7235
7236 synchronized(this) {
7237 mLockScreenShown = shown;
7238 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 }
7240 }
7241
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007242 public void stopAppSwitches() {
7243 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7244 != PackageManager.PERMISSION_GRANTED) {
7245 throw new SecurityException("Requires permission "
7246 + android.Manifest.permission.STOP_APP_SWITCHES);
7247 }
7248
7249 synchronized(this) {
7250 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7251 + APP_SWITCH_DELAY_TIME;
7252 mDidAppSwitch = false;
7253 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7254 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7255 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7256 }
7257 }
7258
7259 public void resumeAppSwitches() {
7260 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7261 != PackageManager.PERMISSION_GRANTED) {
7262 throw new SecurityException("Requires permission "
7263 + android.Manifest.permission.STOP_APP_SWITCHES);
7264 }
7265
7266 synchronized(this) {
7267 // Note that we don't execute any pending app switches... we will
7268 // let those wait until either the timeout, or the next start
7269 // activity request.
7270 mAppSwitchesAllowedTime = 0;
7271 }
7272 }
7273
7274 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7275 String name) {
7276 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7277 return true;
7278 }
7279
7280 final int perm = checkComponentPermission(
7281 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007282 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007283 if (perm == PackageManager.PERMISSION_GRANTED) {
7284 return true;
7285 }
7286
Joe Onorato8a9b2202010-02-26 18:56:32 -08007287 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007288 return false;
7289 }
7290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 public void setDebugApp(String packageName, boolean waitForDebugger,
7292 boolean persistent) {
7293 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7294 "setDebugApp()");
7295
7296 // Note that this is not really thread safe if there are multiple
7297 // callers into it at the same time, but that's not a situation we
7298 // care about.
7299 if (persistent) {
7300 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007301 Settings.Global.putString(
7302 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007304 Settings.Global.putInt(
7305 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 waitForDebugger ? 1 : 0);
7307 }
7308
7309 synchronized (this) {
7310 if (!persistent) {
7311 mOrigDebugApp = mDebugApp;
7312 mOrigWaitForDebugger = mWaitForDebugger;
7313 }
7314 mDebugApp = packageName;
7315 mWaitForDebugger = waitForDebugger;
7316 mDebugTransient = !persistent;
7317 if (packageName != null) {
7318 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007319 forceStopPackageLocked(packageName, -1, false, false, true, true,
7320 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 Binder.restoreCallingIdentity(origId);
7322 }
7323 }
7324 }
7325
Siva Velusamy92a8b222012-03-09 16:24:04 -08007326 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7327 synchronized (this) {
7328 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7329 if (!isDebuggable) {
7330 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7331 throw new SecurityException("Process not debuggable: " + app.packageName);
7332 }
7333 }
7334
7335 mOpenGlTraceApp = processName;
7336 }
7337 }
7338
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007339 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7340 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7341 synchronized (this) {
7342 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7343 if (!isDebuggable) {
7344 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7345 throw new SecurityException("Process not debuggable: " + app.packageName);
7346 }
7347 }
7348 mProfileApp = processName;
7349 mProfileFile = profileFile;
7350 if (mProfileFd != null) {
7351 try {
7352 mProfileFd.close();
7353 } catch (IOException e) {
7354 }
7355 mProfileFd = null;
7356 }
7357 mProfileFd = profileFd;
7358 mProfileType = 0;
7359 mAutoStopProfiler = autoStopProfiler;
7360 }
7361 }
7362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007363 public void setAlwaysFinish(boolean enabled) {
7364 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7365 "setAlwaysFinish()");
7366
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007367 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007368 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007369 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370
7371 synchronized (this) {
7372 mAlwaysFinishActivities = enabled;
7373 }
7374 }
7375
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007376 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007378 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007380 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 }
7382 }
7383
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007384 public boolean isUserAMonkey() {
7385 // For now the fact that there is a controller implies
7386 // we have a monkey.
7387 synchronized (this) {
7388 return mController != null;
7389 }
7390 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007391
7392 public void requestBugReport() {
7393 // No permission check because this can't do anything harmful --
7394 // it will just eventually cause the user to be presented with
7395 // a UI to select where the bug report goes.
7396 SystemProperties.set("ctl.start", "bugreport");
7397 }
7398
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007399 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7400 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7401 != PackageManager.PERMISSION_GRANTED) {
7402 throw new SecurityException("Requires permission "
7403 + android.Manifest.permission.FILTER_EVENTS);
7404 }
7405
7406 ProcessRecord proc;
7407
7408 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7409 synchronized (this) {
7410 synchronized (mPidsSelfLocked) {
7411 proc = mPidsSelfLocked.get(pid);
7412 }
7413 if (proc != null) {
7414 if (proc.debugging) {
7415 return -1;
7416 }
7417
7418 if (mDidDexOpt) {
7419 // Give more time since we were dexopting.
7420 mDidDexOpt = false;
7421 return -1;
7422 }
7423
7424 if (proc.instrumentationClass != null) {
7425 Bundle info = new Bundle();
7426 info.putString("shortMsg", "keyDispatchingTimedOut");
7427 info.putString("longMsg", "Timed out while dispatching key event");
7428 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7429 proc = null;
7430 }
7431 }
7432 }
7433
7434 if (proc != null) {
7435 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7436 if (proc.instrumentationClass != null || proc.usingWrapper) {
7437 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7438 }
7439 }
7440
7441 return KEY_DISPATCHING_TIMEOUT;
7442 }
7443
Jeff Sharkeya4620792011-05-20 15:29:23 -07007444 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007445 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7446 "registerProcessObserver()");
7447 synchronized (this) {
7448 mProcessObservers.register(observer);
7449 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007450 }
7451
7452 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007453 synchronized (this) {
7454 mProcessObservers.unregister(observer);
7455 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007456 }
7457
Daniel Sandler69a48172010-06-23 16:29:36 -04007458 public void setImmersive(IBinder token, boolean immersive) {
7459 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007460 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007461 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007462 throw new IllegalArgumentException();
7463 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007464 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007465
7466 // update associated state if we're frontmost
7467 if (r == mFocusedActivity) {
7468 if (DEBUG_IMMERSIVE) {
7469 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7470 }
7471 applyUpdateLockStateLocked(r);
7472 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007473 }
7474 }
7475
7476 public boolean isImmersive(IBinder token) {
7477 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007478 ActivityRecord r = mMainStack.isInStackLocked(token);
7479 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007480 throw new IllegalArgumentException();
7481 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007482 return r.immersive;
7483 }
7484 }
7485
7486 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007487 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007488 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007489 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007490 return (r != null) ? r.immersive : false;
7491 }
7492 }
7493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 public final void enterSafeMode() {
7495 synchronized(this) {
7496 // It only makes sense to do this before the system is ready
7497 // and started launching other packages.
7498 if (!mSystemReady) {
7499 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007500 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 } catch (RemoteException e) {
7502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 }
7504 }
7505 }
7506
Jeff Brownb09abc12011-01-13 21:08:27 -08007507 public final void showSafeModeOverlay() {
7508 View v = LayoutInflater.from(mContext).inflate(
7509 com.android.internal.R.layout.safe_mode, null);
7510 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7511 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7512 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7513 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007514 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007515 lp.format = v.getBackground().getOpacity();
7516 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7517 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007518 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007519 ((WindowManager)mContext.getSystemService(
7520 Context.WINDOW_SERVICE)).addView(v, lp);
7521 }
7522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 public void noteWakeupAlarm(IIntentSender sender) {
7524 if (!(sender instanceof PendingIntentRecord)) {
7525 return;
7526 }
7527 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7528 synchronized (stats) {
7529 if (mBatteryStatsService.isOnBattery()) {
7530 mBatteryStatsService.enforceCallingPermission();
7531 PendingIntentRecord rec = (PendingIntentRecord)sender;
7532 int MY_UID = Binder.getCallingUid();
7533 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7534 BatteryStatsImpl.Uid.Pkg pkg =
7535 stats.getPackageStatsLocked(uid, rec.key.packageName);
7536 pkg.incWakeupsLocked();
7537 }
7538 }
7539 }
7540
Dianne Hackborn64825172011-03-02 21:32:58 -08007541 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007543 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007545 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 // XXX Note: don't acquire main activity lock here, because the window
7547 // manager calls in with its locks held.
7548
7549 boolean killed = false;
7550 synchronized (mPidsSelfLocked) {
7551 int[] types = new int[pids.length];
7552 int worstType = 0;
7553 for (int i=0; i<pids.length; i++) {
7554 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7555 if (proc != null) {
7556 int type = proc.setAdj;
7557 types[i] = type;
7558 if (type > worstType) {
7559 worstType = type;
7560 }
7561 }
7562 }
7563
Dianne Hackborn64825172011-03-02 21:32:58 -08007564 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007566 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7567 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007568 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007570
7571 // If this is not a secure call, don't let it kill processes that
7572 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007573 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7574 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007575 }
7576
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007577 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 for (int i=0; i<pids.length; i++) {
7579 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7580 if (proc == null) {
7581 continue;
7582 }
7583 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007584 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007585 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007586 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007587 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007589 proc.killedBackground = true;
7590 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 }
7592 }
7593 }
7594 return killed;
7595 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007596
7597 @Override
7598 public boolean killProcessesBelowForeground(String reason) {
7599 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7600 throw new SecurityException("killProcessesBelowForeground() only available to system");
7601 }
7602
7603 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7604 }
7605
7606 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7607 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7608 throw new SecurityException("killProcessesBelowAdj() only available to system");
7609 }
7610
7611 boolean killed = false;
7612 synchronized (mPidsSelfLocked) {
7613 final int size = mPidsSelfLocked.size();
7614 for (int i = 0; i < size; i++) {
7615 final int pid = mPidsSelfLocked.keyAt(i);
7616 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7617 if (proc == null) continue;
7618
7619 final int adj = proc.setAdj;
7620 if (adj > belowAdj && !proc.killedBackground) {
7621 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007622 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7623 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007624 killed = true;
7625 proc.killedBackground = true;
7626 Process.killProcessQuiet(pid);
7627 }
7628 }
7629 }
7630 return killed;
7631 }
7632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 public final void startRunning(String pkg, String cls, String action,
7634 String data) {
7635 synchronized(this) {
7636 if (mStartRunning) {
7637 return;
7638 }
7639 mStartRunning = true;
7640 mTopComponent = pkg != null && cls != null
7641 ? new ComponentName(pkg, cls) : null;
7642 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7643 mTopData = data;
7644 if (!mSystemReady) {
7645 return;
7646 }
7647 }
7648
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007649 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007650 }
7651
7652 private void retrieveSettings() {
7653 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007654 String debugApp = Settings.Global.getString(
7655 resolver, Settings.Global.DEBUG_APP);
7656 boolean waitForDebugger = Settings.Global.getInt(
7657 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7658 boolean alwaysFinishActivities = Settings.Global.getInt(
7659 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660
7661 Configuration configuration = new Configuration();
7662 Settings.System.getConfiguration(resolver, configuration);
7663
7664 synchronized (this) {
7665 mDebugApp = mOrigDebugApp = debugApp;
7666 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7667 mAlwaysFinishActivities = alwaysFinishActivities;
7668 // This happens before any activities are started, so we can
7669 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007670 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007671 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 }
7673 }
7674
7675 public boolean testIsSystemReady() {
7676 // no need to synchronize(this) just to read & return the value
7677 return mSystemReady;
7678 }
7679
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007680 private static File getCalledPreBootReceiversFile() {
7681 File dataDir = Environment.getDataDirectory();
7682 File systemDir = new File(dataDir, "system");
7683 File fname = new File(systemDir, "called_pre_boots.dat");
7684 return fname;
7685 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007686
7687 static final int LAST_DONE_VERSION = 10000;
7688
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007689 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7690 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7691 File file = getCalledPreBootReceiversFile();
7692 FileInputStream fis = null;
7693 try {
7694 fis = new FileInputStream(file);
7695 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007696 int fvers = dis.readInt();
7697 if (fvers == LAST_DONE_VERSION) {
7698 String vers = dis.readUTF();
7699 String codename = dis.readUTF();
7700 String build = dis.readUTF();
7701 if (android.os.Build.VERSION.RELEASE.equals(vers)
7702 && android.os.Build.VERSION.CODENAME.equals(codename)
7703 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7704 int num = dis.readInt();
7705 while (num > 0) {
7706 num--;
7707 String pkg = dis.readUTF();
7708 String cls = dis.readUTF();
7709 lastDoneReceivers.add(new ComponentName(pkg, cls));
7710 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007711 }
7712 }
7713 } catch (FileNotFoundException e) {
7714 } catch (IOException e) {
7715 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7716 } finally {
7717 if (fis != null) {
7718 try {
7719 fis.close();
7720 } catch (IOException e) {
7721 }
7722 }
7723 }
7724 return lastDoneReceivers;
7725 }
7726
7727 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7728 File file = getCalledPreBootReceiversFile();
7729 FileOutputStream fos = null;
7730 DataOutputStream dos = null;
7731 try {
7732 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7733 fos = new FileOutputStream(file);
7734 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007735 dos.writeInt(LAST_DONE_VERSION);
7736 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007737 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007738 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007739 dos.writeInt(list.size());
7740 for (int i=0; i<list.size(); i++) {
7741 dos.writeUTF(list.get(i).getPackageName());
7742 dos.writeUTF(list.get(i).getClassName());
7743 }
7744 } catch (IOException e) {
7745 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7746 file.delete();
7747 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007748 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007749 if (dos != null) {
7750 try {
7751 dos.close();
7752 } catch (IOException e) {
7753 // TODO Auto-generated catch block
7754 e.printStackTrace();
7755 }
7756 }
7757 }
7758 }
7759
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007760 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 synchronized(this) {
7762 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007763 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 return;
7765 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007766
7767 // Check to see if there are any update receivers to run.
7768 if (!mDidUpdate) {
7769 if (mWaitingUpdate) {
7770 return;
7771 }
7772 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7773 List<ResolveInfo> ris = null;
7774 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007775 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007776 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007777 } catch (RemoteException e) {
7778 }
7779 if (ris != null) {
7780 for (int i=ris.size()-1; i>=0; i--) {
7781 if ((ris.get(i).activityInfo.applicationInfo.flags
7782 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7783 ris.remove(i);
7784 }
7785 }
7786 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007787
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007788 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007789
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007790 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007791 for (int i=0; i<ris.size(); i++) {
7792 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007793 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7794 if (lastDoneReceivers.contains(comp)) {
7795 ris.remove(i);
7796 i--;
7797 }
7798 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007799
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007800 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007801 for (int i=0; i<ris.size(); i++) {
7802 ActivityInfo ai = ris.get(i).activityInfo;
7803 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7804 doneReceivers.add(comp);
7805 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007806 for (int j=0; j<users.length; j++) {
7807 IIntentReceiver finisher = null;
7808 if (i == ris.size()-1 && j == users.length-1) {
7809 finisher = new IIntentReceiver.Stub() {
7810 public void performReceive(Intent intent, int resultCode,
7811 String data, Bundle extras, boolean ordered,
7812 boolean sticky, int sendingUser) {
7813 // The raw IIntentReceiver interface is called
7814 // with the AM lock held, so redispatch to
7815 // execute our code without the lock.
7816 mHandler.post(new Runnable() {
7817 public void run() {
7818 synchronized (ActivityManagerService.this) {
7819 mDidUpdate = true;
7820 }
7821 writeLastDonePreBootReceivers(doneReceivers);
7822 showBootMessage(mContext.getText(
7823 R.string.android_upgrading_complete),
7824 false);
7825 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007826 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007827 });
7828 }
7829 };
7830 }
7831 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7832 + " for user " + users[j]);
7833 broadcastIntentLocked(null, null, intent, null, finisher,
7834 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7835 users[j]);
7836 if (finisher != null) {
7837 mWaitingUpdate = true;
7838 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007839 }
7840 }
7841 }
7842 if (mWaitingUpdate) {
7843 return;
7844 }
7845 mDidUpdate = true;
7846 }
7847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 mSystemReady = true;
7849 if (!mStartRunning) {
7850 return;
7851 }
7852 }
7853
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007854 ArrayList<ProcessRecord> procsToKill = null;
7855 synchronized(mPidsSelfLocked) {
7856 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7857 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7858 if (!isAllowedWhileBooting(proc.info)){
7859 if (procsToKill == null) {
7860 procsToKill = new ArrayList<ProcessRecord>();
7861 }
7862 procsToKill.add(proc);
7863 }
7864 }
7865 }
7866
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007867 synchronized(this) {
7868 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007869 for (int i=procsToKill.size()-1; i>=0; i--) {
7870 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007871 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007872 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007873 }
7874 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007875
7876 // Now that we have cleaned up any update processes, we
7877 // are ready to start launching real processes and know that
7878 // we won't trample on them any more.
7879 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007880 }
7881
Joe Onorato8a9b2202010-02-26 18:56:32 -08007882 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007883 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 SystemClock.uptimeMillis());
7885
7886 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007887 // Make sure we have no pre-ready processes sitting around.
7888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7890 ResolveInfo ri = mContext.getPackageManager()
7891 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007892 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 CharSequence errorMsg = null;
7894 if (ri != null) {
7895 ActivityInfo ai = ri.activityInfo;
7896 ApplicationInfo app = ai.applicationInfo;
7897 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7898 mTopAction = Intent.ACTION_FACTORY_TEST;
7899 mTopData = null;
7900 mTopComponent = new ComponentName(app.packageName,
7901 ai.name);
7902 } else {
7903 errorMsg = mContext.getResources().getText(
7904 com.android.internal.R.string.factorytest_not_system);
7905 }
7906 } else {
7907 errorMsg = mContext.getResources().getText(
7908 com.android.internal.R.string.factorytest_no_action);
7909 }
7910 if (errorMsg != null) {
7911 mTopAction = null;
7912 mTopData = null;
7913 mTopComponent = null;
7914 Message msg = Message.obtain();
7915 msg.what = SHOW_FACTORY_ERROR_MSG;
7916 msg.getData().putCharSequence("msg", errorMsg);
7917 mHandler.sendMessage(msg);
7918 }
7919 }
7920 }
7921
7922 retrieveSettings();
7923
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007924 if (goingCallback != null) goingCallback.run();
7925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 synchronized (this) {
7927 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7928 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007929 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007930 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 if (apps != null) {
7932 int N = apps.size();
7933 int i;
7934 for (i=0; i<N; i++) {
7935 ApplicationInfo info
7936 = (ApplicationInfo)apps.get(i);
7937 if (info != null &&
7938 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007939 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 }
7941 }
7942 }
7943 } catch (RemoteException ex) {
7944 // pm is in same process, this will never happen.
7945 }
7946 }
7947
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007948 // Start up initial activity.
7949 mBooting = true;
7950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007952 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 Message msg = Message.obtain();
7954 msg.what = SHOW_UID_ERROR_MSG;
7955 mHandler.sendMessage(msg);
7956 }
7957 } catch (RemoteException e) {
7958 }
7959
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007960 long ident = Binder.clearCallingIdentity();
7961 try {
7962 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007963 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7964 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007965 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7966 broadcastIntentLocked(null, null, intent,
7967 null, null, 0, null, null, null,
7968 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07007969 intent = new Intent(Intent.ACTION_USER_STARTING);
7970 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7971 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7972 broadcastIntentLocked(null, null, intent,
7973 null, new IIntentReceiver.Stub() {
7974 @Override
7975 public void performReceive(Intent intent, int resultCode, String data,
7976 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
7977 throws RemoteException {
7978 }
7979 }, 0, null, null,
7980 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08007981 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007982 } finally {
7983 Binder.restoreCallingIdentity(ident);
7984 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007985 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007986 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 }
7988 }
7989
Dan Egnorb7f03672009-12-09 16:22:32 -08007990 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007991 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007993 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007994 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 startAppProblemLocked(app);
7996 app.stopFreezingAllLocked();
7997 return handleAppCrashLocked(app);
7998 }
7999
Dan Egnorb7f03672009-12-09 16:22:32 -08008000 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008001 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008003 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008004 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8005 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 startAppProblemLocked(app);
8007 app.stopFreezingAllLocked();
8008 }
8009
8010 /**
8011 * Generate a process error record, suitable for attachment to a ProcessRecord.
8012 *
8013 * @param app The ProcessRecord in which the error occurred.
8014 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8015 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008016 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 * @param shortMsg Short message describing the crash.
8018 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008019 * @param stackTrace Full crash stack trace, may be null.
8020 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 * @return Returns a fully-formed AppErrorStateInfo record.
8022 */
8023 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008024 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008025 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 report.condition = condition;
8028 report.processName = app.processName;
8029 report.pid = app.pid;
8030 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008031 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 report.shortMsg = shortMsg;
8033 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008034 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035
8036 return report;
8037 }
8038
Dan Egnor42471dd2010-01-07 17:25:22 -08008039 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 synchronized (this) {
8041 app.crashing = false;
8042 app.crashingReport = null;
8043 app.notResponding = false;
8044 app.notRespondingReport = null;
8045 if (app.anrDialog == fromDialog) {
8046 app.anrDialog = null;
8047 }
8048 if (app.waitDialog == fromDialog) {
8049 app.waitDialog = null;
8050 }
8051 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008052 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008053 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008054 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008055 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008056 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008058 }
8059 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008060
Dan Egnorb7f03672009-12-09 16:22:32 -08008061 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008062 if (mHeadless) {
8063 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8064 return false;
8065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008066 long now = SystemClock.uptimeMillis();
8067
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008068 Long crashTime;
8069 if (!app.isolated) {
8070 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8071 } else {
8072 crashTime = null;
8073 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008074 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008076 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008078 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008079 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008080 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8081 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008083 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008085 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8086 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 }
8088 }
8089 if (!app.persistent) {
8090 // We don't want to start this process again until the user
8091 // explicitly does so... but for persistent process, we really
8092 // need to keep it running. If a persistent process is actually
8093 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008094 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008096 if (!app.isolated) {
8097 // XXX We don't have a way to mark isolated processes
8098 // as bad, since they don't have a peristent identity.
8099 mBadProcesses.put(app.info.processName, app.uid, now);
8100 mProcessCrashTimes.remove(app.info.processName, app.uid);
8101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008104 // Don't let services in this process be restarted and potentially
8105 // annoy the user repeatedly. Unless it is persistent, since those
8106 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008107 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008108 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 return false;
8110 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008111 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008112 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008113 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008114 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008115 // If the top running activity is from this crashing
8116 // process, then terminate it to avoid getting in a loop.
8117 Slog.w(TAG, " Force finishing activity "
8118 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008119 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008120 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008121 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008122 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008123 // stopped, to avoid a situation where one will get
8124 // re-start our crashing activity once it gets resumed again.
8125 index--;
8126 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008127 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008128 if (r.state == ActivityState.RESUMED
8129 || r.state == ActivityState.PAUSING
8130 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008131 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008132 Slog.w(TAG, " Force finishing activity "
8133 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008134 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008135 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008136 }
8137 }
8138 }
8139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 }
8141
8142 // Bump up the crash count of any services currently running in the proc.
8143 if (app.services.size() != 0) {
8144 // Any services running in the application need to be placed
8145 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008146 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008147 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008148 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 sr.crashCount++;
8150 }
8151 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008152
8153 // If the crashing process is what we consider to be the "home process" and it has been
8154 // replaced by a third-party app, clear the package preferred activities from packages
8155 // with a home activity running in the process to prevent a repeatedly crashing app
8156 // from blocking the user to manually clear the list.
8157 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8158 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8159 Iterator it = mHomeProcess.activities.iterator();
8160 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008161 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008162 if (r.isHomeActivity) {
8163 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8164 try {
8165 ActivityThread.getPackageManager()
8166 .clearPackagePreferredActivities(r.packageName);
8167 } catch (RemoteException c) {
8168 // pm is in same process, this will never happen.
8169 }
8170 }
8171 }
8172 }
8173
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008174 if (!app.isolated) {
8175 // XXX Can't keep track of crash times for isolated processes,
8176 // because they don't have a perisistent identity.
8177 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8178 }
8179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 return true;
8181 }
8182
8183 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008184 if (app.userId == mCurrentUserId) {
8185 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8186 mContext, app.info.packageName, app.info.flags);
8187 } else {
8188 // If this app is not running under the current user, then we
8189 // can't give it a report button because that would require
8190 // launching the report UI under a different user.
8191 app.errorReportReceiver = null;
8192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 skipCurrentReceiverLocked(app);
8194 }
8195
8196 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008197 for (BroadcastQueue queue : mBroadcastQueues) {
8198 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 }
8200 }
8201
Dan Egnor60d87622009-12-16 16:32:58 -08008202 /**
8203 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8204 * The application process will exit immediately after this call returns.
8205 * @param app object of the crashing app, null for the system server
8206 * @param crashInfo describing the exception
8207 */
8208 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008209 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008210 final String processName = app == null ? "system_server"
8211 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008212
8213 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008214 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008215 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008216 crashInfo.exceptionClassName,
8217 crashInfo.exceptionMessage,
8218 crashInfo.throwFileName,
8219 crashInfo.throwLineNumber);
8220
Jeff Sharkeya353d262011-10-28 11:12:06 -07008221 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008222
8223 crashApplication(r, crashInfo);
8224 }
8225
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008226 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008227 IBinder app,
8228 int violationMask,
8229 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008230 ProcessRecord r = findAppProcess(app, "StrictMode");
8231 if (r == null) {
8232 return;
8233 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008234
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008235 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008236 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008237 boolean logIt = true;
8238 synchronized (mAlreadyLoggedViolatedStacks) {
8239 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8240 logIt = false;
8241 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008242 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008243 // the relative pain numbers, without logging all
8244 // the stack traces repeatedly. We'd want to do
8245 // likewise in the client code, which also does
8246 // dup suppression, before the Binder call.
8247 } else {
8248 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8249 mAlreadyLoggedViolatedStacks.clear();
8250 }
8251 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8252 }
8253 }
8254 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008255 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008256 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008257 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008258
8259 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8260 AppErrorResult result = new AppErrorResult();
8261 synchronized (this) {
8262 final long origId = Binder.clearCallingIdentity();
8263
8264 Message msg = Message.obtain();
8265 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8266 HashMap<String, Object> data = new HashMap<String, Object>();
8267 data.put("result", result);
8268 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008269 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008270 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008271 msg.obj = data;
8272 mHandler.sendMessage(msg);
8273
8274 Binder.restoreCallingIdentity(origId);
8275 }
8276 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008277 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008278 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008279 }
8280
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008281 // Depending on the policy in effect, there could be a bunch of
8282 // these in quick succession so we try to batch these together to
8283 // minimize disk writes, number of dropbox entries, and maximize
8284 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008285 private void logStrictModeViolationToDropBox(
8286 ProcessRecord process,
8287 StrictMode.ViolationInfo info) {
8288 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008289 return;
8290 }
8291 final boolean isSystemApp = process == null ||
8292 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8293 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008294 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008295 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8296 final DropBoxManager dbox = (DropBoxManager)
8297 mContext.getSystemService(Context.DROPBOX_SERVICE);
8298
8299 // Exit early if the dropbox isn't configured to accept this report type.
8300 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8301
8302 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008303 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008304 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8305 synchronized (sb) {
8306 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008307 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008308 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8309 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008310 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8311 if (info.violationNumThisLoop != 0) {
8312 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8313 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008314 if (info.numAnimationsRunning != 0) {
8315 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8316 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008317 if (info.broadcastIntentAction != null) {
8318 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8319 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008320 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008321 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008322 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008323 if (info.numInstances != -1) {
8324 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8325 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008326 if (info.tags != null) {
8327 for (String tag : info.tags) {
8328 sb.append("Span-Tag: ").append(tag).append("\n");
8329 }
8330 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008331 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008332 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8333 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008334 }
8335 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008336
8337 // Only buffer up to ~64k. Various logging bits truncate
8338 // things at 128k.
8339 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008340 }
8341
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008342 // Flush immediately if the buffer's grown too large, or this
8343 // is a non-system app. Non-system apps are isolated with a
8344 // different tag & policy and not batched.
8345 //
8346 // Batching is useful during internal testing with
8347 // StrictMode settings turned up high. Without batching,
8348 // thousands of separate files could be created on boot.
8349 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008350 new Thread("Error dump: " + dropboxTag) {
8351 @Override
8352 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008353 String report;
8354 synchronized (sb) {
8355 report = sb.toString();
8356 sb.delete(0, sb.length());
8357 sb.trimToSize();
8358 }
8359 if (report.length() != 0) {
8360 dbox.addText(dropboxTag, report);
8361 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008362 }
8363 }.start();
8364 return;
8365 }
8366
8367 // System app batching:
8368 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008369 // An existing dropbox-writing thread is outstanding, so
8370 // we don't need to start it up. The existing thread will
8371 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008372 return;
8373 }
8374
8375 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8376 // (After this point, we shouldn't access AMS internal data structures.)
8377 new Thread("Error dump: " + dropboxTag) {
8378 @Override
8379 public void run() {
8380 // 5 second sleep to let stacks arrive and be batched together
8381 try {
8382 Thread.sleep(5000); // 5 seconds
8383 } catch (InterruptedException e) {}
8384
8385 String errorReport;
8386 synchronized (mStrictModeBuffer) {
8387 errorReport = mStrictModeBuffer.toString();
8388 if (errorReport.length() == 0) {
8389 return;
8390 }
8391 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8392 mStrictModeBuffer.trimToSize();
8393 }
8394 dbox.addText(dropboxTag, errorReport);
8395 }
8396 }.start();
8397 }
8398
Dan Egnor60d87622009-12-16 16:32:58 -08008399 /**
8400 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8401 * @param app object of the crashing app, null for the system server
8402 * @param tag reported by the caller
8403 * @param crashInfo describing the context of the error
8404 * @return true if the process should exit immediately (WTF is fatal)
8405 */
8406 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008407 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008408 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008409 final String processName = app == null ? "system_server"
8410 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008411
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008412 EventLog.writeEvent(EventLogTags.AM_WTF,
8413 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008414 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008415 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008416 tag, crashInfo.exceptionMessage);
8417
Jeff Sharkeya353d262011-10-28 11:12:06 -07008418 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008419
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008420 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008421 Settings.Global.getInt(mContext.getContentResolver(),
8422 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008423 crashApplication(r, crashInfo);
8424 return true;
8425 } else {
8426 return false;
8427 }
8428 }
8429
8430 /**
8431 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8432 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8433 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008434 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008435 if (app == null) {
8436 return null;
8437 }
8438
8439 synchronized (this) {
8440 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8441 final int NA = apps.size();
8442 for (int ia=0; ia<NA; ia++) {
8443 ProcessRecord p = apps.valueAt(ia);
8444 if (p.thread != null && p.thread.asBinder() == app) {
8445 return p;
8446 }
8447 }
8448 }
8449
Dianne Hackborncb44d962011-03-10 17:02:27 -08008450 Slog.w(TAG, "Can't find mystery application for " + reason
8451 + " from pid=" + Binder.getCallingPid()
8452 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008453 return null;
8454 }
8455 }
8456
8457 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008458 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8459 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008460 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008461 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8462 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008463 // Watchdog thread ends up invoking this function (with
8464 // a null ProcessRecord) to add the stack file to dropbox.
8465 // Do not acquire a lock on this (am) in such cases, as it
8466 // could cause a potential deadlock, if and when watchdog
8467 // is invoked due to unavailability of lock on am and it
8468 // would prevent watchdog from killing system_server.
8469 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008470 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008471 return;
8472 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008473 // Note: ProcessRecord 'process' is guarded by the service
8474 // instance. (notably process.pkgList, which could otherwise change
8475 // concurrently during execution of this method)
8476 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008477 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008478 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008479 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008480 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8481 for (String pkg : process.pkgList) {
8482 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008483 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008484 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008485 if (pi != null) {
8486 sb.append(" v").append(pi.versionCode);
8487 if (pi.versionName != null) {
8488 sb.append(" (").append(pi.versionName).append(")");
8489 }
8490 }
8491 } catch (RemoteException e) {
8492 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008493 }
Dan Egnora455d192010-03-12 08:52:28 -08008494 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008495 }
Dan Egnora455d192010-03-12 08:52:28 -08008496 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008497 }
8498
8499 private static String processClass(ProcessRecord process) {
8500 if (process == null || process.pid == MY_PID) {
8501 return "system_server";
8502 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8503 return "system_app";
8504 } else {
8505 return "data_app";
8506 }
8507 }
8508
8509 /**
8510 * Write a description of an error (crash, WTF, ANR) to the drop box.
8511 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8512 * @param process which caused the error, null means the system server
8513 * @param activity which triggered the error, null if unknown
8514 * @param parent activity related to the error, null if unknown
8515 * @param subject line related to the error, null if absent
8516 * @param report in long form describing the error, null if absent
8517 * @param logFile to include in the report, null if none
8518 * @param crashInfo giving an application stack trace, null if absent
8519 */
8520 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008521 ProcessRecord process, String processName, ActivityRecord activity,
8522 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008523 final String report, final File logFile,
8524 final ApplicationErrorReport.CrashInfo crashInfo) {
8525 // NOTE -- this must never acquire the ActivityManagerService lock,
8526 // otherwise the watchdog may be prevented from resetting the system.
8527
8528 final String dropboxTag = processClass(process) + "_" + eventType;
8529 final DropBoxManager dbox = (DropBoxManager)
8530 mContext.getSystemService(Context.DROPBOX_SERVICE);
8531
8532 // Exit early if the dropbox isn't configured to accept this report type.
8533 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8534
8535 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008536 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008537 if (activity != null) {
8538 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8539 }
8540 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8541 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8542 }
8543 if (parent != null && parent != activity) {
8544 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8545 }
8546 if (subject != null) {
8547 sb.append("Subject: ").append(subject).append("\n");
8548 }
8549 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008550 if (Debug.isDebuggerConnected()) {
8551 sb.append("Debugger: Connected\n");
8552 }
Dan Egnora455d192010-03-12 08:52:28 -08008553 sb.append("\n");
8554
8555 // Do the rest in a worker thread to avoid blocking the caller on I/O
8556 // (After this point, we shouldn't access AMS internal data structures.)
8557 Thread worker = new Thread("Error dump: " + dropboxTag) {
8558 @Override
8559 public void run() {
8560 if (report != null) {
8561 sb.append(report);
8562 }
8563 if (logFile != null) {
8564 try {
8565 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8566 } catch (IOException e) {
8567 Slog.e(TAG, "Error reading " + logFile, e);
8568 }
8569 }
8570 if (crashInfo != null && crashInfo.stackTrace != null) {
8571 sb.append(crashInfo.stackTrace);
8572 }
8573
Jeff Sharkey625239a2012-09-26 22:03:49 -07008574 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8575 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008576 if (lines > 0) {
8577 sb.append("\n");
8578
8579 // Merge several logcat streams, and take the last N lines
8580 InputStreamReader input = null;
8581 try {
8582 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8583 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8584 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8585
8586 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8587 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8588 input = new InputStreamReader(logcat.getInputStream());
8589
8590 int num;
8591 char[] buf = new char[8192];
8592 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8593 } catch (IOException e) {
8594 Slog.e(TAG, "Error running logcat", e);
8595 } finally {
8596 if (input != null) try { input.close(); } catch (IOException e) {}
8597 }
8598 }
8599
8600 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008601 }
Dan Egnora455d192010-03-12 08:52:28 -08008602 };
8603
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008604 if (process == null) {
8605 // If process is null, we are being called from some internal code
8606 // and may be about to die -- run this synchronously.
8607 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008608 } else {
8609 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008610 }
8611 }
8612
8613 /**
8614 * Bring up the "unexpected error" dialog box for a crashing app.
8615 * Deal with edge cases (intercepts from instrumented applications,
8616 * ActivityController, error intent receivers, that sort of thing).
8617 * @param r the application crashing
8618 * @param crashInfo describing the failure
8619 */
8620 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008621 long timeMillis = System.currentTimeMillis();
8622 String shortMsg = crashInfo.exceptionClassName;
8623 String longMsg = crashInfo.exceptionMessage;
8624 String stackTrace = crashInfo.stackTrace;
8625 if (shortMsg != null && longMsg != null) {
8626 longMsg = shortMsg + ": " + longMsg;
8627 } else if (shortMsg != null) {
8628 longMsg = shortMsg;
8629 }
8630
Dan Egnor60d87622009-12-16 16:32:58 -08008631 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008633 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 try {
8635 String name = r != null ? r.processName : null;
8636 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008637 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008638 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008639 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 + " at watcher's request");
8641 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008642 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 }
8644 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008645 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 }
8647 }
8648
8649 final long origId = Binder.clearCallingIdentity();
8650
8651 // If this process is running instrumentation, finish it.
8652 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008653 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008655 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8656 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 Bundle info = new Bundle();
8658 info.putString("shortMsg", shortMsg);
8659 info.putString("longMsg", longMsg);
8660 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8661 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008662 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 }
8664
Dan Egnor60d87622009-12-16 16:32:58 -08008665 // If we can't identify the process or it's already exceeded its crash quota,
8666 // quit right away without showing a crash dialog.
8667 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008669 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 }
8671
8672 Message msg = Message.obtain();
8673 msg.what = SHOW_ERROR_MSG;
8674 HashMap data = new HashMap();
8675 data.put("result", result);
8676 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 msg.obj = data;
8678 mHandler.sendMessage(msg);
8679
8680 Binder.restoreCallingIdentity(origId);
8681 }
8682
8683 int res = result.get();
8684
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008685 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008687 if (r != null && !r.isolated) {
8688 // XXX Can't keep track of crash time for isolated processes,
8689 // since they don't have a persistent identity.
8690 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 SystemClock.uptimeMillis());
8692 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008693 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008694 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008695 }
8696 }
8697
8698 if (appErrorIntent != null) {
8699 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008700 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008701 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008702 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008706
8707 Intent createAppErrorIntentLocked(ProcessRecord r,
8708 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8709 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008710 if (report == null) {
8711 return null;
8712 }
8713 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8714 result.setComponent(r.errorReportReceiver);
8715 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8716 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8717 return result;
8718 }
8719
Dan Egnorb7f03672009-12-09 16:22:32 -08008720 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8721 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008722 if (r.errorReportReceiver == null) {
8723 return null;
8724 }
8725
8726 if (!r.crashing && !r.notResponding) {
8727 return null;
8728 }
8729
Dan Egnorb7f03672009-12-09 16:22:32 -08008730 ApplicationErrorReport report = new ApplicationErrorReport();
8731 report.packageName = r.info.packageName;
8732 report.installerPackageName = r.errorReportReceiver.getPackageName();
8733 report.processName = r.processName;
8734 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008735 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008736
Dan Egnorb7f03672009-12-09 16:22:32 -08008737 if (r.crashing) {
8738 report.type = ApplicationErrorReport.TYPE_CRASH;
8739 report.crashInfo = crashInfo;
8740 } else if (r.notResponding) {
8741 report.type = ApplicationErrorReport.TYPE_ANR;
8742 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008743
Dan Egnorb7f03672009-12-09 16:22:32 -08008744 report.anrInfo.activity = r.notRespondingReport.tag;
8745 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8746 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008747 }
8748
Dan Egnorb7f03672009-12-09 16:22:32 -08008749 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008750 }
8751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008753 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008754 // assume our apps are happy - lazy create the list
8755 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8756
Dianne Hackborn0c380492012-08-20 17:23:30 -07008757 final boolean allUsers = ActivityManager.checkUidPermission(
8758 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8759 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8760 int userId = UserHandle.getUserId(Binder.getCallingUid());
8761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 synchronized (this) {
8763
8764 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008765 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8766 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008767 if (!allUsers && app.userId != userId) {
8768 continue;
8769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8771 // This one's in trouble, so we'll generate a report for it
8772 // crashes are higher priority (in case there's a crash *and* an anr)
8773 ActivityManager.ProcessErrorStateInfo report = null;
8774 if (app.crashing) {
8775 report = app.crashingReport;
8776 } else if (app.notResponding) {
8777 report = app.notRespondingReport;
8778 }
8779
8780 if (report != null) {
8781 if (errList == null) {
8782 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8783 }
8784 errList.add(report);
8785 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008786 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 " crashing = " + app.crashing +
8788 " notResponding = " + app.notResponding);
8789 }
8790 }
8791 }
8792 }
8793
8794 return errList;
8795 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008796
8797 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008798 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008799 if (currApp != null) {
8800 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8801 }
8802 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008803 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8804 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008805 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8806 if (currApp != null) {
8807 currApp.lru = 0;
8808 }
8809 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008810 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008811 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8812 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8813 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8814 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8815 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8816 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8817 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8818 } else {
8819 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8820 }
8821 }
8822
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008823 private void fillInProcMemInfo(ProcessRecord app,
8824 ActivityManager.RunningAppProcessInfo outInfo) {
8825 outInfo.pid = app.pid;
8826 outInfo.uid = app.info.uid;
8827 if (mHeavyWeightProcess == app) {
8828 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8829 }
8830 if (app.persistent) {
8831 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8832 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008833 if (app.hasActivities) {
8834 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8835 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008836 outInfo.lastTrimLevel = app.trimMemoryLevel;
8837 int adj = app.curAdj;
8838 outInfo.importance = oomAdjToImportance(adj, outInfo);
8839 outInfo.importanceReasonCode = app.adjTypeCode;
8840 }
8841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008843 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 // Lazy instantiation of list
8845 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008846 final boolean allUsers = ActivityManager.checkUidPermission(
8847 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8848 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8849 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 synchronized (this) {
8851 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008852 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8853 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008854 if (!allUsers && app.userId != userId) {
8855 continue;
8856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8858 // Generate process state info for running application
8859 ActivityManager.RunningAppProcessInfo currApp =
8860 new ActivityManager.RunningAppProcessInfo(app.processName,
8861 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008862 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008863 if (app.adjSource instanceof ProcessRecord) {
8864 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008865 currApp.importanceReasonImportance = oomAdjToImportance(
8866 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008867 } else if (app.adjSource instanceof ActivityRecord) {
8868 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008869 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8870 }
8871 if (app.adjTarget instanceof ComponentName) {
8872 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8873 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008874 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 // + " lru=" + currApp.lru);
8876 if (runList == null) {
8877 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8878 }
8879 runList.add(currApp);
8880 }
8881 }
8882 }
8883 return runList;
8884 }
8885
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008886 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008887 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008888 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8889 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8890 if (runningApps != null && runningApps.size() > 0) {
8891 Set<String> extList = new HashSet<String>();
8892 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8893 if (app.pkgList != null) {
8894 for (String pkg : app.pkgList) {
8895 extList.add(pkg);
8896 }
8897 }
8898 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008899 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008900 for (String pkg : extList) {
8901 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008902 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008903 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8904 retList.add(info);
8905 }
8906 } catch (RemoteException e) {
8907 }
8908 }
8909 }
8910 return retList;
8911 }
8912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008914 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8915 enforceNotIsolatedCaller("getMyMemoryState");
8916 synchronized (this) {
8917 ProcessRecord proc;
8918 synchronized (mPidsSelfLocked) {
8919 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8920 }
8921 fillInProcMemInfo(proc, outInfo);
8922 }
8923 }
8924
8925 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008927 if (checkCallingPermission(android.Manifest.permission.DUMP)
8928 != PackageManager.PERMISSION_GRANTED) {
8929 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8930 + Binder.getCallingPid()
8931 + ", uid=" + Binder.getCallingUid()
8932 + " without permission "
8933 + android.Manifest.permission.DUMP);
8934 return;
8935 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008936
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008938 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008939 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008940
8941 int opti = 0;
8942 while (opti < args.length) {
8943 String opt = args[opti];
8944 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8945 break;
8946 }
8947 opti++;
8948 if ("-a".equals(opt)) {
8949 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008950 } else if ("-c".equals(opt)) {
8951 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008952 } else if ("-h".equals(opt)) {
8953 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008954 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008955 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008956 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008957 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008958 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8959 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008960 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008961 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008962 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008963 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008964 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008965 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008966 pw.println(" all: dump all activities");
8967 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008968 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008969 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8970 pw.println(" a partial substring in a component name, a");
8971 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008972 pw.println(" -a: include all available server state.");
8973 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008974 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008975 } else {
8976 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008978 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008979
8980 long origId = Binder.clearCallingIdentity();
8981 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008982 // Is the caller requesting to dump a particular piece of data?
8983 if (opti < args.length) {
8984 String cmd = args[opti];
8985 opti++;
8986 if ("activities".equals(cmd) || "a".equals(cmd)) {
8987 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008988 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 String[] newArgs;
8992 String name;
8993 if (opti >= args.length) {
8994 name = null;
8995 newArgs = EMPTY_STRING_ARRAY;
8996 } else {
8997 name = args[opti];
8998 opti++;
8999 newArgs = new String[args.length - opti];
9000 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9001 args.length - opti);
9002 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009003 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009004 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009005 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009007 String[] newArgs;
9008 String name;
9009 if (opti >= args.length) {
9010 name = null;
9011 newArgs = EMPTY_STRING_ARRAY;
9012 } else {
9013 name = args[opti];
9014 opti++;
9015 newArgs = new String[args.length - opti];
9016 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9017 args.length - opti);
9018 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009019 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009020 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009021 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009023 String[] newArgs;
9024 String name;
9025 if (opti >= args.length) {
9026 name = null;
9027 newArgs = EMPTY_STRING_ARRAY;
9028 } else {
9029 name = args[opti];
9030 opti++;
9031 newArgs = new String[args.length - opti];
9032 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9033 args.length - opti);
9034 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009035 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009036 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009037 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009038 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9039 synchronized (this) {
9040 dumpOomLocked(fd, pw, args, opti, true);
9041 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009042 } else if ("provider".equals(cmd)) {
9043 String[] newArgs;
9044 String name;
9045 if (opti >= args.length) {
9046 name = null;
9047 newArgs = EMPTY_STRING_ARRAY;
9048 } else {
9049 name = args[opti];
9050 opti++;
9051 newArgs = new String[args.length - opti];
9052 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9053 }
9054 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9055 pw.println("No providers match: " + name);
9056 pw.println("Use -h for help.");
9057 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9059 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009060 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009061 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 String[] newArgs;
9064 String name;
9065 if (opti >= args.length) {
9066 name = null;
9067 newArgs = EMPTY_STRING_ARRAY;
9068 } else {
9069 name = args[opti];
9070 opti++;
9071 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009072 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9073 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009074 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009075 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009076 pw.println("No services match: " + name);
9077 pw.println("Use -h for help.");
9078 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009079 } else if ("package".equals(cmd)) {
9080 String[] newArgs;
9081 if (opti >= args.length) {
9082 pw.println("package: no package name specified");
9083 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009084 } else {
9085 dumpPackage = args[opti];
9086 opti++;
9087 newArgs = new String[args.length - opti];
9088 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9089 args.length - opti);
9090 args = newArgs;
9091 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009092 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009093 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9095 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009096 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009098 } else {
9099 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009100 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9101 pw.println("Bad activity command, or no activities match: " + cmd);
9102 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009103 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009104 }
9105 if (!more) {
9106 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009107 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009109 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009110
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009111 // No piece of data specified, dump everything.
9112 synchronized (this) {
9113 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009114 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009115 if (needSep) {
9116 pw.println(" ");
9117 }
9118 if (dumpAll) {
9119 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009120 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009121 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009122 if (needSep) {
9123 pw.println(" ");
9124 }
9125 if (dumpAll) {
9126 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009128 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009129 if (needSep) {
9130 pw.println(" ");
9131 }
9132 if (dumpAll) {
9133 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009134 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009135 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009136 if (needSep) {
9137 pw.println(" ");
9138 }
9139 if (dumpAll) {
9140 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009141 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009142 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009143 if (needSep) {
9144 pw.println(" ");
9145 }
9146 if (dumpAll) {
9147 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009148 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009149 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009150 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009151 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009152 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009153
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009154 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009155 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009156 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9157 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009158 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9159 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009160 pw.println(" ");
9161 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009162 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9163 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009164 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009165 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009166 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009167 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009168 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009169 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009170 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009172 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009173 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009174 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009175 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009176 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9177 pw.println(" ");
9178 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009179 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009180 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009181 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009182 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009183 pw.println(" ");
9184 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009185 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009186 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009189 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009190 if (mMainStack.mPausingActivity != null) {
9191 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009192 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009193 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009194 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009195 if (dumpAll) {
9196 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9197 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009198 pw.println(" mDismissKeyguardOnNextActivity: "
9199 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009202 if (mRecentTasks.size() > 0) {
9203 pw.println();
9204 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009205
9206 final int N = mRecentTasks.size();
9207 for (int i=0; i<N; i++) {
9208 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 if (dumpPackage != null) {
9210 if (tr.realActivity == null ||
9211 !dumpPackage.equals(tr.realActivity)) {
9212 continue;
9213 }
9214 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009215 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9216 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009217 if (dumpAll) {
9218 mRecentTasks.get(i).dump(pw, " ");
9219 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220 }
9221 }
9222
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009223 if (dumpAll) {
9224 pw.println(" ");
9225 pw.println(" mCurTask: " + mCurTask);
9226 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009227
9228 return true;
9229 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009230
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009231 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009232 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009233 boolean needSep = false;
9234 int numPers = 0;
9235
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009236 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9237
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009238 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9240 final int NA = procs.size();
9241 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009242 ProcessRecord r = procs.valueAt(ia);
9243 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9244 continue;
9245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 if (!needSep) {
9247 pw.println(" All known processes:");
9248 needSep = true;
9249 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009250 pw.print(r.persistent ? " *PERS*" : " *APP*");
9251 pw.print(" UID "); pw.print(procs.keyAt(ia));
9252 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009253 r.dump(pw, " ");
9254 if (r.persistent) {
9255 numPers++;
9256 }
9257 }
9258 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009259 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009260
9261 if (mIsolatedProcesses.size() > 0) {
9262 if (needSep) pw.println(" ");
9263 needSep = true;
9264 pw.println(" Isolated process list (sorted by uid):");
9265 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9266 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9267 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9268 continue;
9269 }
9270 pw.println(String.format("%sIsolated #%2d: %s",
9271 " ", i, r.toString()));
9272 }
9273 }
9274
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009275 if (mLruProcesses.size() > 0) {
9276 if (needSep) pw.println(" ");
9277 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009278 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009279 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009280 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 needSep = true;
9282 }
9283
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009284 if (dumpAll) {
9285 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009286 boolean printed = false;
9287 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9288 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9289 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9290 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009291 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009292 if (!printed) {
9293 if (needSep) pw.println(" ");
9294 needSep = true;
9295 pw.println(" PID mappings:");
9296 printed = true;
9297 }
9298 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9299 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 }
9301 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009302 }
9303
9304 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009305 synchronized (mPidsSelfLocked) {
9306 boolean printed = false;
9307 for (int i=0; i<mForegroundProcesses.size(); i++) {
9308 ProcessRecord r = mPidsSelfLocked.get(
9309 mForegroundProcesses.valueAt(i).pid);
9310 if (dumpPackage != null && (r == null
9311 || !dumpPackage.equals(r.info.packageName))) {
9312 continue;
9313 }
9314 if (!printed) {
9315 if (needSep) pw.println(" ");
9316 needSep = true;
9317 pw.println(" Foreground Processes:");
9318 printed = true;
9319 }
9320 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9321 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009324 }
9325
9326 if (mPersistentStartingProcesses.size() > 0) {
9327 if (needSep) pw.println(" ");
9328 needSep = true;
9329 pw.println(" Persisent processes that are starting:");
9330 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009331 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009334 if (mRemovedProcesses.size() > 0) {
9335 if (needSep) pw.println(" ");
9336 needSep = true;
9337 pw.println(" Processes that are being removed:");
9338 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009339 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009340 }
9341
9342 if (mProcessesOnHold.size() > 0) {
9343 if (needSep) pw.println(" ");
9344 needSep = true;
9345 pw.println(" Processes that are on old until the system is ready:");
9346 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009347 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009350 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009351
9352 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009353 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009354 long now = SystemClock.uptimeMillis();
9355 for (Map.Entry<String, SparseArray<Long>> procs
9356 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009357 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009358 SparseArray<Long> uids = procs.getValue();
9359 final int N = uids.size();
9360 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009361 int puid = uids.keyAt(i);
9362 ProcessRecord r = mProcessNames.get(pname, puid);
9363 if (dumpPackage != null && (r == null
9364 || !dumpPackage.equals(r.info.packageName))) {
9365 continue;
9366 }
9367 if (!printed) {
9368 if (needSep) pw.println(" ");
9369 needSep = true;
9370 pw.println(" Time since processes crashed:");
9371 printed = true;
9372 }
9373 pw.print(" Process "); pw.print(pname);
9374 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009375 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009376 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9377 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009378 }
9379 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009382 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009383 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009384 for (Map.Entry<String, SparseArray<Long>> procs
9385 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009386 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009387 SparseArray<Long> uids = procs.getValue();
9388 final int N = uids.size();
9389 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009390 int puid = uids.keyAt(i);
9391 ProcessRecord r = mProcessNames.get(pname, puid);
9392 if (dumpPackage != null && (r == null
9393 || !dumpPackage.equals(r.info.packageName))) {
9394 continue;
9395 }
9396 if (!printed) {
9397 if (needSep) pw.println(" ");
9398 needSep = true;
9399 pw.println(" Bad processes:");
9400 }
9401 pw.print(" Bad process "); pw.print(pname);
9402 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009403 pw.print(": crashed at time ");
9404 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009405 }
9406 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009409 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009410 pw.println(" mStartedUsers:");
9411 for (int i=0; i<mStartedUsers.size(); i++) {
9412 UserStartedState uss = mStartedUsers.valueAt(i);
9413 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009414 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009415 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009416 pw.print(" mStartedUserArray: [");
9417 for (int i=0; i<mStartedUserArray.length; i++) {
9418 if (i > 0) pw.print(", ");
9419 pw.print(mStartedUserArray[i]);
9420 }
9421 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009422 pw.print(" mUserLru: [");
9423 for (int i=0; i<mUserLru.size(); i++) {
9424 if (i > 0) pw.print(", ");
9425 pw.print(mUserLru.get(i));
9426 }
9427 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009428 if (dumpAll) {
9429 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9430 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009431 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009432 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009433 if (dumpAll) {
9434 StringBuilder sb = new StringBuilder(128);
9435 sb.append(" mPreviousProcessVisibleTime: ");
9436 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9437 pw.println(sb);
9438 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009439 if (mHeavyWeightProcess != null) {
9440 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9441 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009442 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009443 if (dumpAll) {
9444 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009445 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009446 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009447 for (Map.Entry<String, Integer> entry
9448 : mCompatModePackages.getPackages().entrySet()) {
9449 String pkg = entry.getKey();
9450 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009451 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9452 continue;
9453 }
9454 if (!printed) {
9455 pw.println(" mScreenCompatPackages:");
9456 printed = true;
9457 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009458 pw.print(" "); pw.print(pkg); pw.print(": ");
9459 pw.print(mode); pw.println();
9460 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009461 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009462 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009463 if (mSleeping || mWentToSleep || mLockScreenShown) {
9464 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9465 + " mLockScreenShown " + mLockScreenShown);
9466 }
9467 if (mShuttingDown) {
9468 pw.println(" mShuttingDown=" + mShuttingDown);
9469 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009470 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9471 || mOrigWaitForDebugger) {
9472 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9473 + " mDebugTransient=" + mDebugTransient
9474 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9475 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009476 if (mOpenGlTraceApp != null) {
9477 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9478 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009479 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9480 || mProfileFd != null) {
9481 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9482 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9483 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9484 + mAutoStopProfiler);
9485 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009486 if (mAlwaysFinishActivities || mController != null) {
9487 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9488 + " mController=" + mController);
9489 }
9490 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009493 + " mProcessesReady=" + mProcessesReady
9494 + " mSystemReady=" + mSystemReady);
9495 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009496 + " mBooted=" + mBooted
9497 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009498 pw.print(" mLastPowerCheckRealtime=");
9499 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9500 pw.println("");
9501 pw.print(" mLastPowerCheckUptime=");
9502 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9503 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009504 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9505 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009506 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009507 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9508 + " mNumHiddenProcs=" + mNumHiddenProcs
9509 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009510 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009512
9513 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009514 }
9515
Dianne Hackborn287952c2010-09-22 22:34:31 -07009516 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009517 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009518 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009519 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009520 long now = SystemClock.uptimeMillis();
9521 for (int i=0; i<mProcessesToGc.size(); i++) {
9522 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009523 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9524 continue;
9525 }
9526 if (!printed) {
9527 if (needSep) pw.println(" ");
9528 needSep = true;
9529 pw.println(" Processes that are waiting to GC:");
9530 printed = true;
9531 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009532 pw.print(" Process "); pw.println(proc);
9533 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9534 pw.print(", last gced=");
9535 pw.print(now-proc.lastRequestedGc);
9536 pw.print(" ms ago, last lowMem=");
9537 pw.print(now-proc.lastLowMemory);
9538 pw.println(" ms ago");
9539
9540 }
9541 }
9542 return needSep;
9543 }
9544
9545 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9546 int opti, boolean dumpAll) {
9547 boolean needSep = false;
9548
9549 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009550 if (needSep) pw.println(" ");
9551 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009552 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009553 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009554 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009555 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9556 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9557 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9558 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9559 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009560 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009561 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009562 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009563 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009564 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009565 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009566
9567 if (needSep) pw.println(" ");
9568 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009569 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009570 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009571 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009572 needSep = true;
9573 }
9574
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009575 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009576
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009577 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009578 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009579 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009580 if (mHeavyWeightProcess != null) {
9581 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9582 }
9583
9584 return true;
9585 }
9586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 /**
9588 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009589 * - no provider specified: dump all the providers
9590 * - a flattened component name that matched an existing provider was specified as the
9591 * first arg: dump that one provider
9592 * - the first arg isn't the flattened component name of an existing provider:
9593 * dump all providers whose component contains the first arg as a substring
9594 */
9595 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9596 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009597 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009598 }
9599
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009600 static class ItemMatcher {
9601 ArrayList<ComponentName> components;
9602 ArrayList<String> strings;
9603 ArrayList<Integer> objects;
9604 boolean all;
9605
9606 ItemMatcher() {
9607 all = true;
9608 }
9609
9610 void build(String name) {
9611 ComponentName componentName = ComponentName.unflattenFromString(name);
9612 if (componentName != null) {
9613 if (components == null) {
9614 components = new ArrayList<ComponentName>();
9615 }
9616 components.add(componentName);
9617 all = false;
9618 } else {
9619 int objectId = 0;
9620 // Not a '/' separated full component name; maybe an object ID?
9621 try {
9622 objectId = Integer.parseInt(name, 16);
9623 if (objects == null) {
9624 objects = new ArrayList<Integer>();
9625 }
9626 objects.add(objectId);
9627 all = false;
9628 } catch (RuntimeException e) {
9629 // Not an integer; just do string match.
9630 if (strings == null) {
9631 strings = new ArrayList<String>();
9632 }
9633 strings.add(name);
9634 all = false;
9635 }
9636 }
9637 }
9638
9639 int build(String[] args, int opti) {
9640 for (; opti<args.length; opti++) {
9641 String name = args[opti];
9642 if ("--".equals(name)) {
9643 return opti+1;
9644 }
9645 build(name);
9646 }
9647 return opti;
9648 }
9649
9650 boolean match(Object object, ComponentName comp) {
9651 if (all) {
9652 return true;
9653 }
9654 if (components != null) {
9655 for (int i=0; i<components.size(); i++) {
9656 if (components.get(i).equals(comp)) {
9657 return true;
9658 }
9659 }
9660 }
9661 if (objects != null) {
9662 for (int i=0; i<objects.size(); i++) {
9663 if (System.identityHashCode(object) == objects.get(i)) {
9664 return true;
9665 }
9666 }
9667 }
9668 if (strings != null) {
9669 String flat = comp.flattenToString();
9670 for (int i=0; i<strings.size(); i++) {
9671 if (flat.contains(strings.get(i))) {
9672 return true;
9673 }
9674 }
9675 }
9676 return false;
9677 }
9678 }
9679
Dianne Hackborn625ac272010-09-17 18:29:22 -07009680 /**
9681 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009682 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009683 * - the cmd arg isn't the flattened component name of an existing activity:
9684 * dump all activity whose component contains the cmd as a substring
9685 * - A hex number of the ActivityRecord object instance.
9686 */
9687 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9688 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009689 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009690
9691 if ("all".equals(name)) {
9692 synchronized (this) {
9693 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009694 activities.add(r1);
9695 }
9696 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009697 } else if ("top".equals(name)) {
9698 synchronized (this) {
9699 final int N = mMainStack.mHistory.size();
9700 if (N > 0) {
9701 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9702 }
9703 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009704 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009705 ItemMatcher matcher = new ItemMatcher();
9706 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009707
9708 synchronized (this) {
9709 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009710 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009711 activities.add(r1);
9712 }
9713 }
9714 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009715 }
9716
9717 if (activities.size() <= 0) {
9718 return false;
9719 }
9720
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009721 String[] newArgs = new String[args.length - opti];
9722 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9723
Dianne Hackborn30d71892010-12-11 10:37:55 -08009724 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009725 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009726 for (int i=activities.size()-1; i>=0; i--) {
9727 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009728 if (needSep) {
9729 pw.println();
9730 }
9731 needSep = true;
9732 synchronized (this) {
9733 if (lastTask != r.task) {
9734 lastTask = r.task;
9735 pw.print("TASK "); pw.print(lastTask.affinity);
9736 pw.print(" id="); pw.println(lastTask.taskId);
9737 if (dumpAll) {
9738 lastTask.dump(pw, " ");
9739 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009740 }
9741 }
9742 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009743 }
9744 return true;
9745 }
9746
9747 /**
9748 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9749 * there is a thread associated with the activity.
9750 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009751 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009752 final ActivityRecord r, String[] args, boolean dumpAll) {
9753 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009754 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009755 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9756 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9757 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009758 if (r.app != null) pw.println(r.app.pid);
9759 else pw.println("(not running)");
9760 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009761 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009762 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009763 }
9764 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009765 // flush anything that is already in the PrintWriter since the thread is going
9766 // to write to the file descriptor directly
9767 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009768 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009769 TransferPipe tp = new TransferPipe();
9770 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009771 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9772 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009773 tp.go(fd);
9774 } finally {
9775 tp.kill();
9776 }
9777 } catch (IOException e) {
9778 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009779 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009780 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009781 }
9782 }
9783 }
9784
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009785 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009786 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009787 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009788 boolean onlyHistory = false;
9789
9790 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009791 if (opti < args.length && "-s".equals(args[opti])) {
9792 dumpAll = false;
9793 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009794 onlyHistory = true;
9795 dumpPackage = null;
9796 }
9797
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009798 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009799 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009800 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009801 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009802 Iterator it = mRegisteredReceivers.values().iterator();
9803 while (it.hasNext()) {
9804 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009805 if (dumpPackage != null && (r.app == null ||
9806 !dumpPackage.equals(r.app.info.packageName))) {
9807 continue;
9808 }
9809 if (!printed) {
9810 pw.println(" Registered Receivers:");
9811 needSep = true;
9812 printed = true;
9813 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009814 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009815 r.dump(pw, " ");
9816 }
9817 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009818
9819 if (mReceiverResolver.dump(pw, needSep ?
9820 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9821 " ", dumpPackage, false)) {
9822 needSep = true;
9823 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009824 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009825
9826 for (BroadcastQueue q : mBroadcastQueues) {
9827 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009829
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009830 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009831
Dianne Hackborn786b4402012-08-27 15:14:02 -07009832 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009833 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9834 if (needSep) {
9835 pw.println();
9836 }
9837 needSep = true;
9838 pw.print(" Sticky broadcasts for user ");
9839 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9840 StringBuilder sb = new StringBuilder(128);
9841 for (Map.Entry<String, ArrayList<Intent>> ent
9842 : mStickyBroadcasts.valueAt(user).entrySet()) {
9843 pw.print(" * Sticky action "); pw.print(ent.getKey());
9844 if (dumpAll) {
9845 pw.println(":");
9846 ArrayList<Intent> intents = ent.getValue();
9847 final int N = intents.size();
9848 for (int i=0; i<N; i++) {
9849 sb.setLength(0);
9850 sb.append(" Intent: ");
9851 intents.get(i).toShortString(sb, false, true, false, false);
9852 pw.println(sb.toString());
9853 Bundle bundle = intents.get(i).getExtras();
9854 if (bundle != null) {
9855 pw.print(" ");
9856 pw.println(bundle.toString());
9857 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009858 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009859 } else {
9860 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009861 }
9862 }
9863 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009864 }
9865
Dianne Hackborn786b4402012-08-27 15:14:02 -07009866 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009867 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009868 for (BroadcastQueue queue : mBroadcastQueues) {
9869 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9870 + queue.mBroadcastsScheduled);
9871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009872 pw.println(" mHandler:");
9873 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009874 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009875 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009876
9877 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009878 }
9879
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009880 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009881 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009882 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009883
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009884 ItemMatcher matcher = new ItemMatcher();
9885 matcher.build(args, opti);
9886
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009887 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009888
9889 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009890
9891 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009892 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009893 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009894 ContentProviderRecord r = mLaunchingProviders.get(i);
9895 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9896 continue;
9897 }
9898 if (!printed) {
9899 if (needSep) pw.println(" ");
9900 needSep = true;
9901 pw.println(" Launching content providers:");
9902 printed = true;
9903 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009904 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009905 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009906 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009907 }
9908
9909 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009910 if (needSep) pw.println();
9911 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009912 pw.println("Granted Uri Permissions:");
9913 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9914 int uid = mGrantedUriPermissions.keyAt(i);
9915 HashMap<Uri, UriPermission> perms
9916 = mGrantedUriPermissions.valueAt(i);
9917 pw.print(" * UID "); pw.print(uid);
9918 pw.println(" holds:");
9919 for (UriPermission perm : perms.values()) {
9920 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009921 if (dumpAll) {
9922 perm.dump(pw, " ");
9923 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009924 }
9925 }
9926 needSep = true;
9927 }
9928
9929 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009930 }
9931
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009932 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009933 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009934 boolean needSep = false;
9935
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009936 if (mIntentSenderRecords.size() > 0) {
9937 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009938 Iterator<WeakReference<PendingIntentRecord>> it
9939 = mIntentSenderRecords.values().iterator();
9940 while (it.hasNext()) {
9941 WeakReference<PendingIntentRecord> ref = it.next();
9942 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009943 if (dumpPackage != null && (rec == null
9944 || !dumpPackage.equals(rec.key.packageName))) {
9945 continue;
9946 }
9947 if (!printed) {
9948 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9949 printed = true;
9950 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009951 needSep = true;
9952 if (rec != null) {
9953 pw.print(" * "); pw.println(rec);
9954 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009956 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009957 } else {
9958 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009959 }
9960 }
9961 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009962
9963 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009964 }
9965
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009966 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009967 String prefix, String label, boolean complete, boolean brief, boolean client,
9968 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009969 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009970 boolean needNL = false;
9971 final String innerPrefix = prefix + " ";
9972 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009973 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009974 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009975 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9976 continue;
9977 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009978 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009979 if (needNL) {
9980 pw.println(" ");
9981 needNL = false;
9982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009983 if (lastTask != r.task) {
9984 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009985 pw.print(prefix);
9986 pw.print(full ? "* " : " ");
9987 pw.println(lastTask);
9988 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009989 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009990 } else if (complete) {
9991 // Complete + brief == give a summary. Isn't that obvious?!?
9992 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009993 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009994 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009995 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009997 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009998 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9999 pw.print(" #"); pw.print(i); pw.print(": ");
10000 pw.println(r);
10001 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010002 r.dump(pw, innerPrefix);
10003 } else if (complete) {
10004 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010005 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010006 if (r.app != null) {
10007 pw.print(innerPrefix); pw.println(r.app);
10008 }
10009 }
10010 if (client && r.app != null && r.app.thread != null) {
10011 // flush anything that is already in the PrintWriter since the thread is going
10012 // to write to the file descriptor directly
10013 pw.flush();
10014 try {
10015 TransferPipe tp = new TransferPipe();
10016 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010017 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10018 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010019 // Short timeout, since blocking here can
10020 // deadlock with the application.
10021 tp.go(fd, 2000);
10022 } finally {
10023 tp.kill();
10024 }
10025 } catch (IOException e) {
10026 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10027 } catch (RemoteException e) {
10028 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10029 }
10030 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010032 }
10033 }
10034
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010035 private static String buildOomTag(String prefix, String space, int val, int base) {
10036 if (val == base) {
10037 if (space == null) return prefix;
10038 return prefix + " ";
10039 }
10040 return prefix + "+" + Integer.toString(val-base);
10041 }
10042
10043 private static final int dumpProcessList(PrintWriter pw,
10044 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010045 String prefix, String normalLabel, String persistentLabel,
10046 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010048 final int N = list.size()-1;
10049 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010050 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010051 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10052 continue;
10053 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010054 pw.println(String.format("%s%s #%2d: %s",
10055 prefix, (r.persistent ? persistentLabel : normalLabel),
10056 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010057 if (r.persistent) {
10058 numPers++;
10059 }
10060 }
10061 return numPers;
10062 }
10063
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010064 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010065 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010066 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010067 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010068
Dianne Hackborn905577f2011-09-07 18:31:28 -070010069 ArrayList<Pair<ProcessRecord, Integer>> list
10070 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10071 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010072 ProcessRecord r = origList.get(i);
10073 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10074 continue;
10075 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010076 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10077 }
10078
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010079 if (list.size() <= 0) {
10080 return false;
10081 }
10082
Dianne Hackborn905577f2011-09-07 18:31:28 -070010083 Comparator<Pair<ProcessRecord, Integer>> comparator
10084 = new Comparator<Pair<ProcessRecord, Integer>>() {
10085 @Override
10086 public int compare(Pair<ProcessRecord, Integer> object1,
10087 Pair<ProcessRecord, Integer> object2) {
10088 if (object1.first.setAdj != object2.first.setAdj) {
10089 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10090 }
10091 if (object1.second.intValue() != object2.second.intValue()) {
10092 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10093 }
10094 return 0;
10095 }
10096 };
10097
10098 Collections.sort(list, comparator);
10099
Dianne Hackborn287952c2010-09-22 22:34:31 -070010100 final long curRealtime = SystemClock.elapsedRealtime();
10101 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10102 final long curUptime = SystemClock.uptimeMillis();
10103 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10104
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010105 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010106 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010107 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010108 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010109 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010110 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10111 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010112 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10113 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010114 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10115 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010116 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10117 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010118 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010119 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010120 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10121 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10122 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10123 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10124 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10125 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10126 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10127 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010128 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10129 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010130 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10131 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010132 } else {
10133 oomAdj = Integer.toString(r.setAdj);
10134 }
10135 String schedGroup;
10136 switch (r.setSchedGroup) {
10137 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10138 schedGroup = "B";
10139 break;
10140 case Process.THREAD_GROUP_DEFAULT:
10141 schedGroup = "F";
10142 break;
10143 default:
10144 schedGroup = Integer.toString(r.setSchedGroup);
10145 break;
10146 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010147 String foreground;
10148 if (r.foregroundActivities) {
10149 foreground = "A";
10150 } else if (r.foregroundServices) {
10151 foreground = "S";
10152 } else {
10153 foreground = " ";
10154 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010155 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010156 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010157 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10158 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010159 if (r.adjSource != null || r.adjTarget != null) {
10160 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010161 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010162 if (r.adjTarget instanceof ComponentName) {
10163 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10164 } else if (r.adjTarget != null) {
10165 pw.print(r.adjTarget.toString());
10166 } else {
10167 pw.print("{null}");
10168 }
10169 pw.print("<=");
10170 if (r.adjSource instanceof ProcessRecord) {
10171 pw.print("Proc{");
10172 pw.print(((ProcessRecord)r.adjSource).toShortString());
10173 pw.println("}");
10174 } else if (r.adjSource != null) {
10175 pw.println(r.adjSource.toString());
10176 } else {
10177 pw.println("{null}");
10178 }
10179 }
10180 if (inclDetails) {
10181 pw.print(prefix);
10182 pw.print(" ");
10183 pw.print("oom: max="); pw.print(r.maxAdj);
10184 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010185 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010186 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010187 pw.print(" curRaw="); pw.print(r.curRawAdj);
10188 pw.print(" setRaw="); pw.print(r.setRawAdj);
10189 pw.print(" cur="); pw.print(r.curAdj);
10190 pw.print(" set="); pw.println(r.setAdj);
10191 pw.print(prefix);
10192 pw.print(" ");
10193 pw.print("keeping="); pw.print(r.keeping);
10194 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010195 pw.print(" empty="); pw.print(r.empty);
10196 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010197
10198 if (!r.keeping) {
10199 if (r.lastWakeTime != 0) {
10200 long wtime;
10201 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10202 synchronized (stats) {
10203 wtime = stats.getProcessWakeTime(r.info.uid,
10204 r.pid, curRealtime);
10205 }
10206 long timeUsed = wtime - r.lastWakeTime;
10207 pw.print(prefix);
10208 pw.print(" ");
10209 pw.print("keep awake over ");
10210 TimeUtils.formatDuration(realtimeSince, pw);
10211 pw.print(" used ");
10212 TimeUtils.formatDuration(timeUsed, pw);
10213 pw.print(" (");
10214 pw.print((timeUsed*100)/realtimeSince);
10215 pw.println("%)");
10216 }
10217 if (r.lastCpuTime != 0) {
10218 long timeUsed = r.curCpuTime - r.lastCpuTime;
10219 pw.print(prefix);
10220 pw.print(" ");
10221 pw.print("run cpu over ");
10222 TimeUtils.formatDuration(uptimeSince, pw);
10223 pw.print(" used ");
10224 TimeUtils.formatDuration(timeUsed, pw);
10225 pw.print(" (");
10226 pw.print((timeUsed*100)/uptimeSince);
10227 pw.println("%)");
10228 }
10229 }
10230 }
10231 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010232 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010233 }
10234
Dianne Hackbornb437e092011-08-05 17:50:29 -070010235 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010236 ArrayList<ProcessRecord> procs;
10237 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010238 if (args != null && args.length > start
10239 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010240 procs = new ArrayList<ProcessRecord>();
10241 int pid = -1;
10242 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010243 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010244 } catch (NumberFormatException e) {
10245
10246 }
10247 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10248 ProcessRecord proc = mLruProcesses.get(i);
10249 if (proc.pid == pid) {
10250 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010251 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010252 procs.add(proc);
10253 }
10254 }
10255 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010256 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010257 return null;
10258 }
10259 } else {
10260 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10261 }
10262 }
10263 return procs;
10264 }
10265
10266 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10267 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010268 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010269 if (procs == null) {
10270 return;
10271 }
10272
10273 long uptime = SystemClock.uptimeMillis();
10274 long realtime = SystemClock.elapsedRealtime();
10275 pw.println("Applications Graphics Acceleration Info:");
10276 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10277
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010278 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10279 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010280 if (r.thread != null) {
10281 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10282 pw.flush();
10283 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010284 TransferPipe tp = new TransferPipe();
10285 try {
10286 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10287 tp.go(fd);
10288 } finally {
10289 tp.kill();
10290 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010291 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010292 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010293 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010294 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010295 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010296 pw.flush();
10297 }
10298 }
10299 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010300 }
10301
Jeff Brown6754ba22011-12-14 20:20:01 -080010302 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10303 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10304 if (procs == null) {
10305 return;
10306 }
10307
10308 pw.println("Applications Database Info:");
10309
10310 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10311 ProcessRecord r = procs.get(i);
10312 if (r.thread != null) {
10313 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10314 pw.flush();
10315 try {
10316 TransferPipe tp = new TransferPipe();
10317 try {
10318 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10319 tp.go(fd);
10320 } finally {
10321 tp.kill();
10322 }
10323 } catch (IOException e) {
10324 pw.println("Failure while dumping the app: " + r);
10325 pw.flush();
10326 } catch (RemoteException e) {
10327 pw.println("Got a RemoteException while dumping the app " + r);
10328 pw.flush();
10329 }
10330 }
10331 }
10332 }
10333
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010334 final static class MemItem {
10335 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010336 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010337 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010338 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010339 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010340
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010341 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010342 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010343 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010344 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010345 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010346 }
10347 }
10348
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010349 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350 boolean sort) {
10351 if (sort) {
10352 Collections.sort(items, new Comparator<MemItem>() {
10353 @Override
10354 public int compare(MemItem lhs, MemItem rhs) {
10355 if (lhs.pss < rhs.pss) {
10356 return 1;
10357 } else if (lhs.pss > rhs.pss) {
10358 return -1;
10359 }
10360 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010361 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010362 });
10363 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010364
10365 for (int i=0; i<items.size(); i++) {
10366 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010367 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010368 if (mi.subitems != null) {
10369 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10370 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010371 }
10372 }
10373
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010374 // These are in KB.
10375 static final long[] DUMP_MEM_BUCKETS = new long[] {
10376 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10377 120*1024, 160*1024, 200*1024,
10378 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10379 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10380 };
10381
Dianne Hackborn672342c2011-11-29 11:29:02 -080010382 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10383 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010384 int start = label.lastIndexOf('.');
10385 if (start >= 0) start++;
10386 else start = 0;
10387 int end = label.length();
10388 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10389 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10390 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10391 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010392 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010393 out.append(label, start, end);
10394 return;
10395 }
10396 }
10397 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010398 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010399 out.append(label, start, end);
10400 }
10401
10402 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10403 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10404 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10405 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10406 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10407 };
10408 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10409 "System", "Persistent", "Foreground",
10410 "Visible", "Perceptible", "Heavy Weight",
10411 "Backup", "A Services", "Home", "Previous",
10412 "B Services", "Background"
10413 };
10414
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010415 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010416 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010417 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010418 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010419 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010420
10421 int opti = 0;
10422 while (opti < args.length) {
10423 String opt = args[opti];
10424 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10425 break;
10426 }
10427 opti++;
10428 if ("-a".equals(opt)) {
10429 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010430 } else if ("--oom".equals(opt)) {
10431 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010432 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010433 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010434 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010435 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010436 pw.println("If [process] is specified it can be the name or ");
10437 pw.println("pid of a specific process to dump.");
10438 return;
10439 } else {
10440 pw.println("Unknown argument: " + opt + "; use -h for help");
10441 }
10442 }
10443
10444 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010445 if (procs == null) {
10446 return;
10447 }
10448
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010449 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010450 long uptime = SystemClock.uptimeMillis();
10451 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010452
10453 if (procs.size() == 1 || isCheckinRequest) {
10454 dumpAll = true;
10455 }
10456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457 if (isCheckinRequest) {
10458 // short checkin version
10459 pw.println(uptime + "," + realtime);
10460 pw.flush();
10461 } else {
10462 pw.println("Applications Memory Usage (kB):");
10463 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10464 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010465
Dianne Hackbornb437e092011-08-05 17:50:29 -070010466 String[] innerArgs = new String[args.length-opti];
10467 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10468
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010469 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10470 long nativePss=0, dalvikPss=0, otherPss=0;
10471 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10472
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010473 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10474 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10475 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010476
10477 long totalPss = 0;
10478
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010479 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10480 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010481 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010482 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10484 pw.flush();
10485 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010486 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010487 if (dumpAll) {
10488 try {
10489 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10490 } catch (RemoteException e) {
10491 if (!isCheckinRequest) {
10492 pw.println("Got RemoteException!");
10493 pw.flush();
10494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010495 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010496 } else {
10497 mi = new Debug.MemoryInfo();
10498 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010500
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010501 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010502 long myTotalPss = mi.getTotalPss();
10503 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010504 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010505 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010506 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010507
10508 nativePss += mi.nativePss;
10509 dalvikPss += mi.dalvikPss;
10510 otherPss += mi.otherPss;
10511 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10512 long mem = mi.getOtherPss(j);
10513 miscPss[j] += mem;
10514 otherPss -= mem;
10515 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010516
10517 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010518 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10519 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010520 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010521 if (oomProcs[oomIndex] == null) {
10522 oomProcs[oomIndex] = new ArrayList<MemItem>();
10523 }
10524 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010525 break;
10526 }
10527 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 }
10530 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010531
10532 if (!isCheckinRequest && procs.size() > 1) {
10533 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10534
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010535 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10536 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10537 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010538 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010539 String label = Debug.MemoryInfo.getOtherLabel(j);
10540 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010541 }
10542
Dianne Hackbornb437e092011-08-05 17:50:29 -070010543 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10544 for (int j=0; j<oomPss.length; j++) {
10545 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010546 String label = DUMP_MEM_OOM_LABEL[j];
10547 MemItem item = new MemItem(label, label, oomPss[j],
10548 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010549 item.subitems = oomProcs[j];
10550 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010551 }
10552 }
10553
Dianne Hackborn672342c2011-11-29 11:29:02 -080010554 if (outTag != null || outStack != null) {
10555 if (outTag != null) {
10556 appendMemBucket(outTag, totalPss, "total", false);
10557 }
10558 if (outStack != null) {
10559 appendMemBucket(outStack, totalPss, "total", true);
10560 }
10561 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010562 for (int i=0; i<oomMems.size(); i++) {
10563 MemItem miCat = oomMems.get(i);
10564 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10565 continue;
10566 }
10567 if (miCat.id < ProcessList.SERVICE_ADJ
10568 || miCat.id == ProcessList.HOME_APP_ADJ
10569 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010570 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10571 outTag.append(" / ");
10572 }
10573 if (outStack != null) {
10574 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10575 if (firstLine) {
10576 outStack.append(":");
10577 firstLine = false;
10578 }
10579 outStack.append("\n\t at ");
10580 } else {
10581 outStack.append("$");
10582 }
10583 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010584 for (int j=0; j<miCat.subitems.size(); j++) {
10585 MemItem mi = miCat.subitems.get(j);
10586 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010587 if (outTag != null) {
10588 outTag.append(" ");
10589 }
10590 if (outStack != null) {
10591 outStack.append("$");
10592 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010593 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010594 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10595 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10596 }
10597 if (outStack != null) {
10598 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10599 }
10600 }
10601 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10602 outStack.append("(");
10603 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10604 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10605 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10606 outStack.append(":");
10607 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10608 }
10609 }
10610 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010611 }
10612 }
10613 }
10614 }
10615
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010616 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010617 pw.println();
10618 pw.println("Total PSS by process:");
10619 dumpMemItems(pw, " ", procMems, true);
10620 pw.println();
10621 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010622 pw.println("Total PSS by OOM adjustment:");
10623 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010624 if (!oomOnly) {
10625 PrintWriter out = categoryPw != null ? categoryPw : pw;
10626 out.println();
10627 out.println("Total PSS by category:");
10628 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010629 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010630 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010631 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010632 final int[] SINGLE_LONG_FORMAT = new int[] {
10633 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10634 };
10635 long[] longOut = new long[1];
10636 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10637 SINGLE_LONG_FORMAT, null, longOut, null);
10638 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10639 longOut[0] = 0;
10640 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10641 SINGLE_LONG_FORMAT, null, longOut, null);
10642 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10643 longOut[0] = 0;
10644 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10645 SINGLE_LONG_FORMAT, null, longOut, null);
10646 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10647 longOut[0] = 0;
10648 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10649 SINGLE_LONG_FORMAT, null, longOut, null);
10650 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10651 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10652 pw.print(shared); pw.println(" kB");
10653 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10654 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010656 }
10657
10658 /**
10659 * Searches array of arguments for the specified string
10660 * @param args array of argument strings
10661 * @param value value to search for
10662 * @return true if the value is contained in the array
10663 */
10664 private static boolean scanArgs(String[] args, String value) {
10665 if (args != null) {
10666 for (String arg : args) {
10667 if (value.equals(arg)) {
10668 return true;
10669 }
10670 }
10671 }
10672 return false;
10673 }
10674
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010675 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10676 ContentProviderRecord cpr, boolean always) {
10677 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10678
10679 if (!inLaunching || always) {
10680 synchronized (cpr) {
10681 cpr.launchingApp = null;
10682 cpr.notifyAll();
10683 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010684 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010685 String names[] = cpr.info.authority.split(";");
10686 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010687 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 }
10689 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010690
10691 for (int i=0; i<cpr.connections.size(); i++) {
10692 ContentProviderConnection conn = cpr.connections.get(i);
10693 if (conn.waiting) {
10694 // If this connection is waiting for the provider, then we don't
10695 // need to mess with its process unless we are always removing
10696 // or for some reason the provider is not currently launching.
10697 if (inLaunching && !always) {
10698 continue;
10699 }
10700 }
10701 ProcessRecord capp = conn.client;
10702 conn.dead = true;
10703 if (conn.stableCount > 0) {
10704 if (!capp.persistent && capp.thread != null
10705 && capp.pid != 0
10706 && capp.pid != MY_PID) {
10707 Slog.i(TAG, "Kill " + capp.processName
10708 + " (pid " + capp.pid + "): provider " + cpr.info.name
10709 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010710 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010711 capp.processName, capp.setAdj, "dying provider "
10712 + cpr.name.toShortString());
10713 Process.killProcessQuiet(capp.pid);
10714 }
10715 } else if (capp.thread != null && conn.provider.provider != null) {
10716 try {
10717 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10718 } catch (RemoteException e) {
10719 }
10720 // In the protocol here, we don't expect the client to correctly
10721 // clean up this connection, we'll just remove it.
10722 cpr.connections.remove(i);
10723 conn.client.conProviders.remove(conn);
10724 }
10725 }
10726
10727 if (inLaunching && always) {
10728 mLaunchingProviders.remove(cpr);
10729 }
10730 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010731 }
10732
10733 /**
10734 * Main code for cleaning up a process when it has gone away. This is
10735 * called both as a result of the process dying, or directly when stopping
10736 * a process when running in single process mode.
10737 */
10738 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010739 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010740 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010741 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 }
10743
Dianne Hackborn36124872009-10-08 16:22:03 -070010744 mProcessesToGc.remove(app);
10745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 // Dismiss any open dialogs.
10747 if (app.crashDialog != null) {
10748 app.crashDialog.dismiss();
10749 app.crashDialog = null;
10750 }
10751 if (app.anrDialog != null) {
10752 app.anrDialog.dismiss();
10753 app.anrDialog = null;
10754 }
10755 if (app.waitDialog != null) {
10756 app.waitDialog.dismiss();
10757 app.waitDialog = null;
10758 }
10759
10760 app.crashing = false;
10761 app.notResponding = false;
10762
10763 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010764 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 app.thread = null;
10766 app.forcingToForeground = null;
10767 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010768 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010769 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010770 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010772 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010773
10774 boolean restart = false;
10775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 // Remove published content providers.
10777 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010778 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010780 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010781
10782 final boolean always = app.bad || !allowRestart;
10783 if (removeDyingProviderLocked(app, cpr, always) || always) {
10784 // We left the provider in the launching list, need to
10785 // restart it.
10786 restart = true;
10787 }
10788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010790 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 }
10792 app.pubProviders.clear();
10793 }
10794
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010795 // Take care of any launching providers waiting for this process.
10796 if (checkAppInLaunchingProvidersLocked(app, false)) {
10797 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010798 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010800 // Unregister from connected content providers.
10801 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010802 for (int i=0; i<app.conProviders.size(); i++) {
10803 ContentProviderConnection conn = app.conProviders.get(i);
10804 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010805 }
10806 app.conProviders.clear();
10807 }
10808
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010809 // At this point there may be remaining entries in mLaunchingProviders
10810 // where we were the only one waiting, so they are no longer of use.
10811 // Look for these and clean up if found.
10812 // XXX Commented out for now. Trying to figure out a way to reproduce
10813 // the actual situation to identify what is actually going on.
10814 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010815 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010816 ContentProviderRecord cpr = (ContentProviderRecord)
10817 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010818 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010819 synchronized (cpr) {
10820 cpr.launchingApp = null;
10821 cpr.notifyAll();
10822 }
10823 }
10824 }
10825 }
10826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010827 skipCurrentReceiverLocked(app);
10828
10829 // Unregister any receivers.
10830 if (app.receivers.size() > 0) {
10831 Iterator<ReceiverList> it = app.receivers.iterator();
10832 while (it.hasNext()) {
10833 removeReceiverLocked(it.next());
10834 }
10835 app.receivers.clear();
10836 }
10837
Christopher Tate181fafa2009-05-14 11:12:14 -070010838 // If the app is undergoing backup, tell the backup manager about it
10839 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010840 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10841 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010842 try {
10843 IBackupManager bm = IBackupManager.Stub.asInterface(
10844 ServiceManager.getService(Context.BACKUP_SERVICE));
10845 bm.agentDisconnected(app.info.packageName);
10846 } catch (RemoteException e) {
10847 // can't happen; backup manager is local
10848 }
10849 }
10850
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010851 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10852 ProcessChangeItem item = mPendingProcessChanges.get(i);
10853 if (item.pid == app.pid) {
10854 mPendingProcessChanges.remove(i);
10855 mAvailProcessChanges.add(item);
10856 }
10857 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010858 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 // If the caller is restarting this app, then leave it in its
10861 // current lists and let the caller take care of it.
10862 if (restarting) {
10863 return;
10864 }
10865
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010866 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010867 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010869 mProcessNames.remove(app.processName, app.uid);
10870 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010871 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010872 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10873 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010874 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010876 } else if (!app.removed) {
10877 // This app is persistent, so we need to keep its record around.
10878 // If it is not already on the pending app list, add it there
10879 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10881 mPersistentStartingProcesses.add(app);
10882 restart = true;
10883 }
10884 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010885 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010886 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 mProcessesOnHold.remove(app);
10888
The Android Open Source Project4df24232009-03-05 14:34:35 -080010889 if (app == mHomeProcess) {
10890 mHomeProcess = null;
10891 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010892 if (app == mPreviousProcess) {
10893 mPreviousProcess = null;
10894 }
10895
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010896 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 // We have components that still need to be running in the
10898 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010899 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010900 startProcessLocked(app, "restart", app.processName);
10901 } else if (app.pid > 0 && app.pid != MY_PID) {
10902 // Goodbye!
10903 synchronized (mPidsSelfLocked) {
10904 mPidsSelfLocked.remove(app.pid);
10905 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10906 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010907 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010908 }
10909 }
10910
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010911 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10912 // Look through the content providers we are waiting to have launched,
10913 // and if any run in this process then either schedule a restart of
10914 // the process or kill the client waiting for it if this process has
10915 // gone bad.
10916 int NL = mLaunchingProviders.size();
10917 boolean restart = false;
10918 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010919 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010920 if (cpr.launchingApp == app) {
10921 if (!alwaysBad && !app.bad) {
10922 restart = true;
10923 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010924 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010925 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010926 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010927 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010928 }
10929 }
10930 }
10931 return restart;
10932 }
10933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 // =========================================================
10935 // SERVICES
10936 // =========================================================
10937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10939 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010940 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010942 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010943 }
10944 }
10945
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010946 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010947 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010948 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010949 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010950 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010951 }
10952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010954 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010955 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 // Refuse possible leaked file descriptors
10957 if (service != null && service.hasFileDescriptors() == true) {
10958 throw new IllegalArgumentException("File descriptors passed in Intent");
10959 }
10960
Amith Yamasani742a6712011-05-04 14:49:28 -070010961 if (DEBUG_SERVICE)
10962 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 synchronized(this) {
10964 final int callingPid = Binder.getCallingPid();
10965 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010966 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010967 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010968 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010969 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 Binder.restoreCallingIdentity(origId);
10971 return res;
10972 }
10973 }
10974
10975 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010976 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010978 if (DEBUG_SERVICE)
10979 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010981 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010982 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010983 Binder.restoreCallingIdentity(origId);
10984 return res;
10985 }
10986 }
10987
10988 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010989 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010990 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 // Refuse possible leaked file descriptors
10992 if (service != null && service.hasFileDescriptors() == true) {
10993 throw new IllegalArgumentException("File descriptors passed in Intent");
10994 }
10995
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010996 checkValidCaller(Binder.getCallingUid(), userId);
10997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010998 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010999 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 }
11002
11003 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011004 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011005 // Refuse possible leaked file descriptors
11006 if (service != null && service.hasFileDescriptors() == true) {
11007 throw new IllegalArgumentException("File descriptors passed in Intent");
11008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011010 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 }
11013
11014 public boolean stopServiceToken(ComponentName className, IBinder token,
11015 int startId) {
11016 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011017 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011019 }
11020
11021 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011022 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011024 mServices.setServiceForegroundLocked(className, token, id, notification,
11025 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 }
11027 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011028
Dianne Hackborn41203752012-08-31 14:05:51 -070011029 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11030 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011031 final int callingUserId = UserHandle.getUserId(callingUid);
11032 if (callingUserId != userId) {
11033 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11034 if ((requireFull || checkComponentPermission(
11035 android.Manifest.permission.INTERACT_ACROSS_USERS,
11036 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
11037 && checkComponentPermission(
11038 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11039 callingPid, callingUid, -1, true)
11040 != PackageManager.PERMISSION_GRANTED) {
11041 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11042 // In this case, they would like to just execute as their
11043 // owner user instead of failing.
11044 userId = callingUserId;
11045 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011046 StringBuilder builder = new StringBuilder(128);
11047 builder.append("Permission Denial: ");
11048 builder.append(name);
11049 if (callerPackage != null) {
11050 builder.append(" from ");
11051 builder.append(callerPackage);
11052 }
11053 builder.append(" asks to run as user ");
11054 builder.append(userId);
11055 builder.append(" but is calling from user ");
11056 builder.append(UserHandle.getUserId(callingUid));
11057 builder.append("; this requires ");
11058 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11059 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011060 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011061 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11062 }
11063 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011064 Slog.w(TAG, msg);
11065 throw new SecurityException(msg);
11066 }
11067 }
11068 }
11069 if (userId == UserHandle.USER_CURRENT
11070 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011071 // Note that we may be accessing this outside of a lock...
11072 // shouldn't be a big deal, if this is being called outside
11073 // of a locked context there is intrinsically a race with
11074 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011075 userId = mCurrentUserId;
11076 }
11077 if (!allowAll && userId < 0) {
11078 throw new IllegalArgumentException(
11079 "Call does not support special user #" + userId);
11080 }
11081 }
11082 return userId;
11083 }
11084
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011085 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11086 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011087 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011088 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011089 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11090 if (ActivityManager.checkUidPermission(
11091 android.Manifest.permission.INTERACT_ACROSS_USERS,
11092 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11093 ComponentName comp = new ComponentName(aInfo.packageName, className);
11094 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11095 + " requests FLAG_SINGLE_USER, but app does not hold "
11096 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11097 Slog.w(TAG, msg);
11098 throw new SecurityException(msg);
11099 }
11100 result = true;
11101 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011102 } else if (componentProcessName == aInfo.packageName) {
11103 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11104 } else if ("system".equals(componentProcessName)) {
11105 result = true;
11106 }
11107 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011108 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11109 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011110 }
11111 return result;
11112 }
11113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 public int bindService(IApplicationThread caller, IBinder token,
11115 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011116 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011117 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 // Refuse possible leaked file descriptors
11119 if (service != null && service.hasFileDescriptors() == true) {
11120 throw new IllegalArgumentException("File descriptors passed in Intent");
11121 }
11122
11123 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011124 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11125 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 }
11127 }
11128
11129 public boolean unbindService(IServiceConnection connection) {
11130 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011131 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133 }
11134
11135 public void publishService(IBinder token, Intent intent, IBinder service) {
11136 // Refuse possible leaked file descriptors
11137 if (intent != null && intent.hasFileDescriptors() == true) {
11138 throw new IllegalArgumentException("File descriptors passed in Intent");
11139 }
11140
11141 synchronized(this) {
11142 if (!(token instanceof ServiceRecord)) {
11143 throw new IllegalArgumentException("Invalid service token");
11144 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011145 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 }
11147 }
11148
11149 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11150 // Refuse possible leaked file descriptors
11151 if (intent != null && intent.hasFileDescriptors() == true) {
11152 throw new IllegalArgumentException("File descriptors passed in Intent");
11153 }
11154
11155 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011156 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011157 }
11158 }
11159
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011160 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 synchronized(this) {
11162 if (!(token instanceof ServiceRecord)) {
11163 throw new IllegalArgumentException("Invalid service token");
11164 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011165 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 }
11168
11169 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011170 // BACKUP AND RESTORE
11171 // =========================================================
11172
11173 // Cause the target app to be launched if necessary and its backup agent
11174 // instantiated. The backup agent will invoke backupAgentCreated() on the
11175 // activity manager to announce its creation.
11176 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011177 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11178 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011179
11180 synchronized(this) {
11181 // !!! TODO: currently no check here that we're already bound
11182 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11183 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11184 synchronized (stats) {
11185 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11186 }
11187
Dianne Hackborne7f97212011-02-24 14:40:20 -080011188 // Backup agent is now in use, its package can't be stopped.
11189 try {
11190 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011191 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011192 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011193 } catch (IllegalArgumentException e) {
11194 Slog.w(TAG, "Failed trying to unstop package "
11195 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011196 }
11197
Christopher Tate181fafa2009-05-14 11:12:14 -070011198 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011199 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11200 ? new ComponentName(app.packageName, app.backupAgentName)
11201 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011202 // startProcessLocked() returns existing proc's record if it's already running
11203 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011204 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011205 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011206 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011207 return false;
11208 }
11209
11210 r.app = proc;
11211 mBackupTarget = r;
11212 mBackupAppName = app.packageName;
11213
Christopher Tate6fa95972009-06-05 18:43:55 -070011214 // Try not to kill the process during backup
11215 updateOomAdjLocked(proc);
11216
Christopher Tate181fafa2009-05-14 11:12:14 -070011217 // If the process is already attached, schedule the creation of the backup agent now.
11218 // If it is not yet live, this will be done when it attaches to the framework.
11219 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011220 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011221 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011222 proc.thread.scheduleCreateBackupAgent(app,
11223 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011224 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011225 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011226 }
11227 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011228 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011229 }
11230 // Invariants: at this point, the target app process exists and the application
11231 // is either already running or in the process of coming up. mBackupTarget and
11232 // mBackupAppName describe the app, so that when it binds back to the AM we
11233 // know that it's scheduled for a backup-agent operation.
11234 }
11235
11236 return true;
11237 }
11238
Christopher Tate346acb12012-10-15 19:20:25 -070011239 @Override
11240 public void clearPendingBackup() {
11241 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11242 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11243
11244 synchronized (this) {
11245 mBackupTarget = null;
11246 mBackupAppName = null;
11247 }
11248 }
11249
Christopher Tate181fafa2009-05-14 11:12:14 -070011250 // A backup agent has just come up
11251 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011252 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011253 + " = " + agent);
11254
11255 synchronized(this) {
11256 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011257 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011258 return;
11259 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011260 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011261
Dianne Hackborn06740692010-09-22 22:46:21 -070011262 long oldIdent = Binder.clearCallingIdentity();
11263 try {
11264 IBackupManager bm = IBackupManager.Stub.asInterface(
11265 ServiceManager.getService(Context.BACKUP_SERVICE));
11266 bm.agentConnected(agentPackageName, agent);
11267 } catch (RemoteException e) {
11268 // can't happen; the backup manager service is local
11269 } catch (Exception e) {
11270 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11271 e.printStackTrace();
11272 } finally {
11273 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011274 }
11275 }
11276
11277 // done with this agent
11278 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011279 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011280 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011281 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011282 return;
11283 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011284
11285 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011286 try {
11287 if (mBackupAppName == null) {
11288 Slog.w(TAG, "Unbinding backup agent with no active backup");
11289 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011290 }
Christopher Tate346acb12012-10-15 19:20:25 -070011291
11292 if (!mBackupAppName.equals(appInfo.packageName)) {
11293 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11294 return;
11295 }
11296
11297 // Not backing this app up any more; reset its OOM adjustment
11298 final ProcessRecord proc = mBackupTarget.app;
11299 updateOomAdjLocked(proc);
11300
11301 // If the app crashed during backup, 'thread' will be null here
11302 if (proc.thread != null) {
11303 try {
11304 proc.thread.scheduleDestroyBackupAgent(appInfo,
11305 compatibilityInfoForPackageLocked(appInfo));
11306 } catch (Exception e) {
11307 Slog.e(TAG, "Exception when unbinding backup agent:");
11308 e.printStackTrace();
11309 }
11310 }
11311 } finally {
11312 mBackupTarget = null;
11313 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011314 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011315 }
11316 }
11317 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 // BROADCASTS
11319 // =========================================================
11320
Josh Bartel7f208742010-02-25 11:01:44 -060011321 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011322 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011324 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11325 if (stickies == null) {
11326 return cur;
11327 }
11328 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 if (list == null) {
11330 return cur;
11331 }
11332 int N = list.size();
11333 for (int i=0; i<N; i++) {
11334 Intent intent = list.get(i);
11335 if (filter.match(resolver, intent, true, TAG) >= 0) {
11336 if (cur == null) {
11337 cur = new ArrayList<Intent>();
11338 }
11339 cur.add(intent);
11340 }
11341 }
11342 return cur;
11343 }
11344
Christopher Tatef46723b2012-01-26 14:19:24 -080011345 boolean isPendingBroadcastProcessLocked(int pid) {
11346 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11347 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011349
Christopher Tatef46723b2012-01-26 14:19:24 -080011350 void skipPendingBroadcastLocked(int pid) {
11351 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11352 for (BroadcastQueue queue : mBroadcastQueues) {
11353 queue.skipPendingBroadcastLocked(pid);
11354 }
11355 }
11356
11357 // The app just attached; send any pending broadcasts that it should receive
11358 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11359 boolean didSomething = false;
11360 for (BroadcastQueue queue : mBroadcastQueues) {
11361 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011363 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364 }
11365
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011366 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011367 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011368 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011369 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011370 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011371 synchronized(this) {
11372 ProcessRecord callerApp = null;
11373 if (caller != null) {
11374 callerApp = getRecordForAppLocked(caller);
11375 if (callerApp == null) {
11376 throw new SecurityException(
11377 "Unable to find app for caller " + caller
11378 + " (pid=" + Binder.getCallingPid()
11379 + ") when registering receiver " + receiver);
11380 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011381 if (callerApp.info.uid != Process.SYSTEM_UID &&
11382 !callerApp.pkgList.contains(callerPackage)) {
11383 throw new SecurityException("Given caller package " + callerPackage
11384 + " is not running in process " + callerApp);
11385 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011386 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011387 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011388 } else {
11389 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011390 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011391 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011392 }
11393
Dianne Hackborn139748f2012-09-24 11:36:57 -070011394 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011395 true, true, "registerReceiver", callerPackage);
11396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011397 List allSticky = null;
11398
11399 // Look for any matching sticky broadcasts...
11400 Iterator actions = filter.actionsIterator();
11401 if (actions != null) {
11402 while (actions.hasNext()) {
11403 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011404 allSticky = getStickiesLocked(action, filter, allSticky,
11405 UserHandle.USER_ALL);
11406 allSticky = getStickiesLocked(action, filter, allSticky,
11407 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 }
11409 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011410 allSticky = getStickiesLocked(null, filter, allSticky,
11411 UserHandle.USER_ALL);
11412 allSticky = getStickiesLocked(null, filter, allSticky,
11413 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 }
11415
11416 // The first sticky in the list is returned directly back to
11417 // the client.
11418 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11419
Joe Onorato8a9b2202010-02-26 18:56:32 -080011420 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011421 + ": " + sticky);
11422
11423 if (receiver == null) {
11424 return sticky;
11425 }
11426
11427 ReceiverList rl
11428 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11429 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011430 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11431 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011432 if (rl.app != null) {
11433 rl.app.receivers.add(rl);
11434 } else {
11435 try {
11436 receiver.asBinder().linkToDeath(rl, 0);
11437 } catch (RemoteException e) {
11438 return sticky;
11439 }
11440 rl.linkedToDeath = true;
11441 }
11442 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011443 } else if (rl.uid != callingUid) {
11444 throw new IllegalArgumentException(
11445 "Receiver requested to register for uid " + callingUid
11446 + " was previously registered for uid " + rl.uid);
11447 } else if (rl.pid != callingPid) {
11448 throw new IllegalArgumentException(
11449 "Receiver requested to register for pid " + callingPid
11450 + " was previously registered for pid " + rl.pid);
11451 } else if (rl.userId != userId) {
11452 throw new IllegalArgumentException(
11453 "Receiver requested to register for user " + userId
11454 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011455 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011456 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011457 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 rl.add(bf);
11459 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011460 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 }
11462 mReceiverResolver.addFilter(bf);
11463
11464 // Enqueue broadcasts for all existing stickies that match
11465 // this filter.
11466 if (allSticky != null) {
11467 ArrayList receivers = new ArrayList();
11468 receivers.add(bf);
11469
11470 int N = allSticky.size();
11471 for (int i=0; i<N; i++) {
11472 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011473 BroadcastQueue queue = broadcastQueueForIntent(intent);
11474 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011476 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011477 queue.enqueueParallelBroadcastLocked(r);
11478 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479 }
11480 }
11481
11482 return sticky;
11483 }
11484 }
11485
11486 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011487 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011488
Christopher Tatef46723b2012-01-26 14:19:24 -080011489 final long origId = Binder.clearCallingIdentity();
11490 try {
11491 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492
Christopher Tatef46723b2012-01-26 14:19:24 -080011493 synchronized(this) {
11494 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011495 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011496 if (rl != null) {
11497 if (rl.curBroadcast != null) {
11498 BroadcastRecord r = rl.curBroadcast;
11499 final boolean doNext = finishReceiverLocked(
11500 receiver.asBinder(), r.resultCode, r.resultData,
11501 r.resultExtras, r.resultAbort, true);
11502 if (doNext) {
11503 doTrim = true;
11504 r.queue.processNextBroadcast(false);
11505 }
11506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507
Christopher Tatef46723b2012-01-26 14:19:24 -080011508 if (rl.app != null) {
11509 rl.app.receivers.remove(rl);
11510 }
11511 removeReceiverLocked(rl);
11512 if (rl.linkedToDeath) {
11513 rl.linkedToDeath = false;
11514 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 }
11517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518
Christopher Tatef46723b2012-01-26 14:19:24 -080011519 // If we actually concluded any broadcasts, we might now be able
11520 // to trim the recipients' apps from our working set
11521 if (doTrim) {
11522 trimApplications();
11523 return;
11524 }
11525
11526 } finally {
11527 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011529 }
11530
11531 void removeReceiverLocked(ReceiverList rl) {
11532 mRegisteredReceivers.remove(rl.receiver.asBinder());
11533 int N = rl.size();
11534 for (int i=0; i<N; i++) {
11535 mReceiverResolver.removeFilter(rl.get(i));
11536 }
11537 }
11538
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011539 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011540 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11541 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011542 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011543 try {
11544 r.thread.dispatchPackageBroadcast(cmd, packages);
11545 } catch (RemoteException ex) {
11546 }
11547 }
11548 }
11549 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011550
11551 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11552 int[] users) {
11553 List<ResolveInfo> receivers = null;
11554 try {
11555 HashSet<ComponentName> singleUserReceivers = null;
11556 boolean scannedFirstReceivers = false;
11557 for (int user : users) {
11558 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11559 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011560 if (user != 0 && newReceivers != null) {
11561 // If this is not the primary user, we need to check for
11562 // any receivers that should be filtered out.
11563 for (int i=0; i<newReceivers.size(); i++) {
11564 ResolveInfo ri = newReceivers.get(i);
11565 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11566 newReceivers.remove(i);
11567 i--;
11568 }
11569 }
11570 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011571 if (newReceivers != null && newReceivers.size() == 0) {
11572 newReceivers = null;
11573 }
11574 if (receivers == null) {
11575 receivers = newReceivers;
11576 } else if (newReceivers != null) {
11577 // We need to concatenate the additional receivers
11578 // found with what we have do far. This would be easy,
11579 // but we also need to de-dup any receivers that are
11580 // singleUser.
11581 if (!scannedFirstReceivers) {
11582 // Collect any single user receivers we had already retrieved.
11583 scannedFirstReceivers = true;
11584 for (int i=0; i<receivers.size(); i++) {
11585 ResolveInfo ri = receivers.get(i);
11586 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11587 ComponentName cn = new ComponentName(
11588 ri.activityInfo.packageName, ri.activityInfo.name);
11589 if (singleUserReceivers == null) {
11590 singleUserReceivers = new HashSet<ComponentName>();
11591 }
11592 singleUserReceivers.add(cn);
11593 }
11594 }
11595 }
11596 // Add the new results to the existing results, tracking
11597 // and de-dupping single user receivers.
11598 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011599 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011600 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11601 ComponentName cn = new ComponentName(
11602 ri.activityInfo.packageName, ri.activityInfo.name);
11603 if (singleUserReceivers == null) {
11604 singleUserReceivers = new HashSet<ComponentName>();
11605 }
11606 if (!singleUserReceivers.contains(cn)) {
11607 singleUserReceivers.add(cn);
11608 receivers.add(ri);
11609 }
11610 } else {
11611 receivers.add(ri);
11612 }
11613 }
11614 }
11615 }
11616 } catch (RemoteException ex) {
11617 // pm is in same process, this will never happen.
11618 }
11619 return receivers;
11620 }
11621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 private final int broadcastIntentLocked(ProcessRecord callerApp,
11623 String callerPackage, Intent intent, String resolvedType,
11624 IIntentReceiver resultTo, int resultCode, String resultData,
11625 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011626 boolean ordered, boolean sticky, int callingPid, int callingUid,
11627 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628 intent = new Intent(intent);
11629
Dianne Hackborne7f97212011-02-24 14:40:20 -080011630 // By default broadcasts do not go to stopped apps.
11631 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11632
Joe Onorato8a9b2202010-02-26 18:56:32 -080011633 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011634 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011635 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011637 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011639
Dianne Hackborn139748f2012-09-24 11:36:57 -070011640 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011641 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011642
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011643 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011644 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011645 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011646 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11647 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11648 Slog.w(TAG, "Skipping broadcast of " + intent
11649 + ": user " + userId + " is stopped");
11650 return ActivityManager.BROADCAST_SUCCESS;
11651 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011652 }
11653
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011654 /*
11655 * Prevent non-system code (defined here to be non-persistent
11656 * processes) from sending protected broadcasts.
11657 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011658 int callingAppId = UserHandle.getAppId(callingUid);
11659 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11660 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011661 callingUid == 0) {
11662 // Always okay.
11663 } else if (callerApp == null || !callerApp.persistent) {
11664 try {
11665 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11666 intent.getAction())) {
11667 String msg = "Permission Denial: not allowed to send broadcast "
11668 + intent.getAction() + " from pid="
11669 + callingPid + ", uid=" + callingUid;
11670 Slog.w(TAG, msg);
11671 throw new SecurityException(msg);
11672 }
11673 } catch (RemoteException e) {
11674 Slog.w(TAG, "Remote exception", e);
11675 return ActivityManager.BROADCAST_SUCCESS;
11676 }
11677 }
11678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011679 // Handle special intents: if this broadcast is from the package
11680 // manager about a package being removed, we need to remove all of
11681 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011682 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011683 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011684 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11685 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011686 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 || uidRemoved) {
11688 if (checkComponentPermission(
11689 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011690 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011691 == PackageManager.PERMISSION_GRANTED) {
11692 if (uidRemoved) {
11693 final Bundle intentExtras = intent.getExtras();
11694 final int uid = intentExtras != null
11695 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11696 if (uid >= 0) {
11697 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11698 synchronized (bs) {
11699 bs.removeUidStatsLocked(uid);
11700 }
11701 }
11702 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011703 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011704 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011705 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011706 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11707 if (list != null && (list.length > 0)) {
11708 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011709 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011710 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011711 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011712 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011713 }
11714 } else {
11715 Uri data = intent.getData();
11716 String ssp;
11717 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11718 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11719 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011720 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11721 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011722 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011723 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011724 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011725 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727 }
11728 }
11729 }
11730 } else {
11731 String msg = "Permission Denial: " + intent.getAction()
11732 + " broadcast from " + callerPackage + " (pid=" + callingPid
11733 + ", uid=" + callingUid + ")"
11734 + " requires "
11735 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011736 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737 throw new SecurityException(msg);
11738 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011739
11740 // Special case for adding a package: by default turn on compatibility
11741 // mode.
11742 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011743 Uri data = intent.getData();
11744 String ssp;
11745 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11746 mCompatModePackages.handlePackageAddedLocked(ssp,
11747 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749 }
11750
11751 /*
11752 * If this is the time zone changed action, queue up a message that will reset the timezone
11753 * of all currently running processes. This message will get queued up before the broadcast
11754 * happens.
11755 */
11756 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11757 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11758 }
11759
Robert Greenwalt03595d02010-11-02 14:08:23 -070011760 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11761 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11762 }
11763
Robert Greenwalt434203a2010-10-11 16:00:27 -070011764 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11765 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11766 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11767 }
11768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011769 // Add to the sticky list if requested.
11770 if (sticky) {
11771 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11772 callingPid, callingUid)
11773 != PackageManager.PERMISSION_GRANTED) {
11774 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11775 + callingPid + ", uid=" + callingUid
11776 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011777 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 throw new SecurityException(msg);
11779 }
11780 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011781 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011782 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011783 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011784 }
11785 if (intent.getComponent() != null) {
11786 throw new SecurityException(
11787 "Sticky broadcasts can't target a specific component");
11788 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011789 // We use userId directly here, since the "all" target is maintained
11790 // as a separate set of sticky broadcasts.
11791 if (userId != UserHandle.USER_ALL) {
11792 // But first, if this is not a broadcast to all users, then
11793 // make sure it doesn't conflict with an existing broadcast to
11794 // all users.
11795 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11796 UserHandle.USER_ALL);
11797 if (stickies != null) {
11798 ArrayList<Intent> list = stickies.get(intent.getAction());
11799 if (list != null) {
11800 int N = list.size();
11801 int i;
11802 for (i=0; i<N; i++) {
11803 if (intent.filterEquals(list.get(i))) {
11804 throw new IllegalArgumentException(
11805 "Sticky broadcast " + intent + " for user "
11806 + userId + " conflicts with existing global broadcast");
11807 }
11808 }
11809 }
11810 }
11811 }
11812 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11813 if (stickies == null) {
11814 stickies = new HashMap<String, ArrayList<Intent>>();
11815 mStickyBroadcasts.put(userId, stickies);
11816 }
11817 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 if (list == null) {
11819 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011820 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 }
11822 int N = list.size();
11823 int i;
11824 for (i=0; i<N; i++) {
11825 if (intent.filterEquals(list.get(i))) {
11826 // This sticky already exists, replace it.
11827 list.set(i, new Intent(intent));
11828 break;
11829 }
11830 }
11831 if (i >= N) {
11832 list.add(new Intent(intent));
11833 }
11834 }
11835
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011836 int[] users;
11837 if (userId == UserHandle.USER_ALL) {
11838 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011839 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011840 } else {
11841 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011842 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011843 }
11844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011845 // Figure out who all will receive this broadcast.
11846 List receivers = null;
11847 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011848 // Need to resolve the intent to interested receivers...
11849 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11850 == 0) {
11851 receivers = collectReceiverComponents(intent, resolvedType, users);
11852 }
11853 if (intent.getComponent() == null) {
11854 registeredReceivers = mReceiverResolver.queryIntent(intent,
11855 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 }
11857
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011858 final boolean replacePending =
11859 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11860
Joe Onorato8a9b2202010-02-26 18:56:32 -080011861 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011862 + " replacePending=" + replacePending);
11863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11865 if (!ordered && NR > 0) {
11866 // If we are not serializing this broadcast, then send the
11867 // registered receivers separately so they don't wait for the
11868 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011869 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11870 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011871 callerPackage, callingPid, callingUid, requiredPermission,
11872 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011873 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011874 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011875 TAG, "Enqueueing parallel broadcast " + r);
11876 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011877 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011878 queue.enqueueParallelBroadcastLocked(r);
11879 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881 registeredReceivers = null;
11882 NR = 0;
11883 }
11884
11885 // Merge into one list.
11886 int ir = 0;
11887 if (receivers != null) {
11888 // A special case for PACKAGE_ADDED: do not allow the package
11889 // being added to see this broadcast. This prevents them from
11890 // using this as a back door to get run as soon as they are
11891 // installed. Maybe in the future we want to have a special install
11892 // broadcast or such for apps, but we'd like to deliberately make
11893 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011894 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011895 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11896 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11897 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011898 Uri data = intent.getData();
11899 if (data != null) {
11900 String pkgName = data.getSchemeSpecificPart();
11901 if (pkgName != null) {
11902 skipPackages = new String[] { pkgName };
11903 }
11904 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011905 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011906 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011907 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011908 if (skipPackages != null && (skipPackages.length > 0)) {
11909 for (String skipPackage : skipPackages) {
11910 if (skipPackage != null) {
11911 int NT = receivers.size();
11912 for (int it=0; it<NT; it++) {
11913 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11914 if (curt.activityInfo.packageName.equals(skipPackage)) {
11915 receivers.remove(it);
11916 it--;
11917 NT--;
11918 }
11919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920 }
11921 }
11922 }
11923
11924 int NT = receivers != null ? receivers.size() : 0;
11925 int it = 0;
11926 ResolveInfo curt = null;
11927 BroadcastFilter curr = null;
11928 while (it < NT && ir < NR) {
11929 if (curt == null) {
11930 curt = (ResolveInfo)receivers.get(it);
11931 }
11932 if (curr == null) {
11933 curr = registeredReceivers.get(ir);
11934 }
11935 if (curr.getPriority() >= curt.priority) {
11936 // Insert this broadcast record into the final list.
11937 receivers.add(it, curr);
11938 ir++;
11939 curr = null;
11940 it++;
11941 NT++;
11942 } else {
11943 // Skip to the next ResolveInfo in the final list.
11944 it++;
11945 curt = null;
11946 }
11947 }
11948 }
11949 while (ir < NR) {
11950 if (receivers == null) {
11951 receivers = new ArrayList();
11952 }
11953 receivers.add(registeredReceivers.get(ir));
11954 ir++;
11955 }
11956
11957 if ((receivers != null && receivers.size() > 0)
11958 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011959 BroadcastQueue queue = broadcastQueueForIntent(intent);
11960 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011962 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011963 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011964 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011965 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011966 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011967 if (DEBUG_BROADCAST) {
11968 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011969 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011971 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011972 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011973 queue.enqueueOrderedBroadcastLocked(r);
11974 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011976 }
11977
Dianne Hackborna4972e92012-03-14 10:38:05 -070011978 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 }
11980
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011981 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 // Refuse possible leaked file descriptors
11983 if (intent != null && intent.hasFileDescriptors() == true) {
11984 throw new IllegalArgumentException("File descriptors passed in Intent");
11985 }
11986
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011987 int flags = intent.getFlags();
11988
11989 if (!mProcessesReady) {
11990 // if the caller really truly claims to know what they're doing, go
11991 // ahead and allow the broadcast without launching any receivers
11992 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11993 intent = new Intent(intent);
11994 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11995 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11996 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11997 + " before boot completion");
11998 throw new IllegalStateException("Cannot broadcast before boot completed");
11999 }
12000 }
12001
12002 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12003 throw new IllegalArgumentException(
12004 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12005 }
12006
12007 return intent;
12008 }
12009
12010 public final int broadcastIntent(IApplicationThread caller,
12011 Intent intent, String resolvedType, IIntentReceiver resultTo,
12012 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012013 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012014 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012015 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012016 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012018 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12019 final int callingPid = Binder.getCallingPid();
12020 final int callingUid = Binder.getCallingUid();
12021 final long origId = Binder.clearCallingIdentity();
12022 int res = broadcastIntentLocked(callerApp,
12023 callerApp != null ? callerApp.info.packageName : null,
12024 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012025 resultCode, resultData, map, requiredPermission, serialized, sticky,
12026 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 Binder.restoreCallingIdentity(origId);
12028 return res;
12029 }
12030 }
12031
12032 int broadcastIntentInPackage(String packageName, int uid,
12033 Intent intent, String resolvedType, IIntentReceiver resultTo,
12034 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012035 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012037 intent = verifyBroadcastLocked(intent);
12038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012039 final long origId = Binder.clearCallingIdentity();
12040 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12041 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012042 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043 Binder.restoreCallingIdentity(origId);
12044 return res;
12045 }
12046 }
12047
Amith Yamasani742a6712011-05-04 14:49:28 -070012048 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012049 // Refuse possible leaked file descriptors
12050 if (intent != null && intent.hasFileDescriptors() == true) {
12051 throw new IllegalArgumentException("File descriptors passed in Intent");
12052 }
12053
Dianne Hackborn139748f2012-09-24 11:36:57 -070012054 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012055 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012057 synchronized(this) {
12058 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12059 != PackageManager.PERMISSION_GRANTED) {
12060 String msg = "Permission Denial: unbroadcastIntent() from pid="
12061 + Binder.getCallingPid()
12062 + ", uid=" + Binder.getCallingUid()
12063 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012064 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012065 throw new SecurityException(msg);
12066 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012067 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12068 if (stickies != null) {
12069 ArrayList<Intent> list = stickies.get(intent.getAction());
12070 if (list != null) {
12071 int N = list.size();
12072 int i;
12073 for (i=0; i<N; i++) {
12074 if (intent.filterEquals(list.get(i))) {
12075 list.remove(i);
12076 break;
12077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012078 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012079 if (list.size() <= 0) {
12080 stickies.remove(intent.getAction());
12081 }
12082 }
12083 if (stickies.size() <= 0) {
12084 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012085 }
12086 }
12087 }
12088 }
12089
12090 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12091 String resultData, Bundle resultExtras, boolean resultAbort,
12092 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012093 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12094 if (r == null) {
12095 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 return false;
12097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012098
Christopher Tatef46723b2012-01-26 14:19:24 -080012099 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12100 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 }
12102
12103 public void finishReceiver(IBinder who, int resultCode, String resultData,
12104 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012105 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106
12107 // Refuse possible leaked file descriptors
12108 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12109 throw new IllegalArgumentException("File descriptors passed in Bundle");
12110 }
12111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012113 try {
12114 boolean doNext = false;
12115 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012116
Christopher Tatef46723b2012-01-26 14:19:24 -080012117 synchronized(this) {
12118 r = broadcastRecordForReceiverLocked(who);
12119 if (r != null) {
12120 doNext = r.queue.finishReceiverLocked(r, resultCode,
12121 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012124
Christopher Tatef46723b2012-01-26 14:19:24 -080012125 if (doNext) {
12126 r.queue.processNextBroadcast(false);
12127 }
12128 trimApplications();
12129 } finally {
12130 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012134 // =========================================================
12135 // INSTRUMENTATION
12136 // =========================================================
12137
12138 public boolean startInstrumentation(ComponentName className,
12139 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012140 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012141 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012142 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012143 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012144 // Refuse possible leaked file descriptors
12145 if (arguments != null && arguments.hasFileDescriptors()) {
12146 throw new IllegalArgumentException("File descriptors passed in Bundle");
12147 }
12148
12149 synchronized(this) {
12150 InstrumentationInfo ii = null;
12151 ApplicationInfo ai = null;
12152 try {
12153 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012154 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012155 ai = AppGlobals.getPackageManager().getApplicationInfo(
12156 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012157 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012158 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159 }
12160 if (ii == null) {
12161 reportStartInstrumentationFailure(watcher, className,
12162 "Unable to find instrumentation info for: " + className);
12163 return false;
12164 }
12165 if (ai == null) {
12166 reportStartInstrumentationFailure(watcher, className,
12167 "Unable to find instrumentation target package: " + ii.targetPackage);
12168 return false;
12169 }
12170
12171 int match = mContext.getPackageManager().checkSignatures(
12172 ii.targetPackage, ii.packageName);
12173 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12174 String msg = "Permission Denial: starting instrumentation "
12175 + className + " from pid="
12176 + Binder.getCallingPid()
12177 + ", uid=" + Binder.getCallingPid()
12178 + " not allowed because package " + ii.packageName
12179 + " does not have a signature matching the target "
12180 + ii.targetPackage;
12181 reportStartInstrumentationFailure(watcher, className, msg);
12182 throw new SecurityException(msg);
12183 }
12184
12185 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012186 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012187 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012188 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012189 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012190 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 app.instrumentationProfileFile = profileFile;
12192 app.instrumentationArguments = arguments;
12193 app.instrumentationWatcher = watcher;
12194 app.instrumentationResultClass = className;
12195 Binder.restoreCallingIdentity(origId);
12196 }
12197
12198 return true;
12199 }
12200
12201 /**
12202 * Report errors that occur while attempting to start Instrumentation. Always writes the
12203 * error to the logs, but if somebody is watching, send the report there too. This enables
12204 * the "am" command to report errors with more information.
12205 *
12206 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12207 * @param cn The component name of the instrumentation.
12208 * @param report The error report.
12209 */
12210 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12211 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012212 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 try {
12214 if (watcher != null) {
12215 Bundle results = new Bundle();
12216 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12217 results.putString("Error", report);
12218 watcher.instrumentationStatus(cn, -1, results);
12219 }
12220 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012221 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222 }
12223 }
12224
12225 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12226 if (app.instrumentationWatcher != null) {
12227 try {
12228 // NOTE: IInstrumentationWatcher *must* be oneway here
12229 app.instrumentationWatcher.instrumentationFinished(
12230 app.instrumentationClass,
12231 resultCode,
12232 results);
12233 } catch (RemoteException e) {
12234 }
12235 }
12236 app.instrumentationWatcher = null;
12237 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012238 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239 app.instrumentationProfileFile = null;
12240 app.instrumentationArguments = null;
12241
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012242 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012243 }
12244
12245 public void finishInstrumentation(IApplicationThread target,
12246 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012247 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248 // Refuse possible leaked file descriptors
12249 if (results != null && results.hasFileDescriptors()) {
12250 throw new IllegalArgumentException("File descriptors passed in Intent");
12251 }
12252
12253 synchronized(this) {
12254 ProcessRecord app = getRecordForAppLocked(target);
12255 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012256 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012257 return;
12258 }
12259 final long origId = Binder.clearCallingIdentity();
12260 finishInstrumentationLocked(app, resultCode, results);
12261 Binder.restoreCallingIdentity(origId);
12262 }
12263 }
12264
12265 // =========================================================
12266 // CONFIGURATION
12267 // =========================================================
12268
12269 public ConfigurationInfo getDeviceConfigurationInfo() {
12270 ConfigurationInfo config = new ConfigurationInfo();
12271 synchronized (this) {
12272 config.reqTouchScreen = mConfiguration.touchscreen;
12273 config.reqKeyboardType = mConfiguration.keyboard;
12274 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012275 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12276 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012277 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12278 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012279 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12280 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012281 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12282 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012283 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284 }
12285 return config;
12286 }
12287
12288 public Configuration getConfiguration() {
12289 Configuration ci;
12290 synchronized(this) {
12291 ci = new Configuration(mConfiguration);
12292 }
12293 return ci;
12294 }
12295
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012296 public void updatePersistentConfiguration(Configuration values) {
12297 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12298 "updateConfiguration()");
12299 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12300 "updateConfiguration()");
12301 if (values == null) {
12302 throw new NullPointerException("Configuration must not be null");
12303 }
12304
12305 synchronized(this) {
12306 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012307 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012308 Binder.restoreCallingIdentity(origId);
12309 }
12310 }
12311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012312 public void updateConfiguration(Configuration values) {
12313 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12314 "updateConfiguration()");
12315
12316 synchronized(this) {
12317 if (values == null && mWindowManager != null) {
12318 // sentinel: fetch the current configuration from the window manager
12319 values = mWindowManager.computeNewConfiguration();
12320 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012321
12322 if (mWindowManager != null) {
12323 mProcessList.applyDisplaySize(mWindowManager);
12324 }
12325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012326 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012327 if (values != null) {
12328 Settings.System.clearConfiguration(values);
12329 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012330 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012331 Binder.restoreCallingIdentity(origId);
12332 }
12333 }
12334
12335 /**
12336 * Do either or both things: (1) change the current configuration, and (2)
12337 * make sure the given activity is running with the (now) current
12338 * configuration. Returns true if the activity has been left running, or
12339 * false if <var>starting</var> is being destroyed to match the new
12340 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012341 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012342 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012343 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012344 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012345 // do nothing if we are headless
12346 if (mHeadless) return true;
12347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012348 int changes = 0;
12349
12350 boolean kept = true;
12351
12352 if (values != null) {
12353 Configuration newConfig = new Configuration(mConfiguration);
12354 changes = newConfig.updateFrom(values);
12355 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012356 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012357 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358 }
12359
Doug Zongker2bec3d42009-12-04 12:52:44 -080012360 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361
Dianne Hackborn813075a62011-11-14 17:45:19 -080012362 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012363 saveLocaleLocked(values.locale,
12364 !values.locale.equals(mConfiguration.locale),
12365 values.userSetLocale);
12366 }
12367
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012368 mConfigurationSeq++;
12369 if (mConfigurationSeq <= 0) {
12370 mConfigurationSeq = 1;
12371 }
12372 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373 mConfiguration = newConfig;
Craig Mautner4abf3f92012-12-06 22:27:59 -080012374 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012375
12376 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012377
12378 // TODO: If our config changes, should we auto dismiss any currently
12379 // showing dialogs?
12380 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012381
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012382 AttributeCache ac = AttributeCache.instance();
12383 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012384 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012386
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012387 // Make sure all resources in our process are updated
12388 // right now, so that anyone who is going to retrieve
12389 // resource values after we return will be sure to get
12390 // the new ones. This is especially important during
12391 // boot, where the first config change needs to guarantee
12392 // all resources have that config before following boot
12393 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012394 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012395
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012396 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012397 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012398 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012399 mHandler.sendMessage(msg);
12400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012401
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012402 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12403 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012404 try {
12405 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012406 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012407 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012408 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 }
12410 } catch (Exception e) {
12411 }
12412 }
12413 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012414 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012415 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12416 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012417 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012418 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012419 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012420 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12421 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12422 broadcastIntentLocked(null, null, intent,
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012423 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012424 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012426 }
12427 }
12428
12429 if (changes != 0 && starting == null) {
12430 // If the configuration changed, and the caller is not already
12431 // in the process of starting an activity, then find the top
12432 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012433 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434 }
12435
12436 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012437 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012438 // And we need to make sure at this point that all other activities
12439 // are made visible with the correct configuration.
12440 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012441 }
12442
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012443 if (values != null && mWindowManager != null) {
12444 mWindowManager.setNewConfiguration(mConfiguration);
12445 }
12446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012447 return kept;
12448 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012449
12450 /**
12451 * Decide based on the configuration whether we should shouw the ANR,
12452 * crash, etc dialogs. The idea is that if there is no affordnace to
12453 * press the on-screen buttons, we shouldn't show the dialog.
12454 *
12455 * A thought: SystemUI might also want to get told about this, the Power
12456 * dialog / global actions also might want different behaviors.
12457 */
12458 private static final boolean shouldShowDialogs(Configuration config) {
12459 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12460 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012462
12463 /**
12464 * Save the locale. You must be inside a synchronized (this) block.
12465 */
12466 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12467 if(isDiff) {
12468 SystemProperties.set("user.language", l.getLanguage());
12469 SystemProperties.set("user.region", l.getCountry());
12470 }
12471
12472 if(isPersist) {
12473 SystemProperties.set("persist.sys.language", l.getLanguage());
12474 SystemProperties.set("persist.sys.country", l.getCountry());
12475 SystemProperties.set("persist.sys.localevar", l.getVariant());
12476 }
12477 }
12478
Adam Powelldd8fab22012-03-22 17:47:27 -070012479 @Override
12480 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12481 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012482 return srec != null && srec.task.affinity != null &&
12483 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012484 }
12485
12486 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12487 Intent resultData) {
12488 ComponentName dest = destIntent.getComponent();
12489
12490 synchronized (this) {
12491 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012492 if (srec == null) {
12493 return false;
12494 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012495 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12496 final int start = history.indexOf(srec);
12497 if (start < 0) {
12498 // Current activity is not in history stack; do nothing.
12499 return false;
12500 }
12501 int finishTo = start - 1;
12502 ActivityRecord parent = null;
12503 boolean foundParentInTask = false;
12504 if (dest != null) {
12505 TaskRecord tr = srec.task;
12506 for (int i = start - 1; i >= 0; i--) {
12507 ActivityRecord r = history.get(i);
12508 if (tr != r.task) {
12509 // Couldn't find parent in the same task; stop at the one above this.
12510 // (Root of current task; in-app "home" behavior)
12511 // Always at least finish the current activity.
12512 finishTo = Math.min(start - 1, i + 1);
12513 parent = history.get(finishTo);
12514 break;
12515 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12516 r.info.name.equals(dest.getClassName())) {
12517 finishTo = i;
12518 parent = r;
12519 foundParentInTask = true;
12520 break;
12521 }
12522 }
12523 }
12524
12525 if (mController != null) {
12526 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12527 if (next != null) {
12528 // ask watcher if this is allowed
12529 boolean resumeOK = true;
12530 try {
12531 resumeOK = mController.activityResuming(next.packageName);
12532 } catch (RemoteException e) {
12533 mController = null;
12534 }
12535
12536 if (!resumeOK) {
12537 return false;
12538 }
12539 }
12540 }
12541 final long origId = Binder.clearCallingIdentity();
12542 for (int i = start; i > finishTo; i--) {
12543 ActivityRecord r = history.get(i);
12544 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012545 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012546 // Only return the supplied result for the first activity finished
12547 resultCode = Activity.RESULT_CANCELED;
12548 resultData = null;
12549 }
12550
12551 if (parent != null && foundParentInTask) {
12552 final int parentLaunchMode = parent.info.launchMode;
12553 final int destIntentFlags = destIntent.getFlags();
12554 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12555 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12556 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12557 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012558 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012559 } else {
12560 try {
12561 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012562 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012563 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12564 null, aInfo, parent.appToken, null,
12565 0, -1, parent.launchedFromUid, 0, null, true, null);
12566 foundParentInTask = res == ActivityManager.START_SUCCESS;
12567 } catch (RemoteException e) {
12568 foundParentInTask = false;
12569 }
12570 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012571 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012572 }
12573 }
12574 Binder.restoreCallingIdentity(origId);
12575 return foundParentInTask;
12576 }
12577 }
12578
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012579 public int getLaunchedFromUid(IBinder activityToken) {
12580 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12581 if (srec == null) {
12582 return -1;
12583 }
12584 return srec.launchedFromUid;
12585 }
12586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012587 // =========================================================
12588 // LIFETIME MANAGEMENT
12589 // =========================================================
12590
Christopher Tatef46723b2012-01-26 14:19:24 -080012591 // Returns which broadcast queue the app is the current [or imminent] receiver
12592 // on, or 'null' if the app is not an active broadcast recipient.
12593 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12594 BroadcastRecord r = app.curReceiver;
12595 if (r != null) {
12596 return r.queue;
12597 }
12598
12599 // It's not the current receiver, but it might be starting up to become one
12600 synchronized (this) {
12601 for (BroadcastQueue queue : mBroadcastQueues) {
12602 r = queue.mPendingBroadcast;
12603 if (r != null && r.curApp == app) {
12604 // found it; report which queue it's in
12605 return queue;
12606 }
12607 }
12608 }
12609
12610 return null;
12611 }
12612
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012613 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012614 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012616 // This adjustment has already been computed. If we are calling
12617 // from the top, we may have already computed our adjustment with
12618 // an earlier hidden adjustment that isn't really for us... if
12619 // so, use the new hidden adjustment.
12620 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012621 if (app.hasActivities) {
12622 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12623 } else if (app.hasClientActivities) {
12624 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12625 } else {
12626 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12627 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012628 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012629 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012630 }
12631
12632 if (app.thread == null) {
12633 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012634 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012635 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012636 }
12637
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012638 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12639 app.adjSource = null;
12640 app.adjTarget = null;
12641 app.empty = false;
12642 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012643 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012644
12645 final int activitiesSize = app.activities.size();
12646
Dianne Hackborn7d608422011-08-07 16:24:18 -070012647 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012648 // The max adjustment doesn't allow this app to be anything
12649 // below foreground, so it is not worth doing work for it.
12650 app.adjType = "fixed";
12651 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012652 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012653 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012654 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012655 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012656 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012657 // System process can do UI, and when they do we want to have
12658 // them trim their memory after the user leaves the UI. To
12659 // facilitate this, here we need to determine whether or not it
12660 // is currently showing UI.
12661 app.systemNoUi = true;
12662 if (app == TOP_APP) {
12663 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012664 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012665 } else if (activitiesSize > 0) {
12666 for (int j = 0; j < activitiesSize; j++) {
12667 final ActivityRecord r = app.activities.get(j);
12668 if (r.visible) {
12669 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012670 }
12671 if (r.app == app) {
12672 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012673 }
12674 }
12675 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012676 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012677 }
12678
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012679 app.keeping = false;
12680 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012681 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012682
The Android Open Source Project4df24232009-03-05 14:34:35 -080012683 // Determine the importance of the process, starting with most
12684 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012685 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012686 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012687 boolean foregroundActivities = false;
12688 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012689 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012690 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012692 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012693 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012694 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012695 foregroundActivities = true;
12696 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012697 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012698 } else if (app.instrumentationClass != null) {
12699 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012700 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012701 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012702 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012703 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012704 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012705 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012706 // counts as being in the foreground for OOM killer purposes.
12707 // It's placed in a sched group based on the nature of the
12708 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012709 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012710 schedGroup = (queue == mFgBroadcastQueue)
12711 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012712 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012713 } else if (app.executingServices.size() > 0) {
12714 // An app that is currently executing a service callback also
12715 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012716 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012717 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012718 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012719 } else {
12720 // Assume process is hidden (has activities); we will correct
12721 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012722 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012723 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012724 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012725 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012726 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012727
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012728 boolean hasStoppingActivities = false;
12729
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012730 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012731 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012732 for (int j = 0; j < activitiesSize; j++) {
12733 final ActivityRecord r = app.activities.get(j);
12734 if (r.visible) {
12735 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012736 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12737 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012738 app.adjType = "visible";
12739 }
12740 schedGroup = Process.THREAD_GROUP_DEFAULT;
12741 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012742 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012743 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012744 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012745 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012746 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12747 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012748 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012749 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012750 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012751 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012752 } else if (r.state == ActivityState.STOPPING) {
12753 // We will apply the actual adjustment later, because
12754 // we want to allow this process to immediately go through
12755 // any memory trimming that is in effect.
12756 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012757 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012758 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012759 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012760 if (r.app == app) {
12761 app.hasActivities = true;
12762 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012763 }
12764 }
12765
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012766 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012767 if (app.hasClientActivities) {
12768 adj = clientHiddenAdj;
12769 app.adjType = "bg-client-act";
12770 } else {
12771 // Whoops, this process is completely empty as far as we know
12772 // at this point.
12773 adj = emptyAdj;
12774 app.empty = true;
12775 app.adjType = "bg-empty";
12776 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012777 }
12778
Dianne Hackborn7d608422011-08-07 16:24:18 -070012779 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012780 if (app.foregroundServices) {
12781 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012782 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012783 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012784 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012785 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012786 } else if (app.forcingToForeground != null) {
12787 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012788 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012789 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012790 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012791 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012792 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012793 }
12794 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012795
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012796 if (app.foregroundServices) {
12797 interesting = true;
12798 }
12799
Dianne Hackborn7d608422011-08-07 16:24:18 -070012800 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012801 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012802 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012803 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012804 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012805 app.adjType = "heavy";
12806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012807
Dianne Hackborn7d608422011-08-07 16:24:18 -070012808 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012809 // This process is hosting what we currently consider to be the
12810 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012811 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012812 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012813 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012814 app.adjType = "home";
12815 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012816
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012817 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12818 && app.activities.size() > 0) {
12819 // This was the previous process that showed UI to the user.
12820 // We want to try to keep it around more aggressively, to give
12821 // a good experience around switching between two apps.
12822 adj = ProcessList.PREVIOUS_APP_ADJ;
12823 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12824 app.hidden = false;
12825 app.adjType = "previous";
12826 }
12827
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012828 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12829 + " reason=" + app.adjType);
12830
The Android Open Source Project4df24232009-03-05 14:34:35 -080012831 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 // there are applications dependent on our services or providers, but
12833 // this gives us a baseline and makes sure we don't get into an
12834 // infinite recursion.
12835 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012836 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012837
Christopher Tate6fa95972009-06-05 18:43:55 -070012838 if (mBackupTarget != null && app == mBackupTarget.app) {
12839 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012840 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012841 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012842 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012843 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012844 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012845 }
12846 }
12847
Dianne Hackborn7d608422011-08-07 16:24:18 -070012848 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012849 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012850 final long now = SystemClock.uptimeMillis();
12851 // This process is more important if the top activity is
12852 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012853 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012854 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012855 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012856 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012857 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012858 // If this process has shown some UI, let it immediately
12859 // go to the LRU list because it may be pretty heavy with
12860 // UI stuff. We'll tag it with a label just to help
12861 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012862 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012863 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012865 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012866 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012867 // This service has seen some activity within
12868 // recent memory, so we will keep its process ahead
12869 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012870 if (adj > ProcessList.SERVICE_ADJ) {
12871 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012872 app.adjType = "started-services";
12873 app.hidden = false;
12874 }
12875 }
12876 // If we have let the service slide into the background
12877 // state, still have some text describing what it is doing
12878 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012879 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012880 app.adjType = "started-bg-services";
12881 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012882 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012883 // Don't kill this process because it is doing work; it
12884 // has said it is doing work.
12885 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012886 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012887 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012888 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012889 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012890 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012891 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012892 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012893 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012894 // XXX should compute this based on the max of
12895 // all connected clients.
12896 ConnectionRecord cr = clist.get(i);
12897 if (cr.binding.client == app) {
12898 // Binding to ourself is not interesting.
12899 continue;
12900 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012901 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012902 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012903 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012904 int myHiddenAdj = hiddenAdj;
12905 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012906 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012907 myHiddenAdj = client.hiddenAdj;
12908 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012909 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012910 }
12911 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012912 int myClientHiddenAdj = clientHiddenAdj;
12913 if (myClientHiddenAdj > client.clientHiddenAdj) {
12914 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12915 myClientHiddenAdj = client.clientHiddenAdj;
12916 } else {
12917 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12918 }
12919 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012920 int myEmptyAdj = emptyAdj;
12921 if (myEmptyAdj > client.emptyAdj) {
12922 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12923 myEmptyAdj = client.emptyAdj;
12924 } else {
12925 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12926 }
12927 }
12928 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012929 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012930 String adjType = null;
12931 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12932 // Not doing bind OOM management, so treat
12933 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012934 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012935 // If this process has shown some UI, let it immediately
12936 // go to the LRU list because it may be pretty heavy with
12937 // UI stuff. We'll tag it with a label just to help
12938 // debug and understand what is going on.
12939 if (adj > clientAdj) {
12940 adjType = "bound-bg-ui-services";
12941 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012942 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012943 clientAdj = adj;
12944 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012945 if (now >= (s.lastActivity
12946 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012947 // This service has not seen activity within
12948 // recent memory, so allow it to drop to the
12949 // LRU list if there is no other reason to keep
12950 // it around. We'll also tag it with a label just
12951 // to help debug and undertand what is going on.
12952 if (adj > clientAdj) {
12953 adjType = "bound-bg-services";
12954 }
12955 clientAdj = adj;
12956 }
12957 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012958 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12959 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12960 // If this connection is keeping the service
12961 // created, then we want to try to better follow
12962 // its memory management semantics for activities.
12963 // That is, if it is sitting in the background
12964 // LRU list as a hidden process (with activities),
12965 // we don't want the service it is connected to
12966 // to go into the empty LRU and quickly get killed,
12967 // because I'll we'll do is just end up restarting
12968 // the service.
12969 app.hasClientActivities |= client.hasActivities;
12970 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012971 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012972 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012973 // If this process has recently shown UI, and
12974 // the process that is binding to it is less
12975 // important than being visible, then we don't
12976 // care about the binding as much as we care
12977 // about letting this process get into the LRU
12978 // list to be killed and restarted if needed for
12979 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012980 if (app.hasShownUi && app != mHomeProcess
12981 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012982 adjType = "bound-bg-ui-services";
12983 } else {
12984 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12985 |Context.BIND_IMPORTANT)) != 0) {
12986 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012987 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12988 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12989 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12990 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12991 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012992 adj = clientAdj;
12993 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012994 app.pendingUiClean = true;
12995 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12996 adj = ProcessList.VISIBLE_APP_ADJ;
12997 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012998 }
12999 if (!client.hidden) {
13000 app.hidden = false;
13001 }
13002 if (client.keeping) {
13003 app.keeping = true;
13004 }
13005 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013006 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013007 }
13008 if (adjType != null) {
13009 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013010 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13011 .REASON_SERVICE_IN_USE;
13012 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013013 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013014 app.adjTarget = s.name;
13015 }
13016 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13017 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13018 schedGroup = Process.THREAD_GROUP_DEFAULT;
13019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 }
13021 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013022 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013023 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013024 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013025 (a.visible || a.state == ActivityState.RESUMED
13026 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013027 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013028 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13029 schedGroup = Process.THREAD_GROUP_DEFAULT;
13030 }
13031 app.hidden = false;
13032 app.adjType = "service";
13033 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13034 .REASON_SERVICE_IN_USE;
13035 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013036 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013037 app.adjTarget = s.name;
13038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013040 }
13041 }
13042 }
13043 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013044
Dianne Hackborn287952c2010-09-22 22:34:31 -070013045 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013046 // would like to avoid killing it unless it would prevent the current
13047 // application from running. By default we put the process in
13048 // with the rest of the background processes; as we scan through
13049 // its services we may bump it up from there.
13050 if (adj > hiddenAdj) {
13051 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013052 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013053 app.adjType = "bg-services";
13054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013055 }
13056
Dianne Hackborn7d608422011-08-07 16:24:18 -070013057 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013058 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013059 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013060 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013061 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013062 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013063 for (int i = cpr.connections.size()-1;
13064 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13065 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13066 i--) {
13067 ContentProviderConnection conn = cpr.connections.get(i);
13068 ProcessRecord client = conn.client;
13069 if (client == app) {
13070 // Being our own client is not interesting.
13071 continue;
13072 }
13073 int myHiddenAdj = hiddenAdj;
13074 if (myHiddenAdj > client.hiddenAdj) {
13075 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13076 myHiddenAdj = client.hiddenAdj;
13077 } else {
13078 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013079 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013080 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013081 int myClientHiddenAdj = clientHiddenAdj;
13082 if (myClientHiddenAdj > client.clientHiddenAdj) {
13083 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13084 myClientHiddenAdj = client.clientHiddenAdj;
13085 } else {
13086 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13087 }
13088 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013089 int myEmptyAdj = emptyAdj;
13090 if (myEmptyAdj > client.emptyAdj) {
13091 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13092 myEmptyAdj = client.emptyAdj;
13093 } else {
13094 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13095 }
13096 }
13097 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013098 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013099 if (adj > clientAdj) {
13100 if (app.hasShownUi && app != mHomeProcess
13101 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13102 app.adjType = "bg-ui-provider";
13103 } else {
13104 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13105 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13106 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013107 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013108 if (!client.hidden) {
13109 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013111 if (client.keeping) {
13112 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013113 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013114 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13115 .REASON_PROVIDER_IN_USE;
13116 app.adjSource = client;
13117 app.adjSourceOom = clientAdj;
13118 app.adjTarget = cpr.name;
13119 }
13120 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13121 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 }
13123 }
13124 // If the provider has external (non-framework) process
13125 // dependencies, ensure that its adjustment is at least
13126 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013127 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013128 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13129 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013130 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013131 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013132 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013133 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013134 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013135 }
13136 }
13137 }
13138 }
13139
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013140 if (adj == ProcessList.SERVICE_ADJ) {
13141 if (doingAll) {
13142 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13143 mNewNumServiceProcs++;
13144 }
13145 if (app.serviceb) {
13146 adj = ProcessList.SERVICE_B_ADJ;
13147 }
13148 } else {
13149 app.serviceb = false;
13150 }
13151
13152 app.nonStoppingAdj = adj;
13153
13154 if (hasStoppingActivities) {
13155 // Only upgrade adjustment.
13156 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13157 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13158 app.adjType = "stopping";
13159 }
13160 }
13161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013162 app.curRawAdj = adj;
13163
Joe Onorato8a9b2202010-02-26 18:56:32 -080013164 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013165 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13166 if (adj > app.maxAdj) {
13167 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013168 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013169 schedGroup = Process.THREAD_GROUP_DEFAULT;
13170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013171 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013172 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013173 app.keeping = true;
13174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013176 if (app.hasAboveClient) {
13177 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13178 // then we need to drop its adjustment to be lower than the service's
13179 // in order to honor the request. We want to drop it by one adjustment
13180 // level... but there is special meaning applied to various levels so
13181 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013182 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013183 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013184 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13185 adj = ProcessList.VISIBLE_APP_ADJ;
13186 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13187 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13188 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13189 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013190 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013191 adj++;
13192 }
13193 }
13194
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013195 int importance = app.memImportance;
13196 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13197 app.curAdj = adj;
13198 app.curSchedGroup = schedGroup;
13199 if (!interesting) {
13200 // For this reporting, if there is not something explicitly
13201 // interesting in this process then we will push it to the
13202 // background importance.
13203 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13204 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13205 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13206 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13207 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13208 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13209 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13210 } else if (adj >= ProcessList.SERVICE_ADJ) {
13211 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13212 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13213 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13214 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13215 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13216 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13217 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13218 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13219 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13220 } else {
13221 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13222 }
13223 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013224
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013225 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13226 if (foregroundActivities != app.foregroundActivities) {
13227 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13228 }
13229 if (changes != 0) {
13230 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13231 app.memImportance = importance;
13232 app.foregroundActivities = foregroundActivities;
13233 int i = mPendingProcessChanges.size()-1;
13234 ProcessChangeItem item = null;
13235 while (i >= 0) {
13236 item = mPendingProcessChanges.get(i);
13237 if (item.pid == app.pid) {
13238 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13239 break;
13240 }
13241 i--;
13242 }
13243 if (i < 0) {
13244 // No existing item in pending changes; need a new one.
13245 final int NA = mAvailProcessChanges.size();
13246 if (NA > 0) {
13247 item = mAvailProcessChanges.remove(NA-1);
13248 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13249 } else {
13250 item = new ProcessChangeItem();
13251 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13252 }
13253 item.changes = 0;
13254 item.pid = app.pid;
13255 item.uid = app.info.uid;
13256 if (mPendingProcessChanges.size() == 0) {
13257 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13258 "*** Enqueueing dispatch processes changed!");
13259 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13260 }
13261 mPendingProcessChanges.add(item);
13262 }
13263 item.changes |= changes;
13264 item.importance = importance;
13265 item.foregroundActivities = foregroundActivities;
13266 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13267 + Integer.toHexString(System.identityHashCode(item))
13268 + " " + app.toShortString() + ": changes=" + item.changes
13269 + " importance=" + item.importance
13270 + " foreground=" + item.foregroundActivities
13271 + " type=" + app.adjType + " source=" + app.adjSource
13272 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013273 }
13274
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013275 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276 }
13277
13278 /**
13279 * Ask a given process to GC right now.
13280 */
13281 final void performAppGcLocked(ProcessRecord app) {
13282 try {
13283 app.lastRequestedGc = SystemClock.uptimeMillis();
13284 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013285 if (app.reportLowMemory) {
13286 app.reportLowMemory = false;
13287 app.thread.scheduleLowMemory();
13288 } else {
13289 app.thread.processInBackground();
13290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013291 }
13292 } catch (Exception e) {
13293 // whatever.
13294 }
13295 }
13296
13297 /**
13298 * Returns true if things are idle enough to perform GCs.
13299 */
Josh Bartel7f208742010-02-25 11:01:44 -060013300 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013301 boolean processingBroadcasts = false;
13302 for (BroadcastQueue q : mBroadcastQueues) {
13303 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13304 processingBroadcasts = true;
13305 }
13306 }
13307 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013308 && (mSleeping || (mMainStack.mResumedActivity != null &&
13309 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310 }
13311
13312 /**
13313 * Perform GCs on all processes that are waiting for it, but only
13314 * if things are idle.
13315 */
13316 final void performAppGcsLocked() {
13317 final int N = mProcessesToGc.size();
13318 if (N <= 0) {
13319 return;
13320 }
Josh Bartel7f208742010-02-25 11:01:44 -060013321 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013322 while (mProcessesToGc.size() > 0) {
13323 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013324 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013325 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13326 <= SystemClock.uptimeMillis()) {
13327 // To avoid spamming the system, we will GC processes one
13328 // at a time, waiting a few seconds between each.
13329 performAppGcLocked(proc);
13330 scheduleAppGcsLocked();
13331 return;
13332 } else {
13333 // It hasn't been long enough since we last GCed this
13334 // process... put it in the list to wait for its time.
13335 addProcessToGcListLocked(proc);
13336 break;
13337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 }
13339 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013340
13341 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013342 }
13343 }
13344
13345 /**
13346 * If all looks good, perform GCs on all processes waiting for them.
13347 */
13348 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013349 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013350 performAppGcsLocked();
13351 return;
13352 }
13353 // Still not idle, wait some more.
13354 scheduleAppGcsLocked();
13355 }
13356
13357 /**
13358 * Schedule the execution of all pending app GCs.
13359 */
13360 final void scheduleAppGcsLocked() {
13361 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013362
13363 if (mProcessesToGc.size() > 0) {
13364 // Schedule a GC for the time to the next process.
13365 ProcessRecord proc = mProcessesToGc.get(0);
13366 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13367
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013368 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013369 long now = SystemClock.uptimeMillis();
13370 if (when < (now+GC_TIMEOUT)) {
13371 when = now + GC_TIMEOUT;
13372 }
13373 mHandler.sendMessageAtTime(msg, when);
13374 }
13375 }
13376
13377 /**
13378 * Add a process to the array of processes waiting to be GCed. Keeps the
13379 * list in sorted order by the last GC time. The process can't already be
13380 * on the list.
13381 */
13382 final void addProcessToGcListLocked(ProcessRecord proc) {
13383 boolean added = false;
13384 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13385 if (mProcessesToGc.get(i).lastRequestedGc <
13386 proc.lastRequestedGc) {
13387 added = true;
13388 mProcessesToGc.add(i+1, proc);
13389 break;
13390 }
13391 }
13392 if (!added) {
13393 mProcessesToGc.add(0, proc);
13394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013395 }
13396
13397 /**
13398 * Set up to ask a process to GC itself. This will either do it
13399 * immediately, or put it on the list of processes to gc the next
13400 * time things are idle.
13401 */
13402 final void scheduleAppGcLocked(ProcessRecord app) {
13403 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013404 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013405 return;
13406 }
13407 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013408 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013409 scheduleAppGcsLocked();
13410 }
13411 }
13412
Dianne Hackborn287952c2010-09-22 22:34:31 -070013413 final void checkExcessivePowerUsageLocked(boolean doKills) {
13414 updateCpuStatsNow();
13415
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013416 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013417 boolean doWakeKills = doKills;
13418 boolean doCpuKills = doKills;
13419 if (mLastPowerCheckRealtime == 0) {
13420 doWakeKills = false;
13421 }
13422 if (mLastPowerCheckUptime == 0) {
13423 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013424 }
13425 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013426 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013427 }
13428 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013429 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13430 final long curUptime = SystemClock.uptimeMillis();
13431 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13432 mLastPowerCheckRealtime = curRealtime;
13433 mLastPowerCheckUptime = curUptime;
13434 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13435 doWakeKills = false;
13436 }
13437 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13438 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013439 }
13440 int i = mLruProcesses.size();
13441 while (i > 0) {
13442 i--;
13443 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013444 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013445 long wtime;
13446 synchronized (stats) {
13447 wtime = stats.getProcessWakeTime(app.info.uid,
13448 app.pid, curRealtime);
13449 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013450 long wtimeUsed = wtime - app.lastWakeTime;
13451 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13452 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013453 StringBuilder sb = new StringBuilder(128);
13454 sb.append("Wake for ");
13455 app.toShortString(sb);
13456 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013457 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013458 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013459 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013460 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013461 sb.append((wtimeUsed*100)/realtimeSince);
13462 sb.append("%)");
13463 Slog.i(TAG, sb.toString());
13464 sb.setLength(0);
13465 sb.append("CPU for ");
13466 app.toShortString(sb);
13467 sb.append(": over ");
13468 TimeUtils.formatDuration(uptimeSince, sb);
13469 sb.append(" used ");
13470 TimeUtils.formatDuration(cputimeUsed, sb);
13471 sb.append(" (");
13472 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013473 sb.append("%)");
13474 Slog.i(TAG, sb.toString());
13475 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013476 // If a process has held a wake lock for more
13477 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013478 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013479 if (doWakeKills && realtimeSince > 0
13480 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13481 synchronized (stats) {
13482 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13483 realtimeSince, wtimeUsed);
13484 }
13485 Slog.w(TAG, "Excessive wake lock in " + app.processName
13486 + " (pid " + app.pid + "): held " + wtimeUsed
13487 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013488 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013489 app.processName, app.setAdj, "excessive wake lock");
13490 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013491 } else if (doCpuKills && uptimeSince > 0
13492 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13493 synchronized (stats) {
13494 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13495 uptimeSince, cputimeUsed);
13496 }
13497 Slog.w(TAG, "Excessive CPU in " + app.processName
13498 + " (pid " + app.pid + "): used " + cputimeUsed
13499 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013500 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013501 app.processName, app.setAdj, "excessive cpu");
13502 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013503 } else {
13504 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013505 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013506 }
13507 }
13508 }
13509 }
13510
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013511 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013512 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013513 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013514 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013515 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516
13517 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013518 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013519 }
13520
Dianne Hackborn287952c2010-09-22 22:34:31 -070013521 final boolean wasKeeping = app.keeping;
13522
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013523 boolean success = true;
13524
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013525 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013526
Jeff Brown10e89712011-07-08 18:52:57 -070013527 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013528 if (wasKeeping && !app.keeping) {
13529 // This app is no longer something we want to keep. Note
13530 // its current wake lock time to later know to kill it if
13531 // it is not behaving well.
13532 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13533 synchronized (stats) {
13534 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13535 app.pid, SystemClock.elapsedRealtime());
13536 }
13537 app.lastCpuTime = app.curCpuTime;
13538 }
13539
13540 app.setRawAdj = app.curRawAdj;
13541 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013542
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013543 if (app.curAdj != app.setAdj) {
13544 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013545 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013546 TAG, "Set " + app.pid + " " + app.processName +
13547 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013548 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013549 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013550 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013551 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013552 }
13553 }
13554 if (app.setSchedGroup != app.curSchedGroup) {
13555 app.setSchedGroup = app.curSchedGroup;
13556 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13557 "Setting process group of " + app.processName
13558 + " to " + app.curSchedGroup);
13559 if (app.waitingToKill != null &&
13560 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13561 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013562 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013563 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013564 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013565 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013566 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013567 } else {
13568 if (true) {
13569 long oldId = Binder.clearCallingIdentity();
13570 try {
13571 Process.setProcessGroup(app.pid, app.curSchedGroup);
13572 } catch (Exception e) {
13573 Slog.w(TAG, "Failed setting process group of " + app.pid
13574 + " to " + app.curSchedGroup);
13575 e.printStackTrace();
13576 } finally {
13577 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013578 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013579 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013580 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013581 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013582 app.thread.setSchedulingGroup(app.curSchedGroup);
13583 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013584 }
13585 }
13586 }
13587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013588 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013589 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590 }
13591
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013592 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013593 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013594 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013595 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013596 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013597 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013598 }
13599 }
13600 return resumedActivity;
13601 }
13602
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013603 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013604 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013605 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13606 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013607 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13608 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609
13610 mAdjSeq++;
13611
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013612 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13613 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013614 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13615 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013616 if (nowHidden != wasHidden) {
13617 // Changed to/from hidden state, so apps after it in the LRU
13618 // list may also be changed.
13619 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013621 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013622 }
13623
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013624 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013625 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013627 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013628
13629 if (false) {
13630 RuntimeException e = new RuntimeException();
13631 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013632 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013633 }
13634
13635 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013636 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013637
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013638 final int emptyProcessLimit;
13639 final int hiddenProcessLimit;
13640 if (mProcessLimit <= 0) {
13641 emptyProcessLimit = hiddenProcessLimit = 0;
13642 } else if (mProcessLimit == 1) {
13643 emptyProcessLimit = 1;
13644 hiddenProcessLimit = 0;
13645 } else {
13646 emptyProcessLimit = (mProcessLimit*2)/3;
13647 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13648 }
13649
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013650 // Let's determine how many processes we have running vs.
13651 // how many slots we have for background processes; we may want
13652 // to put multiple processes in a slot of there are enough of
13653 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013654 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13655 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013656 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13657 if (numEmptyProcs > hiddenProcessLimit) {
13658 // If there are more empty processes than our limit on hidden
13659 // processes, then use the hidden process limit for the factor.
13660 // This ensures that the really old empty processes get pushed
13661 // down to the bottom, so if we are running low on memory we will
13662 // have a better chance at keeping around more hidden processes
13663 // instead of a gazillion empty processes.
13664 numEmptyProcs = hiddenProcessLimit;
13665 }
13666 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013667 if (emptyFactor < 1) emptyFactor = 1;
13668 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13669 if (hiddenFactor < 1) hiddenFactor = 1;
13670 int stepHidden = 0;
13671 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013672 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013673 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013674 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013675
13676 mNumNonHiddenProcs = 0;
13677 mNumHiddenProcs = 0;
13678
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013679 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013680 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013681 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013682 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013683 int nextHiddenAdj = curHiddenAdj+1;
13684 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13685 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013686 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 while (i > 0) {
13688 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013689 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013690 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013691 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013692 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013693 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13694 // This process was assigned as a hidden process... step the
13695 // hidden level.
13696 mNumHiddenProcs++;
13697 if (curHiddenAdj != nextHiddenAdj) {
13698 stepHidden++;
13699 if (stepHidden >= hiddenFactor) {
13700 stepHidden = 0;
13701 curHiddenAdj = nextHiddenAdj;
13702 nextHiddenAdj += 2;
13703 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13704 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13705 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013706 if (curClientHiddenAdj <= curHiddenAdj) {
13707 curClientHiddenAdj = curHiddenAdj + 1;
13708 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13709 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13710 }
13711 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013712 }
13713 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013714 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013715 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013716 Slog.i(TAG, "No longer want " + app.processName
13717 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013718 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013719 app.processName, app.setAdj, "too many background");
13720 app.killedBackground = true;
13721 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013722 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013723 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13724 // This process has a client that has activities. We will have
13725 // given it the current hidden adj; here we will just leave it
13726 // without stepping the hidden adj.
13727 curClientHiddenAdj++;
13728 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13729 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13730 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013731 } else {
13732 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13733 // This process was assigned as an empty process... step the
13734 // empty level.
13735 if (curEmptyAdj != nextEmptyAdj) {
13736 stepEmpty++;
13737 if (stepEmpty >= emptyFactor) {
13738 stepEmpty = 0;
13739 curEmptyAdj = nextEmptyAdj;
13740 nextEmptyAdj += 2;
13741 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13742 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13743 }
13744 }
13745 }
13746 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13747 mNumNonHiddenProcs++;
13748 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013749 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13750 && !app.hasClientActivities) {
13751 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13752 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013753 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013754 + " (pid " + app.pid + "): empty for "
13755 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13756 / 1000) + "s");
13757 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13758 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013759 app.killedBackground = true;
13760 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013761 } else {
13762 numEmpty++;
13763 if (numEmpty > emptyProcessLimit) {
13764 Slog.i(TAG, "No longer want " + app.processName
13765 + " (pid " + app.pid + "): empty #" + numEmpty);
13766 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13767 app.processName, app.setAdj, "too many background");
13768 app.killedBackground = true;
13769 Process.killProcessQuiet(app.pid);
13770 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013771 }
13772 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013773 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013774 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013775 // If this is an isolated process, and there are no
13776 // services running in it, then the process is no longer
13777 // needed. We agressively kill these because we can by
13778 // definition not re-use the same process again, and it is
13779 // good to avoid having whatever code was running in them
13780 // left sitting around after no longer needed.
13781 Slog.i(TAG, "Isolated process " + app.processName
13782 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013783 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013784 app.processName, app.setAdj, "isolated not needed");
13785 app.killedBackground = true;
13786 Process.killProcessQuiet(app.pid);
13787 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013788 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13789 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13790 && !app.killedBackground) {
13791 numTrimming++;
13792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013793 }
13794 }
13795
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013796 mNumServiceProcs = mNewNumServiceProcs;
13797
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013798 // Now determine the memory trimming level of background processes.
13799 // Unfortunately we need to start at the back of the list to do this
13800 // properly. We only do this if the number of background apps we
13801 // are managing to keep around is less than half the maximum we desire;
13802 // if we are keeping a good number around, we'll let them use whatever
13803 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013804 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13805 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013806 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013807 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013808 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013809 int minFactor = 2;
13810 if (mHomeProcess != null) minFactor++;
13811 if (mPreviousProcess != null) minFactor++;
13812 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013813 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013814 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013815 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013816 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013817 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013818 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13819 } else {
13820 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13821 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013822 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013823 for (i=0; i<N; i++) {
13824 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013825 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13826 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013827 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013828 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13829 try {
13830 app.thread.scheduleTrimMemory(curLevel);
13831 } catch (RemoteException e) {
13832 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013833 if (false) {
13834 // For now we won't do this; our memory trimming seems
13835 // to be good enough at this point that destroying
13836 // activities causes more harm than good.
13837 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13838 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013839 // Need to do this on its own message because the stack may not
13840 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013841 // For these apps we will also finish their activities
13842 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013843 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013844 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013845 }
13846 }
13847 app.trimMemoryLevel = curLevel;
13848 step++;
13849 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013850 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013851 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013852 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13853 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013854 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013855 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13856 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013857 break;
13858 }
13859 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013860 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013861 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013862 && app.thread != null) {
13863 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013864 app.thread.scheduleTrimMemory(
13865 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013866 } catch (RemoteException e) {
13867 }
13868 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013869 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013870 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013871 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013872 && app.pendingUiClean) {
13873 // If this application is now in the background and it
13874 // had done UI, then give it the special trim level to
13875 // have it free UI resources.
13876 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13877 if (app.trimMemoryLevel < level && app.thread != null) {
13878 try {
13879 app.thread.scheduleTrimMemory(level);
13880 } catch (RemoteException e) {
13881 }
13882 }
13883 app.pendingUiClean = false;
13884 }
13885 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013886 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013887 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013888 } catch (RemoteException e) {
13889 }
13890 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013891 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013892 }
13893 }
13894 } else {
13895 final int N = mLruProcesses.size();
13896 for (i=0; i<N; i++) {
13897 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013898 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013899 && app.pendingUiClean) {
13900 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13901 && app.thread != null) {
13902 try {
13903 app.thread.scheduleTrimMemory(
13904 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13905 } catch (RemoteException e) {
13906 }
13907 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013908 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013909 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013910 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013911 }
13912 }
13913
13914 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013915 // Need to do this on its own message because the stack may not
13916 // be in a consistent state at this point.
13917 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013919 }
13920
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013921 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013922 synchronized (this) {
13923 int i;
13924
13925 // First remove any unused application processes whose package
13926 // has been removed.
13927 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13928 final ProcessRecord app = mRemovedProcesses.get(i);
13929 if (app.activities.size() == 0
13930 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013931 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013932 TAG, "Exiting empty application process "
13933 + app.processName + " ("
13934 + (app.thread != null ? app.thread.asBinder() : null)
13935 + ")\n");
13936 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013937 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013938 app.processName, app.setAdj, "empty");
13939 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013940 } else {
13941 try {
13942 app.thread.scheduleExit();
13943 } catch (Exception e) {
13944 // Ignore exceptions.
13945 }
13946 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013947 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013948 mRemovedProcesses.remove(i);
13949
13950 if (app.persistent) {
13951 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013952 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013953 }
13954 }
13955 }
13956 }
13957
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013958 // Now update the oom adj for all processes.
13959 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013960 }
13961 }
13962
13963 /** This method sends the specified signal to each of the persistent apps */
13964 public void signalPersistentProcesses(int sig) throws RemoteException {
13965 if (sig != Process.SIGNAL_USR1) {
13966 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13967 }
13968
13969 synchronized (this) {
13970 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13971 != PackageManager.PERMISSION_GRANTED) {
13972 throw new SecurityException("Requires permission "
13973 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13974 }
13975
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013976 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13977 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013978 if (r.thread != null && r.persistent) {
13979 Process.sendSignal(r.pid, sig);
13980 }
13981 }
13982 }
13983 }
13984
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013985 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13986 if (proc == null || proc == mProfileProc) {
13987 proc = mProfileProc;
13988 path = mProfileFile;
13989 profileType = mProfileType;
13990 clearProfilerLocked();
13991 }
13992 if (proc == null) {
13993 return;
13994 }
13995 try {
13996 proc.thread.profilerControl(false, path, null, profileType);
13997 } catch (RemoteException e) {
13998 throw new IllegalStateException("Process disappeared");
13999 }
14000 }
14001
14002 private void clearProfilerLocked() {
14003 if (mProfileFd != null) {
14004 try {
14005 mProfileFd.close();
14006 } catch (IOException e) {
14007 }
14008 }
14009 mProfileApp = null;
14010 mProfileProc = null;
14011 mProfileFile = null;
14012 mProfileType = 0;
14013 mAutoStopProfiler = false;
14014 }
14015
Dianne Hackborn1676c852012-09-10 14:52:30 -070014016 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014017 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014018
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014019 try {
14020 synchronized (this) {
14021 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14022 // its own permission.
14023 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14024 != PackageManager.PERMISSION_GRANTED) {
14025 throw new SecurityException("Requires permission "
14026 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014027 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014028
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014029 if (start && fd == null) {
14030 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014031 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014032
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014033 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014034 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014035 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014036 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014037
14038 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014039 throw new IllegalArgumentException("Unknown process: " + process);
14040 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014041
14042 if (start) {
14043 stopProfilerLocked(null, null, 0);
14044 setProfileApp(proc.info, proc.processName, path, fd, false);
14045 mProfileProc = proc;
14046 mProfileType = profileType;
14047 try {
14048 fd = fd.dup();
14049 } catch (IOException e) {
14050 fd = null;
14051 }
14052 proc.thread.profilerControl(start, path, fd, profileType);
14053 fd = null;
14054 mProfileFd = null;
14055 } else {
14056 stopProfilerLocked(proc, path, profileType);
14057 if (fd != null) {
14058 try {
14059 fd.close();
14060 } catch (IOException e) {
14061 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014062 }
14063 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014064
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014065 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014066 }
14067 } catch (RemoteException e) {
14068 throw new IllegalStateException("Process disappeared");
14069 } finally {
14070 if (fd != null) {
14071 try {
14072 fd.close();
14073 } catch (IOException e) {
14074 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014075 }
14076 }
14077 }
Andy McFadden824c5102010-07-09 16:26:57 -070014078
Dianne Hackborn1676c852012-09-10 14:52:30 -070014079 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014080 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014081 userId, true, true, callName, null);
14082 ProcessRecord proc = null;
14083 try {
14084 int pid = Integer.parseInt(process);
14085 synchronized (mPidsSelfLocked) {
14086 proc = mPidsSelfLocked.get(pid);
14087 }
14088 } catch (NumberFormatException e) {
14089 }
14090
14091 if (proc == null) {
14092 HashMap<String, SparseArray<ProcessRecord>> all
14093 = mProcessNames.getMap();
14094 SparseArray<ProcessRecord> procs = all.get(process);
14095 if (procs != null && procs.size() > 0) {
14096 proc = procs.valueAt(0);
14097 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14098 for (int i=1; i<procs.size(); i++) {
14099 ProcessRecord thisProc = procs.valueAt(i);
14100 if (thisProc.userId == userId) {
14101 proc = thisProc;
14102 break;
14103 }
14104 }
14105 }
14106 }
14107 }
14108
14109 return proc;
14110 }
14111
14112 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014113 String path, ParcelFileDescriptor fd) throws RemoteException {
14114
14115 try {
14116 synchronized (this) {
14117 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14118 // its own permission (same as profileControl).
14119 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14120 != PackageManager.PERMISSION_GRANTED) {
14121 throw new SecurityException("Requires permission "
14122 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14123 }
14124
14125 if (fd == null) {
14126 throw new IllegalArgumentException("null fd");
14127 }
14128
Dianne Hackborn1676c852012-09-10 14:52:30 -070014129 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014130 if (proc == null || proc.thread == null) {
14131 throw new IllegalArgumentException("Unknown process: " + process);
14132 }
14133
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014134 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14135 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014136 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14137 throw new SecurityException("Process not debuggable: " + proc);
14138 }
14139 }
14140
14141 proc.thread.dumpHeap(managed, path, fd);
14142 fd = null;
14143 return true;
14144 }
14145 } catch (RemoteException e) {
14146 throw new IllegalStateException("Process disappeared");
14147 } finally {
14148 if (fd != null) {
14149 try {
14150 fd.close();
14151 } catch (IOException e) {
14152 }
14153 }
14154 }
14155 }
14156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014157 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14158 public void monitor() {
14159 synchronized (this) { }
14160 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014161
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014162 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014163 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14164 ProcessRecord processRecord = mLruProcesses.get(i);
14165 try {
14166 if (processRecord.thread != null) {
14167 processRecord.thread.setCoreSettings(settings);
14168 }
14169 } catch (RemoteException re) {
14170 /* ignore */
14171 }
14172 }
14173 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014174
14175 // Multi-user methods
14176
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014177 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014178 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014179 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);
Amith Yamasani742a6712011-05-04 14:49:28 -070014187 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014188
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014189 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014190 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014191 synchronized (this) {
14192 final int oldUserId = mCurrentUserId;
14193 if (oldUserId == userId) {
14194 return true;
14195 }
14196
14197 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14198 if (userInfo == null) {
14199 Slog.w(TAG, "No user info for user #" + userId);
14200 return false;
14201 }
14202
14203 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14204 R.anim.screen_user_enter);
14205
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014206 boolean needStart = false;
14207
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014208 // If the user we are switching to is not currently started, then
14209 // we need to start it now.
14210 if (mStartedUsers.get(userId) == null) {
14211 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014212 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014213 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014214 }
14215
14216 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014217 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014218 final Integer userIdInt = Integer.valueOf(userId);
14219 mUserLru.remove(userIdInt);
14220 mUserLru.add(userIdInt);
14221
Craig Mautnerf1b67412012-09-19 13:18:29 -070014222 mWindowManager.setCurrentUser(userId);
14223
Adam Cohenf7522022012-10-03 20:03:18 -070014224 // Once the internal notion of the active user has switched, we lock the device
14225 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014226 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014227
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014228 final UserStartedState uss = mStartedUsers.get(userId);
14229
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014230 // Make sure user is in the started state. If it is currently
14231 // stopping, we need to knock that off.
14232 if (uss.mState == UserStartedState.STATE_STOPPING) {
14233 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14234 // so we can just fairly silently bring the user back from
14235 // the almost-dead.
14236 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014237 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014238 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014239 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14240 // This means ACTION_SHUTDOWN has been sent, so we will
14241 // need to treat this as a new boot of the user.
14242 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014243 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014244 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014245 }
14246
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014247 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14248 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14249 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14250 oldUserId, userId, uss));
14251 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14252 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014253 if (needStart) {
14254 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14255 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14256 | Intent.FLAG_RECEIVER_FOREGROUND);
14257 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14258 broadcastIntentLocked(null, null, intent,
14259 null, null, 0, null, null, null,
14260 false, false, MY_PID, Process.SYSTEM_UID, userId);
14261 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014262
14263 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14264 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014265 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014266 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014267 broadcastIntentLocked(null, null, intent, null,
14268 new IIntentReceiver.Stub() {
14269 public void performReceive(Intent intent, int resultCode,
14270 String data, Bundle extras, boolean ordered,
14271 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014272 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014273 }
14274 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14275 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014276 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014277 } else {
14278 getUserManagerLocked().makeInitialized(userInfo.id);
14279 }
14280 }
14281
14282 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14283 if (!haveActivities) {
14284 startHomeActivityLocked(userId);
14285 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014286
Jeff Sharkey86597df2012-11-09 15:00:31 -080014287 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014288 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014289 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014290 if (needStart) {
14291 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14292 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14293 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14294 broadcastIntentLocked(null, null, intent,
14295 null, new IIntentReceiver.Stub() {
14296 @Override
14297 public void performReceive(Intent intent, int resultCode, String data,
14298 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14299 throws RemoteException {
14300 }
14301 }, 0, null, null,
14302 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014303 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014304 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014305 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014306 } finally {
14307 Binder.restoreCallingIdentity(ident);
14308 }
Amith Yamasani13593602012-03-22 16:16:17 -070014309
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014310 return true;
14311 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014312
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014313 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14314 long ident = Binder.clearCallingIdentity();
14315 try {
14316 Intent intent;
14317 if (oldUserId >= 0) {
14318 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014319 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14320 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014321 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14322 broadcastIntentLocked(null, null, intent,
14323 null, null, 0, null, null, null,
14324 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14325 }
14326 if (newUserId >= 0) {
14327 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014328 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14329 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014330 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14331 broadcastIntentLocked(null, null, intent,
14332 null, null, 0, null, null, null,
14333 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14334 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014335 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14336 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014337 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14338 broadcastIntentLocked(null, null, intent,
14339 null, null, 0, null, null,
14340 android.Manifest.permission.MANAGE_USERS,
14341 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14342 }
14343 } finally {
14344 Binder.restoreCallingIdentity(ident);
14345 }
14346 }
14347
14348 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14349 final int newUserId) {
14350 final int N = mUserSwitchObservers.beginBroadcast();
14351 if (N > 0) {
14352 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14353 int mCount = 0;
14354 @Override
14355 public void sendResult(Bundle data) throws RemoteException {
14356 synchronized (ActivityManagerService.this) {
14357 if (mCurUserSwitchCallback == this) {
14358 mCount++;
14359 if (mCount == N) {
14360 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14361 }
14362 }
14363 }
14364 }
14365 };
14366 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014367 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014368 mCurUserSwitchCallback = callback;
14369 }
14370 for (int i=0; i<N; i++) {
14371 try {
14372 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14373 newUserId, callback);
14374 } catch (RemoteException e) {
14375 }
14376 }
14377 } else {
14378 synchronized (this) {
14379 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14380 }
14381 }
14382 mUserSwitchObservers.finishBroadcast();
14383 }
14384
14385 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14386 synchronized (this) {
14387 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14388 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14389 }
14390 }
14391
14392 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14393 mCurUserSwitchCallback = null;
14394 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14395 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14396 oldUserId, newUserId, uss));
14397 }
14398
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014399 void userInitialized(UserStartedState uss, int newUserId) {
14400 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014401 }
14402
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014403 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014404 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014405 }
14406
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014407 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14408 boolean clearInitializing, boolean clearSwitching) {
14409 boolean unfrozen = false;
14410 synchronized (this) {
14411 if (clearInitializing) {
14412 uss.initializing = false;
14413 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14414 }
14415 if (clearSwitching) {
14416 uss.switching = false;
14417 }
14418 if (!uss.switching && !uss.initializing) {
14419 mWindowManager.stopFreezingScreen();
14420 unfrozen = true;
14421 }
14422 }
14423 if (unfrozen) {
14424 final int N = mUserSwitchObservers.beginBroadcast();
14425 for (int i=0; i<N; i++) {
14426 try {
14427 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14428 } catch (RemoteException e) {
14429 }
14430 }
14431 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014432 }
14433 }
14434
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014435 void finishUserSwitch(UserStartedState uss) {
14436 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014437 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014438 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14439 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014440 final int userId = uss.mHandle.getIdentifier();
14441 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14442 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14443 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014444 null, null, 0, null, null,
14445 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014446 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014447 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014448 int num = mUserLru.size();
14449 int i = 0;
14450 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14451 Integer oldUserId = mUserLru.get(i);
14452 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14453 if (oldUss == null) {
14454 // Shouldn't happen, but be sane if it does.
14455 mUserLru.remove(i);
14456 num--;
14457 continue;
14458 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014459 if (oldUss.mState == UserStartedState.STATE_STOPPING
14460 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014461 // This user is already stopping, doesn't count.
14462 num--;
14463 i++;
14464 continue;
14465 }
14466 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14467 // Owner and current can't be stopped, but count as running.
14468 i++;
14469 continue;
14470 }
14471 // This is a user to be stopped.
14472 stopUserLocked(oldUserId, null);
14473 num--;
14474 i++;
14475 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014476 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014477 }
14478
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014479 @Override
14480 public int stopUser(final int userId, final IStopUserCallback callback) {
14481 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14482 != PackageManager.PERMISSION_GRANTED) {
14483 String msg = "Permission Denial: switchUser() from pid="
14484 + Binder.getCallingPid()
14485 + ", uid=" + Binder.getCallingUid()
14486 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14487 Slog.w(TAG, msg);
14488 throw new SecurityException(msg);
14489 }
14490 if (userId <= 0) {
14491 throw new IllegalArgumentException("Can't stop primary user " + userId);
14492 }
Amith Yamasani13593602012-03-22 16:16:17 -070014493 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014494 return stopUserLocked(userId, callback);
14495 }
14496 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014497
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014498 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14499 if (mCurrentUserId == userId) {
14500 return ActivityManager.USER_OP_IS_CURRENT;
14501 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014502
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014503 final UserStartedState uss = mStartedUsers.get(userId);
14504 if (uss == null) {
14505 // User is not started, nothing to do... but we do need to
14506 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014507 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014508 mHandler.post(new Runnable() {
14509 @Override
14510 public void run() {
14511 try {
14512 callback.userStopped(userId);
14513 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014514 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014515 }
14516 });
14517 }
14518 return ActivityManager.USER_OP_SUCCESS;
14519 }
14520
14521 if (callback != null) {
14522 uss.mStopCallbacks.add(callback);
14523 }
14524
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014525 if (uss.mState != UserStartedState.STATE_STOPPING
14526 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014527 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014528 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014529
14530 long ident = Binder.clearCallingIdentity();
14531 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014532 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014533 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014534 // stop the user.
14535 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14536 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14537 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14538 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14539 // This is the result receiver for the final shutdown broadcast.
14540 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014541 @Override
14542 public void performReceive(Intent intent, int resultCode, String data,
14543 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14544 finishUserStop(uss);
14545 }
14546 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014547 // This is the result receiver for the initial stopping broadcast.
14548 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14549 @Override
14550 public void performReceive(Intent intent, int resultCode, String data,
14551 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14552 // On to the next.
14553 synchronized (ActivityManagerService.this) {
14554 if (uss.mState != UserStartedState.STATE_STOPPING) {
14555 // Whoops, we are being started back up. Abort, abort!
14556 return;
14557 }
14558 uss.mState = UserStartedState.STATE_SHUTDOWN;
14559 }
14560 broadcastIntentLocked(null, null, shutdownIntent,
14561 null, shutdownReceiver, 0, null, null, null,
14562 true, false, MY_PID, Process.SYSTEM_UID, userId);
14563 }
14564 };
14565 // Kick things off.
14566 broadcastIntentLocked(null, null, stoppingIntent,
14567 null, stoppingReceiver, 0, null, null,
14568 android.Manifest.permission.INTERACT_ACROSS_USERS,
14569 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014570 } finally {
14571 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014572 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014573 }
Amith Yamasani13593602012-03-22 16:16:17 -070014574
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014575 return ActivityManager.USER_OP_SUCCESS;
14576 }
14577
14578 void finishUserStop(UserStartedState uss) {
14579 final int userId = uss.mHandle.getIdentifier();
14580 boolean stopped;
14581 ArrayList<IStopUserCallback> callbacks;
14582 synchronized (this) {
14583 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014584 if (mStartedUsers.get(userId) != uss) {
14585 stopped = false;
14586 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014587 stopped = false;
14588 } else {
14589 stopped = true;
14590 // User can no longer run.
14591 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014592 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014593 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014594
14595 // Clean up all state and processes associated with the user.
14596 // Kill all the processes for the user.
14597 forceStopUserLocked(userId);
Dianne Hackbornbb4ca522012-12-03 14:09:06 -080014598 AttributeCache ac = AttributeCache.instance();
14599 if (ac != null) {
14600 ac.removeUser(userId);
14601 }
Amith Yamasani13593602012-03-22 16:16:17 -070014602 }
14603 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014604
14605 for (int i=0; i<callbacks.size(); i++) {
14606 try {
14607 if (stopped) callbacks.get(i).userStopped(userId);
14608 else callbacks.get(i).userStopAborted(userId);
14609 } catch (RemoteException e) {
14610 }
14611 }
14612 }
14613
14614 @Override
14615 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014616 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14617 != PackageManager.PERMISSION_GRANTED) && (
14618 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14619 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014620 String msg = "Permission Denial: getCurrentUser() from pid="
14621 + Binder.getCallingPid()
14622 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014623 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014624 Slog.w(TAG, msg);
14625 throw new SecurityException(msg);
14626 }
14627 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014628 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014629 }
Amith Yamasani13593602012-03-22 16:16:17 -070014630 }
14631
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014632 int getCurrentUserIdLocked() {
14633 return mCurrentUserId;
14634 }
14635
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014636 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014637 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014638 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14639 != PackageManager.PERMISSION_GRANTED) {
14640 String msg = "Permission Denial: isUserRunning() from pid="
14641 + Binder.getCallingPid()
14642 + ", uid=" + Binder.getCallingUid()
14643 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14644 Slog.w(TAG, msg);
14645 throw new SecurityException(msg);
14646 }
14647 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014648 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014649 }
14650 }
14651
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014652 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014653 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014654 if (state == null) {
14655 return false;
14656 }
14657 if (orStopped) {
14658 return true;
14659 }
14660 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014661 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014662 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014663
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014664 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014665 public int[] getRunningUserIds() {
14666 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14667 != PackageManager.PERMISSION_GRANTED) {
14668 String msg = "Permission Denial: isUserRunning() from pid="
14669 + Binder.getCallingPid()
14670 + ", uid=" + Binder.getCallingUid()
14671 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14672 Slog.w(TAG, msg);
14673 throw new SecurityException(msg);
14674 }
14675 synchronized (this) {
14676 return mStartedUserArray;
14677 }
14678 }
14679
14680 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014681 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014682 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014683 UserStartedState uss = mStartedUsers.valueAt(i);
14684 // This list does not include stopping users.
14685 if (uss.mState != UserStartedState.STATE_STOPPING
14686 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14687 num++;
14688 }
14689 }
14690 mStartedUserArray = new int[num];
14691 num = 0;
14692 for (int i=0; i<mStartedUsers.size(); i++) {
14693 UserStartedState uss = mStartedUsers.valueAt(i);
14694 if (uss.mState != UserStartedState.STATE_STOPPING
14695 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14696 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14697 num++;
14698 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014699 }
14700 }
14701
14702 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014703 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14704 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14705 != PackageManager.PERMISSION_GRANTED) {
14706 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14707 + Binder.getCallingPid()
14708 + ", uid=" + Binder.getCallingUid()
14709 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14710 Slog.w(TAG, msg);
14711 throw new SecurityException(msg);
14712 }
14713
14714 mUserSwitchObservers.register(observer);
14715 }
14716
14717 @Override
14718 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14719 mUserSwitchObservers.unregister(observer);
14720 }
14721
Dianne Hackborn1676c852012-09-10 14:52:30 -070014722 private boolean userExists(int userId) {
14723 if (userId == 0) {
14724 return true;
14725 }
14726 UserManagerService ums = getUserManagerLocked();
14727 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14728 }
14729
14730 int[] getUsersLocked() {
14731 UserManagerService ums = getUserManagerLocked();
14732 return ums != null ? ums.getUserIds() : new int[] { 0 };
14733 }
14734
14735 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014736 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014737 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14738 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014739 }
14740 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014741 }
14742
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014743 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014744 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014745
14746 throw new SecurityException("Caller uid=" + uid
14747 + " is not privileged to communicate with user=" + userId);
14748 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014749
14750 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014751 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014752 }
14753
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014754 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014755 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014756 ApplicationInfo newInfo = new ApplicationInfo(info);
14757 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014758 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14759 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014760 return newInfo;
14761 }
14762
14763 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014764 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014765 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014766 return aInfo;
14767 }
14768
14769 ActivityInfo info = new ActivityInfo(aInfo);
14770 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14771 return info;
14772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014773}